diff --git a/tasks/sp00nznet__ps3recomp-478/tests/test.sh b/tasks/sp00nznet__ps3recomp-478/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-478/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-478/tests/verifier.py b/tasks/sp00nznet__ps3recomp-478/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-478/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-482/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-482/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e58bcfa58777d72bba591f37e690838b686d5be --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-482/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-482/instruction.md b/tasks/sp00nznet__ps3recomp-482/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3d9174960e128950cd2f664a880b14547cfb397d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-482/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** rsx_fp_decompiler: divide texel coordinates of a 3D texture by its depth + +## Description + +`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. + +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. + +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. + +Tests: +- `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. +- `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. +- 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. + +No game data or program bytes are included. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-482/solution/patch.diff b/tasks/sp00nznet__ps3recomp-482/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..80609fad477bba92518d8af9d22a38aec7b0c46a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-482/solution/patch.diff @@ -0,0 +1,186 @@ +diff --git a/libs/video/rsx_draw_engine.c b/libs/video/rsx_draw_engine.c +index f99986b3..995c2cc2 100644 +--- a/libs/video/rsx_draw_engine.c ++++ b/libs/video/rsx_draw_engine.c +@@ -1369,18 +1369,19 @@ static u32 eng_vtex_mask(void) + * dim. No host sampling mode is unnormalised for these, so the fragment + * program divides the coordinates instead, and the divisor makes the sizes + * pipeline identity (rsx_live_draw.c keys them the same way). */ +-static u32 eng_unnorm_units(u32 dim[RSX_DSP_NUM_TEXTURES][2]) ++static u32 eng_unnorm_units(u32 dim[RSX_DSP_NUM_TEXTURES][3]) + { + u32 mask = 0; + for (u32 u = 0; u < RSX_DSP_NUM_TEXTURES; u++) { + rsx_dsp_texture t; + rsx_dsp_get_texture(&g.rsx, u, &t); +- dim[u][0] = dim[u][1] = 0; ++ dim[u][0] = dim[u][1] = dim[u][2] = 0; + if (!t.enabled || !(t.format & RSX_TEX_FMT_UNNORM) || !t.width || !t.height) + continue; + mask |= 1u << u; + dim[u][0] = t.width; + dim[u][1] = t.height; ++ dim[u][2] = t.depth; + } + return mask; + } +@@ -1662,14 +1663,14 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout, + for (u32 u = 0; u < RSX_DSP_NUM_TEXTURES; ++u) + if (!(expand_units & (1u << u))) expand_masks[u] = 0; + +- u32 unnorm_dim[RSX_DSP_NUM_TEXTURES][2]; ++ u32 unnorm_dim[RSX_DSP_NUM_TEXTURES][3]; + /* Shadow helpers normalize against the bound resource themselves. Only + * sampled ordinary UN units need baked dimensions or cache identity. */ + const u32 unnorm_mask = eng_unnorm_units(unnorm_dim) & + (fixed ? 0xFFFFu : sampled_units) & ~shadow_mask; + for (u32 u = 0; u < RSX_DSP_NUM_TEXTURES; u++) + if (!(unnorm_mask & (1u << u))) +- unnorm_dim[u][0] = unnorm_dim[u][1] = 0; ++ unnorm_dim[u][0] = unnorm_dim[u][1] = unnorm_dim[u][2] = 0; + + memset(&g.fp_constants, 0, sizeof g.fp_constants); + if (!fixed && rsx_fp_collect_constants(fp_uc, fp_size, &g.fp_constants) < 0) +@@ -1735,7 +1736,8 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout, + s_ps_hlsl, sizeof s_ps_hlsl, &nconst); + if (fi > 0 && nconst != g.fp_constants.count) fi = -1; + if (fi > 0 && rsx_fp_apply_unnorm_scale(s_ps_hlsl, sizeof s_ps_hlsl, unnorm_mask, +- (const u32 (*)[2])unnorm_dim, cube_mask) < 0) ++ (const u32 (*)[3])unnorm_dim, cube_mask, ++ vol_mask) < 0) + fi = -1; + if (fi > 0 && srgb_output && + rsx_fp_apply_srgb_output(s_ps_hlsl, sizeof s_ps_hlsl) < 0) +diff --git a/libs/video/rsx_fp_decompiler.c b/libs/video/rsx_fp_decompiler.c +index 5ce72ef6..ebdd14c0 100644 +--- a/libs/video/rsx_fp_decompiler.c ++++ b/libs/video/rsx_fp_decompiler.c +@@ -1655,10 +1655,12 @@ u32 rsx_fp_code_hash(const u8* ucode, u32 max_bytes) + * works this way, and leaves every non-UNNORM program byte-identical. + * + * Cube units are skipped: their coordinate is a float3 direction, and +- * RSX_TEX_FMT_UNNORM has no meaning for one. ++ * RSX_TEX_FMT_UNNORM has no meaning for one. A volume unit (Texture3D) is ++ * sampled with three coordinates, all in texels, so it is divided by its depth ++ * too (RPCS3's texture cache scales a 3D texture's r by 1/depth the same way). + */ + int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask, +- const u32 dim[][2], u32 cube_mask) ++ const u32 dim[][3], u32 cube_mask, u32 volume_mask) + { + if (!hlsl || !unnorm_mask) return 0; + int patched = 0; +@@ -1666,8 +1668,9 @@ int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask, + for (u32 u = 0; u < 16; u++) { + if (!((unnorm_mask >> u) & 1u)) continue; + if ((cube_mask >> u) & 1u) continue; +- const u32 w = dim[u][0], h = dim[u][1]; +- if (!w || !h) continue; ++ const u32 w = dim[u][0], h = dim[u][1], d = dim[u][2]; ++ const int volume = (volume_mask >> u) & 1u; ++ if (!w || !h || (volume && !d)) continue; + + /* Both spellings the emitter produces for a 2D unit. */ + char needles[2][40]; +@@ -1693,8 +1696,12 @@ int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask, + if (*p != ')') break; + + char scale[80]; +- snprintf(scale, sizeof scale, " * float2(%.9g, %.9g)", +- 1.0 / (double)w, 1.0 / (double)h); ++ if (volume) ++ snprintf(scale, sizeof scale, " * float3(%.9g, %.9g, %.9g)", ++ 1.0 / (double)w, 1.0 / (double)h, 1.0 / (double)d); ++ else ++ snprintf(scale, sizeof scale, " * float2(%.9g, %.9g)", ++ 1.0 / (double)w, 1.0 / (double)h); + const u32 slen = (u32)strlen(scale); + const u32 used = (u32)strlen(hlsl); + if (used + slen + 1 > hlsl_size) return -1; +diff --git a/libs/video/rsx_fp_decompiler.h b/libs/video/rsx_fp_decompiler.h +index 670e8863..b39968e7 100644 +--- a/libs/video/rsx_fp_decompiler.h ++++ b/libs/video/rsx_fp_decompiler.h +@@ -86,11 +86,12 @@ int rsx_fp_apply_alpha_test(char* hlsl, u32 out_size, u32 func, float ref); + float rsx_fp_alpha_ref(u32 raw, u32 surface_color_format); + + /* Scale texel-space (RSX_TEX_FMT_UNNORM) coordinates into HLSL's 0..1 range. +- * unnorm_mask selects the units; dim[u] gives that unit's {width, height}; +- * cube units are skipped. Returns the number of Sample sites patched, or -1 if ++ * unnorm_mask selects the units; dim[u] gives that unit's {width, height, ++ * depth}; cube units are skipped and volume_mask units (Texture3D) are divided ++ * by their depth as well. Returns the number of Sample sites patched, or -1 if + * the buffer would overflow. A no-op when unnorm_mask is 0. */ + int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask, +- const u32 dim[][2], u32 cube_mask); ++ const u32 dim[][3], u32 cube_mask, u32 volume_mask); + + /* Decode NV4097_SET_ALPHA_REF for the active surface color format. Ordinary + * integer render targets use the low 8 bits as UNORM8; W16Z16Y16X16 uses a +diff --git a/libs/video/rsx_live_draw.c b/libs/video/rsx_live_draw.c +index 2e65b8ee..3b7f0151 100644 +--- a/libs/video/rsx_live_draw.c ++++ b/libs/video/rsx_live_draw.c +@@ -4771,7 +4771,7 @@ static ID3D12PipelineState* get_pso( + * mode. The divisor is baked into the HLSL, so the sizes are part of the + * PSO identity and must be in the key. */ + u32 unnorm_mask = 0; +- u32 unnorm_dim[16][2] = {{0}}; ++ u32 unnorm_dim[16][3] = {{0}}; + for (u32 uu = 0; uu < 16; uu++) { + rsx_dsp_texture ut; rsx_dsp_get_texture(&g.rsx, uu, &ut); + if (!ut.enabled || !(ut.format & TEX_FMT_UNNORM)) continue; +@@ -4901,7 +4901,7 @@ static ID3D12PipelineState* get_pso( + fi = -1; + if (fi > 0) { + const int np = rsx_fp_apply_unnorm_scale( +- ps_hlsl, sizeof(ps_hlsl), unnorm_mask, unnorm_dim, cube_mask); ++ ps_hlsl, sizeof(ps_hlsl), unnorm_mask, unnorm_dim, cube_mask, 0u); + { static int n = 0; + if (PS3_LOG_FIRST(n, 8)) + fprintf(stderr, "[unnorm] mask=0x%X cube=0x%X dim0=%ux%u" +@@ -4921,7 +4921,7 @@ static ID3D12PipelineState* get_pso( + fi = -1; + if (fi > 0 && rsx_fp_apply_unnorm_scale( + ps_hlsl, sizeof(ps_hlsl), unnorm_mask, +- unnorm_dim, cube_mask) < 0) ++ unnorm_dim, cube_mask, 0u) < 0) + fi = -1; + } + #if defined(YZ_PERF_PROFILE) +diff --git a/libs/video/tests/test_shader_msl.c b/libs/video/tests/test_shader_msl.c +index de2a6dc6..017e9ddd 100644 +--- a/libs/video/tests/test_shader_msl.c ++++ b/libs/video/tests/test_shader_msl.c +@@ -19,6 +19,7 @@ + * what a character material does + * FP TEX r0, TC0 unit 0 (END) texture unit 0 sampled at texcoord0 + * FP TEX r0, TC0 unit 0, CUBE (END) ... with unit 0 a cube map ++ * FP TEX r0, TC0 unit 0, 3D UN (END) ... a volume addressed in texels + * VP MOV o0, v0 ; TXL o1, v8 (END) a vertex texture sampled at t16 + * FP MOV r0, COL0 ; MOV r2, COL0.zyxw two colour targets: what --mrt runs + * +@@ -364,6 +365,23 @@ int main(int argc, char** argv) + check("3D TEX FP MSL", g_msl, "texture3d"); + } + ++ /* ---- the same, with unnormalised (texel) coordinates ------------------ ++ * All three coordinates are texels and are divided by width, height and ++ * depth. A float2 scale on the float3 coordinate does not compile, and ++ * the pipeline was dropped: Resistance 3's 32x32x32 volume lookups. */ ++ { ++ u8 fp[16]; ++ rsx_test_fp_tex_r0_tc0(fp, 0); ++ rsx_fp_decompile_buffered_shadow_color_expand_vol_ex(fp, sizeof fp, 0x40u, 0, 1u, ++ NULL, NULL, NULL, g_hlsl, sizeof g_hlsl, NULL); ++ const u32 dim[16][3] = { { 8, 4, 2 } }; ++ check_count("3D UN TEX FP scale sites", ++ rsx_fp_apply_unnorm_scale(g_hlsl, sizeof g_hlsl, 1u, dim, 0, 1u), 1); ++ check("3D UN TEX FP HLSL", g_hlsl, ".xyz * float3(0.125, 0.25, 0.5))"); ++ if (translate("3D UN TEX FP", RSX_SHADER_STAGE_FRAGMENT) == 0) ++ check("3D UN TEX FP MSL", g_msl, "texture3d"); ++ } ++ + /* ---- fragment program: TEX r0, TC0 with EXP_TEX on a biased unit ----- + * The _bx2 fetch: the lanes the unit's biased remap names come back as + * x*2-1. The helper must survive glslang/spirv-cross intact. */ diff --git a/tasks/sp00nznet__ps3recomp-482/solution/solve.sh b/tasks/sp00nznet__ps3recomp-482/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-482/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-482/task.toml b/tasks/sp00nznet__ps3recomp-482/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..abdde0b26d74ed4221ca88c4dd7ae766ca4d984c --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-482/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-482" +description = "rsx_fp_decompiler: divide texel coordinates of a 3D texture by its depth" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "a6d76c895f77eb30b90a806c830544e61821b77f" +reference = "https://github.com/sp00nznet/ps3recomp/pull/482" +source_access = "auto" +built_at = "2026-11-16T16:09:59.867927+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1de209523f7c5ddf164253e0a9c67f985fddd6a058e41b81c5acee68b0aa4559" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-26T15:32:55Z" +diff_format = "unified" +context_files = [ + "libs/video/rsx_draw_engine.c", + "libs/video/rsx_fp_decompiler.c", + "libs/video/rsx_fp_decompiler.h", + "libs/video/rsx_live_draw.c", + "libs/video/tests/test_shader_msl.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 62 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.115301+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-482/tests/capture.py b/tasks/sp00nznet__ps3recomp-482/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-482/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-482/tests/instruction.md b/tasks/sp00nznet__ps3recomp-482/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3d9174960e128950cd2f664a880b14547cfb397d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-482/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** rsx_fp_decompiler: divide texel coordinates of a 3D texture by its depth + +## Description + +`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. + +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. + +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. + +Tests: +- `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. +- `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. +- 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. + +No game data or program bytes are included. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-482/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-482/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..80609fad477bba92518d8af9d22a38aec7b0c46a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-482/tests/oracle.patch @@ -0,0 +1,186 @@ +diff --git a/libs/video/rsx_draw_engine.c b/libs/video/rsx_draw_engine.c +index f99986b3..995c2cc2 100644 +--- a/libs/video/rsx_draw_engine.c ++++ b/libs/video/rsx_draw_engine.c +@@ -1369,18 +1369,19 @@ static u32 eng_vtex_mask(void) + * dim. No host sampling mode is unnormalised for these, so the fragment + * program divides the coordinates instead, and the divisor makes the sizes + * pipeline identity (rsx_live_draw.c keys them the same way). */ +-static u32 eng_unnorm_units(u32 dim[RSX_DSP_NUM_TEXTURES][2]) ++static u32 eng_unnorm_units(u32 dim[RSX_DSP_NUM_TEXTURES][3]) + { + u32 mask = 0; + for (u32 u = 0; u < RSX_DSP_NUM_TEXTURES; u++) { + rsx_dsp_texture t; + rsx_dsp_get_texture(&g.rsx, u, &t); +- dim[u][0] = dim[u][1] = 0; ++ dim[u][0] = dim[u][1] = dim[u][2] = 0; + if (!t.enabled || !(t.format & RSX_TEX_FMT_UNNORM) || !t.width || !t.height) + continue; + mask |= 1u << u; + dim[u][0] = t.width; + dim[u][1] = t.height; ++ dim[u][2] = t.depth; + } + return mask; + } +@@ -1662,14 +1663,14 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout, + for (u32 u = 0; u < RSX_DSP_NUM_TEXTURES; ++u) + if (!(expand_units & (1u << u))) expand_masks[u] = 0; + +- u32 unnorm_dim[RSX_DSP_NUM_TEXTURES][2]; ++ u32 unnorm_dim[RSX_DSP_NUM_TEXTURES][3]; + /* Shadow helpers normalize against the bound resource themselves. Only + * sampled ordinary UN units need baked dimensions or cache identity. */ + const u32 unnorm_mask = eng_unnorm_units(unnorm_dim) & + (fixed ? 0xFFFFu : sampled_units) & ~shadow_mask; + for (u32 u = 0; u < RSX_DSP_NUM_TEXTURES; u++) + if (!(unnorm_mask & (1u << u))) +- unnorm_dim[u][0] = unnorm_dim[u][1] = 0; ++ unnorm_dim[u][0] = unnorm_dim[u][1] = unnorm_dim[u][2] = 0; + + memset(&g.fp_constants, 0, sizeof g.fp_constants); + if (!fixed && rsx_fp_collect_constants(fp_uc, fp_size, &g.fp_constants) < 0) +@@ -1735,7 +1736,8 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout, + s_ps_hlsl, sizeof s_ps_hlsl, &nconst); + if (fi > 0 && nconst != g.fp_constants.count) fi = -1; + if (fi > 0 && rsx_fp_apply_unnorm_scale(s_ps_hlsl, sizeof s_ps_hlsl, unnorm_mask, +- (const u32 (*)[2])unnorm_dim, cube_mask) < 0) ++ (const u32 (*)[3])unnorm_dim, cube_mask, ++ vol_mask) < 0) + fi = -1; + if (fi > 0 && srgb_output && + rsx_fp_apply_srgb_output(s_ps_hlsl, sizeof s_ps_hlsl) < 0) +diff --git a/libs/video/rsx_fp_decompiler.c b/libs/video/rsx_fp_decompiler.c +index 5ce72ef6..ebdd14c0 100644 +--- a/libs/video/rsx_fp_decompiler.c ++++ b/libs/video/rsx_fp_decompiler.c +@@ -1655,10 +1655,12 @@ u32 rsx_fp_code_hash(const u8* ucode, u32 max_bytes) + * works this way, and leaves every non-UNNORM program byte-identical. + * + * Cube units are skipped: their coordinate is a float3 direction, and +- * RSX_TEX_FMT_UNNORM has no meaning for one. ++ * RSX_TEX_FMT_UNNORM has no meaning for one. A volume unit (Texture3D) is ++ * sampled with three coordinates, all in texels, so it is divided by its depth ++ * too (RPCS3's texture cache scales a 3D texture's r by 1/depth the same way). + */ + int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask, +- const u32 dim[][2], u32 cube_mask) ++ const u32 dim[][3], u32 cube_mask, u32 volume_mask) + { + if (!hlsl || !unnorm_mask) return 0; + int patched = 0; +@@ -1666,8 +1668,9 @@ int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask, + for (u32 u = 0; u < 16; u++) { + if (!((unnorm_mask >> u) & 1u)) continue; + if ((cube_mask >> u) & 1u) continue; +- const u32 w = dim[u][0], h = dim[u][1]; +- if (!w || !h) continue; ++ const u32 w = dim[u][0], h = dim[u][1], d = dim[u][2]; ++ const int volume = (volume_mask >> u) & 1u; ++ if (!w || !h || (volume && !d)) continue; + + /* Both spellings the emitter produces for a 2D unit. */ + char needles[2][40]; +@@ -1693,8 +1696,12 @@ int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask, + if (*p != ')') break; + + char scale[80]; +- snprintf(scale, sizeof scale, " * float2(%.9g, %.9g)", +- 1.0 / (double)w, 1.0 / (double)h); ++ if (volume) ++ snprintf(scale, sizeof scale, " * float3(%.9g, %.9g, %.9g)", ++ 1.0 / (double)w, 1.0 / (double)h, 1.0 / (double)d); ++ else ++ snprintf(scale, sizeof scale, " * float2(%.9g, %.9g)", ++ 1.0 / (double)w, 1.0 / (double)h); + const u32 slen = (u32)strlen(scale); + const u32 used = (u32)strlen(hlsl); + if (used + slen + 1 > hlsl_size) return -1; +diff --git a/libs/video/rsx_fp_decompiler.h b/libs/video/rsx_fp_decompiler.h +index 670e8863..b39968e7 100644 +--- a/libs/video/rsx_fp_decompiler.h ++++ b/libs/video/rsx_fp_decompiler.h +@@ -86,11 +86,12 @@ int rsx_fp_apply_alpha_test(char* hlsl, u32 out_size, u32 func, float ref); + float rsx_fp_alpha_ref(u32 raw, u32 surface_color_format); + + /* Scale texel-space (RSX_TEX_FMT_UNNORM) coordinates into HLSL's 0..1 range. +- * unnorm_mask selects the units; dim[u] gives that unit's {width, height}; +- * cube units are skipped. Returns the number of Sample sites patched, or -1 if ++ * unnorm_mask selects the units; dim[u] gives that unit's {width, height, ++ * depth}; cube units are skipped and volume_mask units (Texture3D) are divided ++ * by their depth as well. Returns the number of Sample sites patched, or -1 if + * the buffer would overflow. A no-op when unnorm_mask is 0. */ + int rsx_fp_apply_unnorm_scale(char* hlsl, u32 hlsl_size, u32 unnorm_mask, +- const u32 dim[][2], u32 cube_mask); ++ const u32 dim[][3], u32 cube_mask, u32 volume_mask); + + /* Decode NV4097_SET_ALPHA_REF for the active surface color format. Ordinary + * integer render targets use the low 8 bits as UNORM8; W16Z16Y16X16 uses a +diff --git a/libs/video/rsx_live_draw.c b/libs/video/rsx_live_draw.c +index 2e65b8ee..3b7f0151 100644 +--- a/libs/video/rsx_live_draw.c ++++ b/libs/video/rsx_live_draw.c +@@ -4771,7 +4771,7 @@ static ID3D12PipelineState* get_pso( + * mode. The divisor is baked into the HLSL, so the sizes are part of the + * PSO identity and must be in the key. */ + u32 unnorm_mask = 0; +- u32 unnorm_dim[16][2] = {{0}}; ++ u32 unnorm_dim[16][3] = {{0}}; + for (u32 uu = 0; uu < 16; uu++) { + rsx_dsp_texture ut; rsx_dsp_get_texture(&g.rsx, uu, &ut); + if (!ut.enabled || !(ut.format & TEX_FMT_UNNORM)) continue; +@@ -4901,7 +4901,7 @@ static ID3D12PipelineState* get_pso( + fi = -1; + if (fi > 0) { + const int np = rsx_fp_apply_unnorm_scale( +- ps_hlsl, sizeof(ps_hlsl), unnorm_mask, unnorm_dim, cube_mask); ++ ps_hlsl, sizeof(ps_hlsl), unnorm_mask, unnorm_dim, cube_mask, 0u); + { static int n = 0; + if (PS3_LOG_FIRST(n, 8)) + fprintf(stderr, "[unnorm] mask=0x%X cube=0x%X dim0=%ux%u" +@@ -4921,7 +4921,7 @@ static ID3D12PipelineState* get_pso( + fi = -1; + if (fi > 0 && rsx_fp_apply_unnorm_scale( + ps_hlsl, sizeof(ps_hlsl), unnorm_mask, +- unnorm_dim, cube_mask) < 0) ++ unnorm_dim, cube_mask, 0u) < 0) + fi = -1; + } + #if defined(YZ_PERF_PROFILE) +diff --git a/libs/video/tests/test_shader_msl.c b/libs/video/tests/test_shader_msl.c +index de2a6dc6..017e9ddd 100644 +--- a/libs/video/tests/test_shader_msl.c ++++ b/libs/video/tests/test_shader_msl.c +@@ -19,6 +19,7 @@ + * what a character material does + * FP TEX r0, TC0 unit 0 (END) texture unit 0 sampled at texcoord0 + * FP TEX r0, TC0 unit 0, CUBE (END) ... with unit 0 a cube map ++ * FP TEX r0, TC0 unit 0, 3D UN (END) ... a volume addressed in texels + * VP MOV o0, v0 ; TXL o1, v8 (END) a vertex texture sampled at t16 + * FP MOV r0, COL0 ; MOV r2, COL0.zyxw two colour targets: what --mrt runs + * +@@ -364,6 +365,23 @@ int main(int argc, char** argv) + check("3D TEX FP MSL", g_msl, "texture3d"); + } + ++ /* ---- the same, with unnormalised (texel) coordinates ------------------ ++ * All three coordinates are texels and are divided by width, height and ++ * depth. A float2 scale on the float3 coordinate does not compile, and ++ * the pipeline was dropped: Resistance 3's 32x32x32 volume lookups. */ ++ { ++ u8 fp[16]; ++ rsx_test_fp_tex_r0_tc0(fp, 0); ++ rsx_fp_decompile_buffered_shadow_color_expand_vol_ex(fp, sizeof fp, 0x40u, 0, 1u, ++ NULL, NULL, NULL, g_hlsl, sizeof g_hlsl, NULL); ++ const u32 dim[16][3] = { { 8, 4, 2 } }; ++ check_count("3D UN TEX FP scale sites", ++ rsx_fp_apply_unnorm_scale(g_hlsl, sizeof g_hlsl, 1u, dim, 0, 1u), 1); ++ check("3D UN TEX FP HLSL", g_hlsl, ".xyz * float3(0.125, 0.25, 0.5))"); ++ if (translate("3D UN TEX FP", RSX_SHADER_STAGE_FRAGMENT) == 0) ++ check("3D UN TEX FP MSL", g_msl, "texture3d"); ++ } ++ + /* ---- fragment program: TEX r0, TC0 with EXP_TEX on a biased unit ----- + * The _bx2 fetch: the lanes the unit's biased remap names come back as + * x*2-1. The helper must survive glslang/spirv-cross intact. */ diff --git a/tasks/sp00nznet__ps3recomp-482/tests/test.sh b/tasks/sp00nznet__ps3recomp-482/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-482/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-482/tests/verifier.py b/tasks/sp00nznet__ps3recomp-482/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-482/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-484/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-484/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e58bcfa58777d72bba591f37e690838b686d5be --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-484/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-484/instruction.md b/tasks/sp00nznet__ps3recomp-484/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cafcdd3054f0bffd4e1e73bbf062a5463bfa90bc --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-484/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** spu: copy only the reserved lines of a PUT under the lock-line lock + +## Description + +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. + +This PR, for a span of two or more lines that touches a reserved line: + +- **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). +- **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. +- **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. + +A single-line span keeps the single locked copy. + +### Ordering + +- 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. +- 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. +- 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. + +### Test + +`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. + +### Measurements + +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. + +### Validation (macOS ARM64, base `a6d76c895f77eb30b90a806c830544e61821b77f`) + +- 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. +- 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. +- 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. + +The patch contains no original program bytes or application-specific data. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-484/solution/patch.diff b/tasks/sp00nznet__ps3recomp-484/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7605c3a024c9cc19c2e0db8b91d7bf9afa60cce8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-484/solution/patch.diff @@ -0,0 +1,110 @@ +diff --git a/runtime/spu/spu_dma.h b/runtime/spu/spu_dma.h +index 7b0debec..ba238440 100644 +--- a/runtime/spu/spu_dma.h ++++ b/runtime/spu/spu_dma.h +@@ -652,10 +652,18 @@ static inline int mfc_do_transfer(spu_context* spu, uint32_t lsa, uint64_t ea, + * snapshot against a line this copy has already replaced and commits + * over it, and a peer parked on RdEventStat sleeps through the write. + * +- * So when the span touches a reserved line the copy and the notify run +- * as ONE critical section under the lock-line lock -- the same contract +- * the PPU store path and the PUTLLC commit keep, and the only way the +- * copy cannot land inside a peer's compare-and-commit window. Spans ++ * So a reserved line's copy and its notify run as ONE critical section ++ * under the lock-line lock -- the same contract the PPU store path and ++ * the PUTLLC commit keep, and the only way the copy cannot land inside ++ * a peer's compare-and-commit window. Only the reserved lines need it: ++ * in a multi-line span the others are copied first, without the lock, ++ * exactly as an unreserved span is, and the locked pass then copies the ++ * lines it skipped and notifies every reserved one. A line reserved ++ * after its unlocked copy is notified there but NOT copied again: a ++ * peer may already have reserved and committed it on top of our bytes, ++ * and a second copy would write that commit back over. A wide PUT that ++ * touches one queue line no longer holds every other SPU's atomics off ++ * for the whole copy. Spans + * that touch no reserved line keep the lock-free copy: bulk asset PUTs + * are large and hot, and the scan is a bitmap bit per 128 bytes against + * a global that stays zero until an SPU reserves its first line. +@@ -679,7 +687,34 @@ static inline int mfc_do_transfer(spu_context* spu, uint32_t lsa, uint64_t ea, + if (spu_coh_is_reserved(a)) { span_reserved = 1; break; } + if (a == a1) break; + } +- if (span_reserved) { ++ /* Lines the unlocked pass left for the locked one: a 16 KiB ++ * transfer spans at most 129 lines. */ ++ uint64_t locked_lines[3] = {0, 0, 0}; ++ if (span_reserved && a0 != a1 && ((a1 - a0) >> 7) < 64u * 3u) { ++ const uint32_t ea32 = (uint32_t)ea; ++ uint32_t i = 0; ++ for (uint32_t a = a0; ; a += 128u, i++) { ++ const uint32_t lo = a > ea32 ? a - ea32 : 0u; ++ const uint32_t hi = a + 128u - ea32 < size ? a + 128u - ea32 : size; ++ if (spu_coh_is_reserved(a)) locked_lines[i >> 6] |= 1ull << (i & 63u); ++ else memcpy(ea_ptr + lo, ls_ptr + lo, hi - lo); ++ if (a == a1) break; ++ } ++ spu_lockline_lock(); ++ i = 0; ++ for (uint32_t a = a0; ; a += 128u, i++) { ++ const uint32_t lo = a > ea32 ? a - ea32 : 0u; ++ const uint32_t hi = a + 128u - ea32 < size ? a + 128u - ea32 : size; ++ if ((locked_lines[i >> 6] >> (i & 63u)) & 1u) { ++ memcpy(ea_ptr + lo, ls_ptr + lo, hi - lo); ++ spu_coh_notify_write_except(a, spu); ++ } else if (spu_coh_is_reserved(a)) { ++ spu_coh_notify_write_except(a, spu); /* reserved after its copy */ ++ } ++ if (a == a1) break; ++ } ++ spu_lockline_unlock(); ++ } else if (span_reserved) { + spu_lockline_lock(); + memcpy(ea_ptr, ls_ptr, size); + for (uint32_t a = a0; ; a += 128u) { +diff --git a/runtime/spu/tests/test_spu_lockline_peer.c b/runtime/spu/tests/test_spu_lockline_peer.c +index 4bf08693..f945ab0b 100644 +--- a/runtime/spu/tests/test_spu_lockline_peer.c ++++ b/runtime/spu/tests/test_spu_lockline_peer.c +@@ -347,6 +347,34 @@ static void test_wide_put_finds_the_reserved_line(void) + CHECK(mem_is(LINE_D, 0xB0, 0x200)); + } + ++/* The reserved line is copied under the lock and the rest of the span outside ++ * it, so the partial first and last lines are their own pieces: each has to ++ * land exactly, and nothing either side of the span may move. */ ++static void test_unaligned_wide_put_around_a_reserved_line(void) ++{ ++ reset_pair(); ++ memset(g_guest_mem + LINE_D, 0xEE, 0x200); ++ unsigned long raised = g_spu_lr_raise; ++ ++ spu_atomic(&g_a, LSA_A, LINE_D + 0x80, MFC_GETLLAR_CMD); /* the middle line */ ++ ++ TEST("an unaligned PUT over a reserved line raises once"); ++ stage(&g_b, LSA_B, 0xC0, 0x100); ++ spu_put(&g_b, LSA_B, LINE_D + 0x40, 0x100); ++ CHECK_EQ_U32(g_a.event_status & SPU_EVENT_LR, SPU_EVENT_LR); ++ CHECK(g_a.resv_valid == 0); ++ CHECK(g_spu_lr_raise == raised + 1); ++ ++ TEST("...the span landed, partial lines included"); ++ CHECK(mem_is(LINE_D + 0x40, 0xC0, 0x100)); ++ ++ TEST("...and the bytes either side of it did not move"); ++ int untouched = 1; ++ for (uint32_t i = 0; i < 0x40; i++) untouched &= g_guest_mem[LINE_D + i] == 0xEE; ++ for (uint32_t i = 0x140; i < 0x200; i++) untouched &= g_guest_mem[LINE_D + i] == 0xEE; ++ CHECK(untouched); ++} ++ + /* =========================================================================== + * The event acknowledge against a concurrent raise + * +@@ -426,6 +454,7 @@ int main(void) + test_plain_put_breaks_peer(); + test_plain_put_elsewhere_is_quiet(); + test_wide_put_finds_the_reserved_line(); ++ test_unaligned_wide_put_around_a_reserved_line(); + test_ack_keeps_a_concurrent_raise(); + + printf("\nSPU-to-SPU lock-line coherence tests: %d passed, %d failed\n", diff --git a/tasks/sp00nznet__ps3recomp-484/solution/solve.sh b/tasks/sp00nznet__ps3recomp-484/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-484/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-484/task.toml b/tasks/sp00nznet__ps3recomp-484/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..76e2fa7025f2bb010633601f24accd87f0ba5d04 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-484/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-484" +description = "spu: copy only the reserved lines of a PUT under the lock-line lock" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "a6d76c895f77eb30b90a806c830544e61821b77f" +reference = "https://github.com/sp00nznet/ps3recomp/pull/484" +source_access = "auto" +built_at = "2026-11-16T16:09:59.866082+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:26a2d0ba86766d15592e7870890b4e7ea99502098f1a6141bfeea33830ecd057" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-26T15:32:55Z" +diff_format = "unified" +context_files = [ + "runtime/spu/spu_dma.h", + "runtime/spu/tests/test_spu_lockline_peer.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 74 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.115843+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-484/tests/capture.py b/tasks/sp00nznet__ps3recomp-484/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-484/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-484/tests/instruction.md b/tasks/sp00nznet__ps3recomp-484/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cafcdd3054f0bffd4e1e73bbf062a5463bfa90bc --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-484/tests/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** spu: copy only the reserved lines of a PUT under the lock-line lock + +## Description + +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. + +This PR, for a span of two or more lines that touches a reserved line: + +- **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). +- **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. +- **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. + +A single-line span keeps the single locked copy. + +### Ordering + +- 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. +- 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. +- 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. + +### Test + +`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. + +### Measurements + +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. + +### Validation (macOS ARM64, base `a6d76c895f77eb30b90a806c830544e61821b77f`) + +- 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. +- 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. +- 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. + +The patch contains no original program bytes or application-specific data. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-484/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-484/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7605c3a024c9cc19c2e0db8b91d7bf9afa60cce8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-484/tests/oracle.patch @@ -0,0 +1,110 @@ +diff --git a/runtime/spu/spu_dma.h b/runtime/spu/spu_dma.h +index 7b0debec..ba238440 100644 +--- a/runtime/spu/spu_dma.h ++++ b/runtime/spu/spu_dma.h +@@ -652,10 +652,18 @@ static inline int mfc_do_transfer(spu_context* spu, uint32_t lsa, uint64_t ea, + * snapshot against a line this copy has already replaced and commits + * over it, and a peer parked on RdEventStat sleeps through the write. + * +- * So when the span touches a reserved line the copy and the notify run +- * as ONE critical section under the lock-line lock -- the same contract +- * the PPU store path and the PUTLLC commit keep, and the only way the +- * copy cannot land inside a peer's compare-and-commit window. Spans ++ * So a reserved line's copy and its notify run as ONE critical section ++ * under the lock-line lock -- the same contract the PPU store path and ++ * the PUTLLC commit keep, and the only way the copy cannot land inside ++ * a peer's compare-and-commit window. Only the reserved lines need it: ++ * in a multi-line span the others are copied first, without the lock, ++ * exactly as an unreserved span is, and the locked pass then copies the ++ * lines it skipped and notifies every reserved one. A line reserved ++ * after its unlocked copy is notified there but NOT copied again: a ++ * peer may already have reserved and committed it on top of our bytes, ++ * and a second copy would write that commit back over. A wide PUT that ++ * touches one queue line no longer holds every other SPU's atomics off ++ * for the whole copy. Spans + * that touch no reserved line keep the lock-free copy: bulk asset PUTs + * are large and hot, and the scan is a bitmap bit per 128 bytes against + * a global that stays zero until an SPU reserves its first line. +@@ -679,7 +687,34 @@ static inline int mfc_do_transfer(spu_context* spu, uint32_t lsa, uint64_t ea, + if (spu_coh_is_reserved(a)) { span_reserved = 1; break; } + if (a == a1) break; + } +- if (span_reserved) { ++ /* Lines the unlocked pass left for the locked one: a 16 KiB ++ * transfer spans at most 129 lines. */ ++ uint64_t locked_lines[3] = {0, 0, 0}; ++ if (span_reserved && a0 != a1 && ((a1 - a0) >> 7) < 64u * 3u) { ++ const uint32_t ea32 = (uint32_t)ea; ++ uint32_t i = 0; ++ for (uint32_t a = a0; ; a += 128u, i++) { ++ const uint32_t lo = a > ea32 ? a - ea32 : 0u; ++ const uint32_t hi = a + 128u - ea32 < size ? a + 128u - ea32 : size; ++ if (spu_coh_is_reserved(a)) locked_lines[i >> 6] |= 1ull << (i & 63u); ++ else memcpy(ea_ptr + lo, ls_ptr + lo, hi - lo); ++ if (a == a1) break; ++ } ++ spu_lockline_lock(); ++ i = 0; ++ for (uint32_t a = a0; ; a += 128u, i++) { ++ const uint32_t lo = a > ea32 ? a - ea32 : 0u; ++ const uint32_t hi = a + 128u - ea32 < size ? a + 128u - ea32 : size; ++ if ((locked_lines[i >> 6] >> (i & 63u)) & 1u) { ++ memcpy(ea_ptr + lo, ls_ptr + lo, hi - lo); ++ spu_coh_notify_write_except(a, spu); ++ } else if (spu_coh_is_reserved(a)) { ++ spu_coh_notify_write_except(a, spu); /* reserved after its copy */ ++ } ++ if (a == a1) break; ++ } ++ spu_lockline_unlock(); ++ } else if (span_reserved) { + spu_lockline_lock(); + memcpy(ea_ptr, ls_ptr, size); + for (uint32_t a = a0; ; a += 128u) { +diff --git a/runtime/spu/tests/test_spu_lockline_peer.c b/runtime/spu/tests/test_spu_lockline_peer.c +index 4bf08693..f945ab0b 100644 +--- a/runtime/spu/tests/test_spu_lockline_peer.c ++++ b/runtime/spu/tests/test_spu_lockline_peer.c +@@ -347,6 +347,34 @@ static void test_wide_put_finds_the_reserved_line(void) + CHECK(mem_is(LINE_D, 0xB0, 0x200)); + } + ++/* The reserved line is copied under the lock and the rest of the span outside ++ * it, so the partial first and last lines are their own pieces: each has to ++ * land exactly, and nothing either side of the span may move. */ ++static void test_unaligned_wide_put_around_a_reserved_line(void) ++{ ++ reset_pair(); ++ memset(g_guest_mem + LINE_D, 0xEE, 0x200); ++ unsigned long raised = g_spu_lr_raise; ++ ++ spu_atomic(&g_a, LSA_A, LINE_D + 0x80, MFC_GETLLAR_CMD); /* the middle line */ ++ ++ TEST("an unaligned PUT over a reserved line raises once"); ++ stage(&g_b, LSA_B, 0xC0, 0x100); ++ spu_put(&g_b, LSA_B, LINE_D + 0x40, 0x100); ++ CHECK_EQ_U32(g_a.event_status & SPU_EVENT_LR, SPU_EVENT_LR); ++ CHECK(g_a.resv_valid == 0); ++ CHECK(g_spu_lr_raise == raised + 1); ++ ++ TEST("...the span landed, partial lines included"); ++ CHECK(mem_is(LINE_D + 0x40, 0xC0, 0x100)); ++ ++ TEST("...and the bytes either side of it did not move"); ++ int untouched = 1; ++ for (uint32_t i = 0; i < 0x40; i++) untouched &= g_guest_mem[LINE_D + i] == 0xEE; ++ for (uint32_t i = 0x140; i < 0x200; i++) untouched &= g_guest_mem[LINE_D + i] == 0xEE; ++ CHECK(untouched); ++} ++ + /* =========================================================================== + * The event acknowledge against a concurrent raise + * +@@ -426,6 +454,7 @@ int main(void) + test_plain_put_breaks_peer(); + test_plain_put_elsewhere_is_quiet(); + test_wide_put_finds_the_reserved_line(); ++ test_unaligned_wide_put_around_a_reserved_line(); + test_ack_keeps_a_concurrent_raise(); + + printf("\nSPU-to-SPU lock-line coherence tests: %d passed, %d failed\n", diff --git a/tasks/sp00nznet__ps3recomp-484/tests/test.sh b/tasks/sp00nznet__ps3recomp-484/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-484/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-484/tests/verifier.py b/tasks/sp00nznet__ps3recomp-484/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-484/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-485/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-485/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e58bcfa58777d72bba591f37e690838b686d5be --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-485/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-485/instruction.md b/tasks/sp00nznet__ps3recomp-485/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d97bda4b4a5fb513a7dafceeeaf0f3f0ec70dd58 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-485/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** rsx_vp_decompiler: branch on the transform branch bits; leaders up to slot 544 + +## Description + +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. + +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. + +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. + +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. + +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. + +Tests: +- `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. +- `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. +- In-game on Metal: no more dropped pipelines, and the glows and light shafts show up as on the console. + +No game data or program bytes are included. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-485/solution/patch.diff b/tasks/sp00nznet__ps3recomp-485/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8876101b75b427ccbbba473b3ecacb1254e60215 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-485/solution/patch.diff @@ -0,0 +1,256 @@ +diff --git a/libs/video/rsx_draw_engine.c b/libs/video/rsx_draw_engine.c +index f99986b3..4a02779b 100644 +--- a/libs/video/rsx_draw_engine.c ++++ b/libs/video/rsx_draw_engine.c +@@ -1631,6 +1631,10 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout, + const u32 cube_mask = eng_cube_mask(); + const u32 vol_mask = eng_volume_mask(); + const u32 vtex_mask = eng_vtex_mask(); ++ /* BRB/CLB outcomes are baked into the program: the branch bits are ++ * identity only for a program that tests them. */ ++ const int vp_branch_bits_used = !fixed && rsx_vp_uses_branch_bits(vp_uc, vp_instrs * 16u); ++ const u32 vp_branch_bits = vp_branch_bits_used ? rsx_dsp_reg(&g.rsx, 0x1FF8u) : 0; + rsx_fp_shadow_desc shadow[RSX_DSP_NUM_TEXTURES] = {{0}}; + u32 shadow_mask = 0; + const u32 sampled_units = fixed ? 0 : rsx_fp_texture_units(fp_uc, fp_size); +@@ -1686,6 +1690,7 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout, + key = eng_fnv1a(&fixed_tag, sizeof fixed_tag, key); + } else { + key = eng_fnv1a(vp_uc, vp_instrs * 16u, key); ++ if (vp_branch_bits_used) key = eng_fnv1a(&vp_branch_bits, sizeof vp_branch_bits, key); + key = rsx_fp_structural_hash(fp_uc, fp_size, key); + if (!key) return 0; + const u32 fp_ctrl_key = fp_ctrl & 0x4Eu; /* colour width and fragment depth export */ +@@ -1727,6 +1732,7 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout, + snprintf(s_vs_hlsl, sizeof s_vs_hlsl, "%s", kEngFixedVS); + snprintf(s_ps_hlsl, sizeof s_ps_hlsl, "%s", kEngFixedPS); + } else { ++ rsx_vp_set_branch_bits(vp_branch_bits); + vi = rsx_vp_decompile_compact_ex(vp_uc, vp_instrs * 16u, vtex_mask, + layout->mask, s_vs_hlsl, + sizeof s_vs_hlsl); +diff --git a/libs/video/rsx_live_draw.c b/libs/video/rsx_live_draw.c +index 2e65b8ee..54fdffd9 100644 +--- a/libs/video/rsx_live_draw.c ++++ b/libs/video/rsx_live_draw.c +@@ -4766,6 +4766,11 @@ static ID3D12PipelineState* get_pso( + key = fnv1a(&fp_ctrl_key, sizeof(fp_ctrl_key), key); + key = fnv1a(&cube_mask, sizeof(cube_mask), key); + key = fnv1a(&vtex_mask, sizeof(vtex_mask), key); ++ /* BRB/CLB outcomes are baked into the program (rsx_vp_set_branch_bits). */ ++ const int vp_branch_bits_used = rsx_vp_uses_branch_bits(vp_uc, vp_instrs * 16); ++ const u32 vp_branch_bits = vp_branch_bits_used ? rsx_dsp_reg(&g.rsx, 0x1FF8u) : 0; ++ if (vp_branch_bits_used) ++ key = fnv1a(&vp_branch_bits, sizeof(vp_branch_bits), key); + /* Texel-addressed (RSX_TEX_FMT_UNNORM) units need their coordinates divided + * by the texture size in the shader -- D3D12 has no unnormalised addressing + * mode. The divisor is baked into the HLSL, so the sizes are part of the +@@ -4880,6 +4885,7 @@ static ID3D12PipelineState* get_pso( + const LONGLONG decompile_begin = ld_profile_qpc(); + #endif + rsx_vp_set_branch_base(rsx_dsp_vp_start(&g.rsx)); ++ rsx_vp_set_branch_bits(vp_branch_bits); + const int vi = masked_layout + ? rsx_vp_decompile_compact_ex( + vp_uc, vp_instrs * 16, vtex_mask, masked_layout->mask, +diff --git a/libs/video/rsx_vp_decompiler.c b/libs/video/rsx_vp_decompiler.c +index b9ed32be..4547280b 100644 +--- a/libs/video/rsx_vp_decompiler.c ++++ b/libs/video/rsx_vp_decompiler.c +@@ -132,11 +132,27 @@ static void emit_store(Out* b, const char* dst_fmt, u32 idx, const char* m) + } + + /* ---- flow control -------------------------------------------------------- */ +-#define RSX_VP_MAX_INSTR 512 ++/* The transform program memory holds 544 slots (RSX_DSP_VP_INSTR), not 512: ++ * a branch target or block leader past slot 511 must still open a block. */ ++#define RSX_VP_MAX_INSTR 544 + + static u32 s_vp_branch_base = 0; /* VP slot the program being decompiled starts at */ + void rsx_vp_set_branch_base(u32 start_slot) { s_vp_branch_base = start_slot; } + ++static u32 s_vp_branch_bits = 0; /* SET_TRANSFORM_BRANCH_BITS, tested by BRB/CLB */ ++void rsx_vp_set_branch_bits(u32 bits) { s_vp_branch_bits = bits; } ++ ++int rsx_vp_uses_branch_bits(const u8* ucode, u32 max_bytes) ++{ ++ if (!ucode) return 0; ++ for (u32 off = 0; off + 16 <= max_bytes; off += 16) { ++ const u32 sca_op = (rd_le(ucode + off + 4) >> 27) & 0x1Fu; ++ if (sca_op == 0x11 || sca_op == 0x12) return 1; /* BRB, CLB */ ++ if (rd_le(ucode + off + 12) & 1u) break; /* D3.end */ ++ } ++ return 0; ++} ++ + /* BRA BRI CAL CLI RET BRB CLB (scalar opcodes). */ + static int vp_is_flow(u32 sca_op) + { +@@ -500,10 +516,20 @@ static int rsx_vp_decompile_impl( + snprintf(flow_term, sizeof flow_term, + " if (%s) { if (_csp > 0) { _csp--; _pc = _cs[_csp]; } else _pc = -1; } else _pc = %d;\n", + c, next); +- else { /* BRB/CLB: boolean-register branches */ +- n_flow_skipped++; +- snprintf(flow_term, sizeof flow_term, +- " _pc = %d; /* TODO: %s not modelled */\n", next, rsx_vp_sca_name(sca_op)); ++ else { /* BRB, CLB */ ++ /* A boolean branch tests bit D3[23:27] of the transform ++ * branch bits against D3[28] and ignores the CC condition ++ * (RPCS3's GetOptionalBranchCond). The bits are baked in: ++ * the caller keys the program on them. */ ++ const u32 bit = (s_vp_branch_bits >> ((d3 >> 23) & 0x1Fu)) & 1u; ++ const int taken = bit == ((d3 >> 28) & 1u); ++ if (!taken) ++ snprintf(flow_term, sizeof flow_term, " _pc = %d;\n", next); ++ else if (sca_op == 0x11) ++ snprintf(flow_term, sizeof flow_term, " _pc = %u;\n", tgt); ++ else ++ snprintf(flow_term, sizeof flow_term, ++ " _cs[_csp] = %d; _csp = min(_csp + 1, 7); _pc = %u;\n", next, tgt); + } + } + /* ---- scalar ALU (reads SRC2) ---- */ +diff --git a/libs/video/rsx_vp_decompiler.h b/libs/video/rsx_vp_decompiler.h +index ecc53fce..9310c482 100644 +--- a/libs/video/rsx_vp_decompiler.h ++++ b/libs/video/rsx_vp_decompiler.h +@@ -57,6 +57,12 @@ int rsx_vp_decompile(const u8* ucode, u32 max_bytes, char* out, u32 out_size); + * to the ucode pointer handed in. Defaults to 0. */ + void rsx_vp_set_branch_base(u32 start_slot); + ++/* SET_TRANSFORM_BRANCH_BITS for the next program decompiled. BRB and CLB ++ * branch on one of these bits; the decompiler bakes the outcome in, so a ++ * program that rsx_vp_uses_branch_bits() must be keyed on them too. */ ++void rsx_vp_set_branch_bits(u32 bits); ++int rsx_vp_uses_branch_bits(const u8* ucode, u32 max_bytes); ++ + /* Bit N in vtex_mask declares NV40 2D vertex-texture unit N at t(16+N), + * sampler sN, and turns TXL for that unit into SampleLevel(..., LOD 0). + * Unmasked units retain the defined-zero fallback. */ +diff --git a/libs/video/tests/test_shader_msl.c b/libs/video/tests/test_shader_msl.c +index de2a6dc6..293386e2 100644 +--- a/libs/video/tests/test_shader_msl.c ++++ b/libs/video/tests/test_shader_msl.c +@@ -20,6 +20,8 @@ + * FP TEX r0, TC0 unit 0 (END) texture unit 0 sampled at texcoord0 + * FP TEX r0, TC0 unit 0, CUBE (END) ... with unit 0 a cube map + * VP MOV o0, v0 ; TXL o1, v8 (END) a vertex texture sampled at t16 ++ * VP 519 slots, BRI past slot 512 a long effects program's branches ++ * VP BRB, CLB on transform branch bits its optional paths + * FP MOV r0, COL0 ; MOV r2, COL0.zyxw two colour targets: what --mrt runs + * + * Each program's HLSL is checked for what was meant before the MSL is looked +@@ -70,8 +72,23 @@ static void check_count(const char* what, int got, int want) + + /* ---- the translation step, shared by every case -------------------------- */ + +-static char g_hlsl[65536]; +-static char g_msl[65536]; ++static char g_hlsl[262144]; ++static char g_msl[262144]; ++static u8 g_long_vp[519 * 16]; /* the 519-slot program; also has no BRB/CLB */ ++ ++/* Flow instruction `sca_op` (0x09 BRI, 0x11 BRB, 0x12 CLB) to VP slot ++ * `target`: cond [10:12] = 7 (TR), the target split over D0[23], D2[0:5] and ++ * D3[29:31]; a boolean branch tests branch bit `bit` (D3[23:27]) for ++ * `if_set` (D3[28]). No ALU writes. */ ++static void vp_branch(u8* p, u32 sca_op, u32 target, u32 bit, u32 if_set) ++{ ++ const u32 d0 = (0x3Fu << 15) | (7u << 10) | (((target >> 9) & 1u) << 23); ++ const u32 d1 = sca_op << 27; ++ const u32 d2 = (target >> 3) & 0x3Fu; ++ const u32 d3 = (0x3Fu << 7) | (bit << 23) | (if_set << 28) | ((target & 7u) << 29); ++ rsx_test_put_le32(p + 0, d0); rsx_test_put_le32(p + 4, d1); ++ rsx_test_put_le32(p + 8, d2); rsx_test_put_le32(p + 12, d3); ++} + static char g_log[4096]; + + static int translate(const char* what, int stage) +@@ -129,6 +146,86 @@ int main(int argc, char** argv) + } + } + ++ /* ---- vertex program: branches past slot 512 ------------------------------ ++ * The transform program memory has 544 slots. A branching program is ++ * emitted as one "if (_pc == N)" block per leader; a leader past slot 511 ++ * opened no block, so every later branch closed a block that was never ++ * opened and main() ended early. A 543-slot effects program failed that ++ * way and every draw using it was dropped. */ ++ { ++ u8* vp = g_long_vp; ++ for (u32 i = 0; i < 513; i++) ++ rsx_test_vp_mov_out(vp + i * 16, 0, RSX_TEST_VP_SWZ_IDENT, 0, 0); /* MOV o0, v0 */ ++ vp_branch(vp + 513 * 16, 0x09, 515, 0, 0); ++ rsx_test_vp_mov_out(vp + 514 * 16, 3, RSX_TEST_VP_SWZ_IDENT, 1, 0); /* skipped */ ++ rsx_test_vp_mov_out(vp + 515 * 16, 1, RSX_TEST_VP_SWZ_IDENT, 1, 0); /* MOV o1, v1 */ ++ vp_branch(vp + 516 * 16, 0x09, 518, 0, 0); ++ rsx_test_vp_mov_out(vp + 517 * 16, 3, RSX_TEST_VP_SWZ_IDENT, 2, 0); /* skipped */ ++ rsx_test_vp_mov_out(vp + 518 * 16, 2, RSX_TEST_VP_SWZ_IDENT, 2, 1); /* MOV o2, v2, END */ ++ rsx_vp_set_branch_base(0); ++ if (rsx_vp_decompile(vp, sizeof g_long_vp, g_hlsl, sizeof g_hlsl) > 0) { ++ check("long VP HLSL", g_hlsl, "if (_pc == 514) {"); ++ check("long VP HLSL", g_hlsl, "if (_pc == 515) {"); ++ check("long VP HLSL", g_hlsl, "if (_pc == 518) {"); ++ if (translate("long VP", RSX_SHADER_STAGE_VERTEX) == 0) ++ check("long VP MSL", g_msl, "vertex "); ++ } else { ++ printf("[FAIL] long VP -- decompile failed\n"); ++ g_fail++; ++ } ++ } ++ ++ /* ---- vertex program: boolean branches -------------------------------- ++ * BRB and CLB branch on one bit of SET_TRANSFORM_BRANCH_BITS, not on a ++ * condition code. An uber effects program skips its optional paths with ++ * "BRB !bN"; run straight through, every path was taken and the glows ++ * came out as red stretched polygons. ++ * 0 MOV o0, v0 1 BRB !b3 -> 3 2 MOV o1, v1 ++ * 3 CLB b12 -> 6 4 MOV o2, v2 5 BRI -> 8 ++ * 6 MOV o3, v3 7 RET 8 MOV o4, v4 (END) */ ++ { ++ static u8 vp[9 * 16]; ++ rsx_test_vp_mov_out(vp + 0 * 16, 0, RSX_TEST_VP_SWZ_IDENT, 0, 0); ++ vp_branch(vp + 1 * 16, 0x11, 3, 3, 0); ++ rsx_test_vp_mov_out(vp + 2 * 16, 1, RSX_TEST_VP_SWZ_IDENT, 1, 0); ++ vp_branch(vp + 3 * 16, 0x12, 6, 12, 1); ++ rsx_test_vp_mov_out(vp + 4 * 16, 2, RSX_TEST_VP_SWZ_IDENT, 2, 0); ++ vp_branch(vp + 5 * 16, 0x09, 8, 0, 0); ++ rsx_test_vp_mov_out(vp + 6 * 16, 3, RSX_TEST_VP_SWZ_IDENT, 3, 0); ++ vp_branch(vp + 7 * 16, 0x0C, 0, 0, 0); ++ rsx_test_vp_mov_out(vp + 8 * 16, 4, RSX_TEST_VP_SWZ_IDENT, 4, 1); ++ if (rsx_vp_uses_branch_bits(vp, sizeof vp) && ++ !rsx_vp_uses_branch_bits(g_long_vp, sizeof g_long_vp)) { ++ printf("[PASS] bool VP -- keyed on the branch bits, the BRI-only program not\n"); ++ g_pass++; ++ } else { ++ printf("[FAIL] bool VP -- rsx_vp_uses_branch_bits\n"); ++ g_fail++; ++ } ++ static const struct { u32 bits; const char* brb; const char* clb; } cases[] = { ++ { 0x0000u, "BRB @1 -> 3 cond=7 test=0 swz=xxxx */\n _pc = 3;", ++ "CLB @3 -> 6 cond=7 test=0 swz=xxxx */\n _pc = 4;" }, ++ { 0x1008u, "BRB @1 -> 3 cond=7 test=0 swz=xxxx */\n _pc = 2;", ++ "CLB @3 -> 6 cond=7 test=0 swz=xxxx */\n" ++ " _cs[_csp] = 4; _csp = min(_csp + 1, 7); _pc = 6;" }, ++ }; ++ for (u32 i = 0; i < 2; i++) { ++ rsx_vp_set_branch_base(0); ++ rsx_vp_set_branch_bits(cases[i].bits); ++ if (rsx_vp_decompile(vp, sizeof vp, g_hlsl, sizeof g_hlsl) > 0) { ++ check("bool VP HLSL", g_hlsl, cases[i].brb); ++ check("bool VP HLSL", g_hlsl, cases[i].clb); ++ check_absent("bool VP HLSL", g_hlsl, "not modelled"); ++ if (translate("bool VP", RSX_SHADER_STAGE_VERTEX) == 0) ++ check("bool VP MSL", g_msl, "vertex "); ++ } else { ++ printf("[FAIL] bool VP -- decompile failed\n"); ++ g_fail++; ++ } ++ } ++ rsx_vp_set_branch_bits(0); ++ } ++ + /* ---- fragment program: MOV r0, COL0 ---------------------------------- */ + { + u8 fp[16]; diff --git a/tasks/sp00nznet__ps3recomp-485/solution/solve.sh b/tasks/sp00nznet__ps3recomp-485/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-485/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-485/task.toml b/tasks/sp00nznet__ps3recomp-485/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3d32ee0bfec2f44d59a9854dd5f194d5eb9113ec --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-485/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-485" +description = "rsx_vp_decompiler: branch on the transform branch bits; leaders up to slot 544" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "a6d76c895f77eb30b90a806c830544e61821b77f" +reference = "https://github.com/sp00nznet/ps3recomp/pull/485" +source_access = "auto" +built_at = "2026-11-16T16:09:59.627812+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:202dda984e653bdaf8ad710f51d8cb81d3c3f7c73f1491357497ca21421bf38d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-26T15:32:55Z" +diff_format = "unified" +context_files = [ + "libs/video/rsx_draw_engine.c", + "libs/video/rsx_live_draw.c", + "libs/video/rsx_vp_decompiler.c", + "libs/video/rsx_vp_decompiler.h", + "libs/video/tests/test_shader_msl.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 155 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.116463+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-485/tests/capture.py b/tasks/sp00nznet__ps3recomp-485/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-485/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-485/tests/instruction.md b/tasks/sp00nznet__ps3recomp-485/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d97bda4b4a5fb513a7dafceeeaf0f3f0ec70dd58 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-485/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** rsx_vp_decompiler: branch on the transform branch bits; leaders up to slot 544 + +## Description + +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. + +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. + +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. + +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. + +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. + +Tests: +- `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. +- `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. +- In-game on Metal: no more dropped pipelines, and the glows and light shafts show up as on the console. + +No game data or program bytes are included. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-485/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-485/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8876101b75b427ccbbba473b3ecacb1254e60215 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-485/tests/oracle.patch @@ -0,0 +1,256 @@ +diff --git a/libs/video/rsx_draw_engine.c b/libs/video/rsx_draw_engine.c +index f99986b3..4a02779b 100644 +--- a/libs/video/rsx_draw_engine.c ++++ b/libs/video/rsx_draw_engine.c +@@ -1631,6 +1631,10 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout, + const u32 cube_mask = eng_cube_mask(); + const u32 vol_mask = eng_volume_mask(); + const u32 vtex_mask = eng_vtex_mask(); ++ /* BRB/CLB outcomes are baked into the program: the branch bits are ++ * identity only for a program that tests them. */ ++ const int vp_branch_bits_used = !fixed && rsx_vp_uses_branch_bits(vp_uc, vp_instrs * 16u); ++ const u32 vp_branch_bits = vp_branch_bits_used ? rsx_dsp_reg(&g.rsx, 0x1FF8u) : 0; + rsx_fp_shadow_desc shadow[RSX_DSP_NUM_TEXTURES] = {{0}}; + u32 shadow_mask = 0; + const u32 sampled_units = fixed ? 0 : rsx_fp_texture_units(fp_uc, fp_size); +@@ -1686,6 +1690,7 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout, + key = eng_fnv1a(&fixed_tag, sizeof fixed_tag, key); + } else { + key = eng_fnv1a(vp_uc, vp_instrs * 16u, key); ++ if (vp_branch_bits_used) key = eng_fnv1a(&vp_branch_bits, sizeof vp_branch_bits, key); + key = rsx_fp_structural_hash(fp_uc, fp_size, key); + if (!key) return 0; + const u32 fp_ctrl_key = fp_ctrl & 0x4Eu; /* colour width and fragment depth export */ +@@ -1727,6 +1732,7 @@ static u32 eng_pipeline_get(const rsx_vertex_layout_plan* layout, + snprintf(s_vs_hlsl, sizeof s_vs_hlsl, "%s", kEngFixedVS); + snprintf(s_ps_hlsl, sizeof s_ps_hlsl, "%s", kEngFixedPS); + } else { ++ rsx_vp_set_branch_bits(vp_branch_bits); + vi = rsx_vp_decompile_compact_ex(vp_uc, vp_instrs * 16u, vtex_mask, + layout->mask, s_vs_hlsl, + sizeof s_vs_hlsl); +diff --git a/libs/video/rsx_live_draw.c b/libs/video/rsx_live_draw.c +index 2e65b8ee..54fdffd9 100644 +--- a/libs/video/rsx_live_draw.c ++++ b/libs/video/rsx_live_draw.c +@@ -4766,6 +4766,11 @@ static ID3D12PipelineState* get_pso( + key = fnv1a(&fp_ctrl_key, sizeof(fp_ctrl_key), key); + key = fnv1a(&cube_mask, sizeof(cube_mask), key); + key = fnv1a(&vtex_mask, sizeof(vtex_mask), key); ++ /* BRB/CLB outcomes are baked into the program (rsx_vp_set_branch_bits). */ ++ const int vp_branch_bits_used = rsx_vp_uses_branch_bits(vp_uc, vp_instrs * 16); ++ const u32 vp_branch_bits = vp_branch_bits_used ? rsx_dsp_reg(&g.rsx, 0x1FF8u) : 0; ++ if (vp_branch_bits_used) ++ key = fnv1a(&vp_branch_bits, sizeof(vp_branch_bits), key); + /* Texel-addressed (RSX_TEX_FMT_UNNORM) units need their coordinates divided + * by the texture size in the shader -- D3D12 has no unnormalised addressing + * mode. The divisor is baked into the HLSL, so the sizes are part of the +@@ -4880,6 +4885,7 @@ static ID3D12PipelineState* get_pso( + const LONGLONG decompile_begin = ld_profile_qpc(); + #endif + rsx_vp_set_branch_base(rsx_dsp_vp_start(&g.rsx)); ++ rsx_vp_set_branch_bits(vp_branch_bits); + const int vi = masked_layout + ? rsx_vp_decompile_compact_ex( + vp_uc, vp_instrs * 16, vtex_mask, masked_layout->mask, +diff --git a/libs/video/rsx_vp_decompiler.c b/libs/video/rsx_vp_decompiler.c +index b9ed32be..4547280b 100644 +--- a/libs/video/rsx_vp_decompiler.c ++++ b/libs/video/rsx_vp_decompiler.c +@@ -132,11 +132,27 @@ static void emit_store(Out* b, const char* dst_fmt, u32 idx, const char* m) + } + + /* ---- flow control -------------------------------------------------------- */ +-#define RSX_VP_MAX_INSTR 512 ++/* The transform program memory holds 544 slots (RSX_DSP_VP_INSTR), not 512: ++ * a branch target or block leader past slot 511 must still open a block. */ ++#define RSX_VP_MAX_INSTR 544 + + static u32 s_vp_branch_base = 0; /* VP slot the program being decompiled starts at */ + void rsx_vp_set_branch_base(u32 start_slot) { s_vp_branch_base = start_slot; } + ++static u32 s_vp_branch_bits = 0; /* SET_TRANSFORM_BRANCH_BITS, tested by BRB/CLB */ ++void rsx_vp_set_branch_bits(u32 bits) { s_vp_branch_bits = bits; } ++ ++int rsx_vp_uses_branch_bits(const u8* ucode, u32 max_bytes) ++{ ++ if (!ucode) return 0; ++ for (u32 off = 0; off + 16 <= max_bytes; off += 16) { ++ const u32 sca_op = (rd_le(ucode + off + 4) >> 27) & 0x1Fu; ++ if (sca_op == 0x11 || sca_op == 0x12) return 1; /* BRB, CLB */ ++ if (rd_le(ucode + off + 12) & 1u) break; /* D3.end */ ++ } ++ return 0; ++} ++ + /* BRA BRI CAL CLI RET BRB CLB (scalar opcodes). */ + static int vp_is_flow(u32 sca_op) + { +@@ -500,10 +516,20 @@ static int rsx_vp_decompile_impl( + snprintf(flow_term, sizeof flow_term, + " if (%s) { if (_csp > 0) { _csp--; _pc = _cs[_csp]; } else _pc = -1; } else _pc = %d;\n", + c, next); +- else { /* BRB/CLB: boolean-register branches */ +- n_flow_skipped++; +- snprintf(flow_term, sizeof flow_term, +- " _pc = %d; /* TODO: %s not modelled */\n", next, rsx_vp_sca_name(sca_op)); ++ else { /* BRB, CLB */ ++ /* A boolean branch tests bit D3[23:27] of the transform ++ * branch bits against D3[28] and ignores the CC condition ++ * (RPCS3's GetOptionalBranchCond). The bits are baked in: ++ * the caller keys the program on them. */ ++ const u32 bit = (s_vp_branch_bits >> ((d3 >> 23) & 0x1Fu)) & 1u; ++ const int taken = bit == ((d3 >> 28) & 1u); ++ if (!taken) ++ snprintf(flow_term, sizeof flow_term, " _pc = %d;\n", next); ++ else if (sca_op == 0x11) ++ snprintf(flow_term, sizeof flow_term, " _pc = %u;\n", tgt); ++ else ++ snprintf(flow_term, sizeof flow_term, ++ " _cs[_csp] = %d; _csp = min(_csp + 1, 7); _pc = %u;\n", next, tgt); + } + } + /* ---- scalar ALU (reads SRC2) ---- */ +diff --git a/libs/video/rsx_vp_decompiler.h b/libs/video/rsx_vp_decompiler.h +index ecc53fce..9310c482 100644 +--- a/libs/video/rsx_vp_decompiler.h ++++ b/libs/video/rsx_vp_decompiler.h +@@ -57,6 +57,12 @@ int rsx_vp_decompile(const u8* ucode, u32 max_bytes, char* out, u32 out_size); + * to the ucode pointer handed in. Defaults to 0. */ + void rsx_vp_set_branch_base(u32 start_slot); + ++/* SET_TRANSFORM_BRANCH_BITS for the next program decompiled. BRB and CLB ++ * branch on one of these bits; the decompiler bakes the outcome in, so a ++ * program that rsx_vp_uses_branch_bits() must be keyed on them too. */ ++void rsx_vp_set_branch_bits(u32 bits); ++int rsx_vp_uses_branch_bits(const u8* ucode, u32 max_bytes); ++ + /* Bit N in vtex_mask declares NV40 2D vertex-texture unit N at t(16+N), + * sampler sN, and turns TXL for that unit into SampleLevel(..., LOD 0). + * Unmasked units retain the defined-zero fallback. */ +diff --git a/libs/video/tests/test_shader_msl.c b/libs/video/tests/test_shader_msl.c +index de2a6dc6..293386e2 100644 +--- a/libs/video/tests/test_shader_msl.c ++++ b/libs/video/tests/test_shader_msl.c +@@ -20,6 +20,8 @@ + * FP TEX r0, TC0 unit 0 (END) texture unit 0 sampled at texcoord0 + * FP TEX r0, TC0 unit 0, CUBE (END) ... with unit 0 a cube map + * VP MOV o0, v0 ; TXL o1, v8 (END) a vertex texture sampled at t16 ++ * VP 519 slots, BRI past slot 512 a long effects program's branches ++ * VP BRB, CLB on transform branch bits its optional paths + * FP MOV r0, COL0 ; MOV r2, COL0.zyxw two colour targets: what --mrt runs + * + * Each program's HLSL is checked for what was meant before the MSL is looked +@@ -70,8 +72,23 @@ static void check_count(const char* what, int got, int want) + + /* ---- the translation step, shared by every case -------------------------- */ + +-static char g_hlsl[65536]; +-static char g_msl[65536]; ++static char g_hlsl[262144]; ++static char g_msl[262144]; ++static u8 g_long_vp[519 * 16]; /* the 519-slot program; also has no BRB/CLB */ ++ ++/* Flow instruction `sca_op` (0x09 BRI, 0x11 BRB, 0x12 CLB) to VP slot ++ * `target`: cond [10:12] = 7 (TR), the target split over D0[23], D2[0:5] and ++ * D3[29:31]; a boolean branch tests branch bit `bit` (D3[23:27]) for ++ * `if_set` (D3[28]). No ALU writes. */ ++static void vp_branch(u8* p, u32 sca_op, u32 target, u32 bit, u32 if_set) ++{ ++ const u32 d0 = (0x3Fu << 15) | (7u << 10) | (((target >> 9) & 1u) << 23); ++ const u32 d1 = sca_op << 27; ++ const u32 d2 = (target >> 3) & 0x3Fu; ++ const u32 d3 = (0x3Fu << 7) | (bit << 23) | (if_set << 28) | ((target & 7u) << 29); ++ rsx_test_put_le32(p + 0, d0); rsx_test_put_le32(p + 4, d1); ++ rsx_test_put_le32(p + 8, d2); rsx_test_put_le32(p + 12, d3); ++} + static char g_log[4096]; + + static int translate(const char* what, int stage) +@@ -129,6 +146,86 @@ int main(int argc, char** argv) + } + } + ++ /* ---- vertex program: branches past slot 512 ------------------------------ ++ * The transform program memory has 544 slots. A branching program is ++ * emitted as one "if (_pc == N)" block per leader; a leader past slot 511 ++ * opened no block, so every later branch closed a block that was never ++ * opened and main() ended early. A 543-slot effects program failed that ++ * way and every draw using it was dropped. */ ++ { ++ u8* vp = g_long_vp; ++ for (u32 i = 0; i < 513; i++) ++ rsx_test_vp_mov_out(vp + i * 16, 0, RSX_TEST_VP_SWZ_IDENT, 0, 0); /* MOV o0, v0 */ ++ vp_branch(vp + 513 * 16, 0x09, 515, 0, 0); ++ rsx_test_vp_mov_out(vp + 514 * 16, 3, RSX_TEST_VP_SWZ_IDENT, 1, 0); /* skipped */ ++ rsx_test_vp_mov_out(vp + 515 * 16, 1, RSX_TEST_VP_SWZ_IDENT, 1, 0); /* MOV o1, v1 */ ++ vp_branch(vp + 516 * 16, 0x09, 518, 0, 0); ++ rsx_test_vp_mov_out(vp + 517 * 16, 3, RSX_TEST_VP_SWZ_IDENT, 2, 0); /* skipped */ ++ rsx_test_vp_mov_out(vp + 518 * 16, 2, RSX_TEST_VP_SWZ_IDENT, 2, 1); /* MOV o2, v2, END */ ++ rsx_vp_set_branch_base(0); ++ if (rsx_vp_decompile(vp, sizeof g_long_vp, g_hlsl, sizeof g_hlsl) > 0) { ++ check("long VP HLSL", g_hlsl, "if (_pc == 514) {"); ++ check("long VP HLSL", g_hlsl, "if (_pc == 515) {"); ++ check("long VP HLSL", g_hlsl, "if (_pc == 518) {"); ++ if (translate("long VP", RSX_SHADER_STAGE_VERTEX) == 0) ++ check("long VP MSL", g_msl, "vertex "); ++ } else { ++ printf("[FAIL] long VP -- decompile failed\n"); ++ g_fail++; ++ } ++ } ++ ++ /* ---- vertex program: boolean branches -------------------------------- ++ * BRB and CLB branch on one bit of SET_TRANSFORM_BRANCH_BITS, not on a ++ * condition code. An uber effects program skips its optional paths with ++ * "BRB !bN"; run straight through, every path was taken and the glows ++ * came out as red stretched polygons. ++ * 0 MOV o0, v0 1 BRB !b3 -> 3 2 MOV o1, v1 ++ * 3 CLB b12 -> 6 4 MOV o2, v2 5 BRI -> 8 ++ * 6 MOV o3, v3 7 RET 8 MOV o4, v4 (END) */ ++ { ++ static u8 vp[9 * 16]; ++ rsx_test_vp_mov_out(vp + 0 * 16, 0, RSX_TEST_VP_SWZ_IDENT, 0, 0); ++ vp_branch(vp + 1 * 16, 0x11, 3, 3, 0); ++ rsx_test_vp_mov_out(vp + 2 * 16, 1, RSX_TEST_VP_SWZ_IDENT, 1, 0); ++ vp_branch(vp + 3 * 16, 0x12, 6, 12, 1); ++ rsx_test_vp_mov_out(vp + 4 * 16, 2, RSX_TEST_VP_SWZ_IDENT, 2, 0); ++ vp_branch(vp + 5 * 16, 0x09, 8, 0, 0); ++ rsx_test_vp_mov_out(vp + 6 * 16, 3, RSX_TEST_VP_SWZ_IDENT, 3, 0); ++ vp_branch(vp + 7 * 16, 0x0C, 0, 0, 0); ++ rsx_test_vp_mov_out(vp + 8 * 16, 4, RSX_TEST_VP_SWZ_IDENT, 4, 1); ++ if (rsx_vp_uses_branch_bits(vp, sizeof vp) && ++ !rsx_vp_uses_branch_bits(g_long_vp, sizeof g_long_vp)) { ++ printf("[PASS] bool VP -- keyed on the branch bits, the BRI-only program not\n"); ++ g_pass++; ++ } else { ++ printf("[FAIL] bool VP -- rsx_vp_uses_branch_bits\n"); ++ g_fail++; ++ } ++ static const struct { u32 bits; const char* brb; const char* clb; } cases[] = { ++ { 0x0000u, "BRB @1 -> 3 cond=7 test=0 swz=xxxx */\n _pc = 3;", ++ "CLB @3 -> 6 cond=7 test=0 swz=xxxx */\n _pc = 4;" }, ++ { 0x1008u, "BRB @1 -> 3 cond=7 test=0 swz=xxxx */\n _pc = 2;", ++ "CLB @3 -> 6 cond=7 test=0 swz=xxxx */\n" ++ " _cs[_csp] = 4; _csp = min(_csp + 1, 7); _pc = 6;" }, ++ }; ++ for (u32 i = 0; i < 2; i++) { ++ rsx_vp_set_branch_base(0); ++ rsx_vp_set_branch_bits(cases[i].bits); ++ if (rsx_vp_decompile(vp, sizeof vp, g_hlsl, sizeof g_hlsl) > 0) { ++ check("bool VP HLSL", g_hlsl, cases[i].brb); ++ check("bool VP HLSL", g_hlsl, cases[i].clb); ++ check_absent("bool VP HLSL", g_hlsl, "not modelled"); ++ if (translate("bool VP", RSX_SHADER_STAGE_VERTEX) == 0) ++ check("bool VP MSL", g_msl, "vertex "); ++ } else { ++ printf("[FAIL] bool VP -- decompile failed\n"); ++ g_fail++; ++ } ++ } ++ rsx_vp_set_branch_bits(0); ++ } ++ + /* ---- fragment program: MOV r0, COL0 ---------------------------------- */ + { + u8 fp[16]; diff --git a/tasks/sp00nznet__ps3recomp-485/tests/test.sh b/tasks/sp00nznet__ps3recomp-485/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-485/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-485/tests/verifier.py b/tasks/sp00nznet__ps3recomp-485/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-485/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-490/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-490/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e58bcfa58777d72bba591f37e690838b686d5be --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-490/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-490/instruction.md b/tasks/sp00nznet__ps3recomp-490/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..91527192ea91203c7df3c45be8291c284309cc84 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-490/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** sys_mutex: destroy refuses a mutex that is held or has waiters (EBUSY) + +## Description + +## Why + +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. + +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. + +## What + +- `sys_mutex_info.waiters` counts the threads blocked acquiring the mutex: + - around the acquire in `sys_mutex_lock`, on both hosts; both timeout returns give the count back; + - around the re-lock in `sys_cond_wait`. +- `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. + +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. + +## Tests + +- 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`: + 1. while the mutex is held; + 2. while it is held and another thread is blocked on it. That thread then gets the mutex once it is released; + 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; + 4. while a `sys_cond_wait` re-lock is blocked, from the signaler that still holds the mutex. + + 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`. + + Without the check in `sys_mutex_destroy`, cases 1 to 3 get `CELL_OK` and the checks after them fail too. +- `sync_stress` passes. macOS; the Windows build is clang-cl, which has the `__atomic` builtins (`sys_rwlock.c` already uses them). + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-490/solution/patch.diff b/tasks/sp00nznet__ps3recomp-490/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..814af5da2176e7817b70f7e369c5d053ca885649 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-490/solution/patch.diff @@ -0,0 +1,235 @@ +diff --git a/runtime/syscalls/sys_cond.c b/runtime/syscalls/sys_cond.c +index 45235ea6..e1311a27 100644 +--- a/runtime/syscalls/sys_cond.c ++++ b/runtime/syscalls/sys_cond.c +@@ -195,7 +195,10 @@ int64_t sys_cond_wait(ppu_context* ctx) + while (*link != &waiter) link = &(*link)->next; + *link = waiter.next; + cond_unlock(c); ++ /* Re-acquiring counts as waiting on the mutex (sys_mutex_destroy). */ ++ __atomic_add_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); + for (int i = 0; i < depth; ++i) guest_lock(m); ++ __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); + m->owner_tid = ctx->thread_id; + m->lock_count = depth; + return result; +diff --git a/runtime/syscalls/sys_mutex.c b/runtime/syscalls/sys_mutex.c +index 2e760ea5..76f4c0d4 100644 +--- a/runtime/syscalls/sys_mutex.c ++++ b/runtime/syscalls/sys_mutex.c +@@ -159,6 +159,22 @@ int64_t sys_mutex_destroy(ppu_context* ctx) + return (int64_t)(int32_t)CELL_ESRCH; + } + ++ /* lv2 refuses to destroy a mutex that is held or has waiters (EBUSY). ++ * Destroying it anyway freed the host mutex under a thread blocked on it, ++ * and the next sys_mutex_create in the same slot initialised a new one ++ * over it: everyone else then used the new mutex and the blocked thread ++ * waited on the dead one for good. */ ++ if (m->lock_count > 0 || __atomic_load_n(&m->waiters, __ATOMIC_SEQ_CST) > 0) { ++ static int n = 0; ++ if (n++ < 16) ++ fprintf(stderr, "[mutex] destroy of mutex %u '%.8s' refused: owner tid=%llu " ++ "count=%d waiters=%d (EBUSY)\n", mutex_id, m->name, ++ (unsigned long long)m->owner_tid, m->lock_count, ++ __atomic_load_n(&m->waiters, __ATOMIC_SEQ_CST)); ++ mtx_table_unlock(); ++ return (int64_t)(int32_t)CELL_EBUSY; ++ } ++ + #ifdef _WIN32 + DeleteCriticalSection(&m->cs); + if (m->wait_handle) CloseHandle(m->wait_handle); +@@ -195,6 +211,7 @@ int64_t sys_mutex_lock(ppu_context* ctx) + return (int64_t)(int32_t)CELL_EDEADLK; + } + ++ __atomic_add_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); /* see sys_mutex_destroy */ + #ifdef _WIN32 + if (timeout_us == 0) { + /* Infinite wait */ +@@ -210,6 +227,7 @@ int64_t sys_mutex_lock(ppu_context* ctx) + int64_t deadline = lv2_usec_deadline(timeout_us); + while (!TryEnterCriticalSection(&m->cs)) { + if (lv2_deadline_passed(deadline)) { ++ __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); + return (int64_t)(int32_t)CELL_ETIMEDOUT; + } + if (timeout_us < 1000) SwitchToThread(); +@@ -230,10 +248,12 @@ int64_t sys_mutex_lock(ppu_context* ctx) + } + int rc = pthread_mutex_timedlock(&m->mtx, &ts); + if (rc == ETIMEDOUT) { ++ __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); + return (int64_t)(int32_t)CELL_ETIMEDOUT; + } + } + #endif ++ __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); + + m->owner_tid = caller_tid; + m->lock_count++; +diff --git a/runtime/syscalls/sys_mutex.h b/runtime/syscalls/sys_mutex.h +index bfe849d8..08b20e46 100644 +--- a/runtime/syscalls/sys_mutex.h ++++ b/runtime/syscalls/sys_mutex.h +@@ -62,6 +62,7 @@ typedef struct sys_mutex_info { + int recursive; + uint64_t owner_tid; /* thread_id of current owner (for recursive/error checking) */ + int lock_count; /* recursive lock count */ ++ volatile int waiters; /* threads blocked acquiring it (sys_mutex_lock, cond re-lock) */ + + #ifdef _WIN32 + CRITICAL_SECTION cs; +diff --git a/tests/sync_stress/CMakeLists.txt b/tests/sync_stress/CMakeLists.txt +index 52fb8216..df1ccc35 100644 +--- a/tests/sync_stress/CMakeLists.txt ++++ b/tests/sync_stress/CMakeLists.txt +@@ -89,6 +89,27 @@ set_tests_properties(sync_stress PROPERTIES + TIMEOUT 120 + ) + ++# sys_mutex_destroy: EBUSY while the mutex is held or a thread is blocked ++# acquiring it. Win32 host threads, through the shim off Windows. ++add_executable(test_mutex_destroy ++ test_mutex_destroy.c test_shims.c ++ "${RUNTIME_SYNC_DIR}/sys_mutex.c" ++ "${RUNTIME_SYNC_DIR}/sys_cond.c") ++if(NOT WIN32) ++ target_sources(test_mutex_destroy PRIVATE ++ "${PS3RECOMP_TREE_ROOT}/runtime/platform/win32_compat.c") ++ find_package(Threads REQUIRED) ++ target_link_libraries(test_mutex_destroy PRIVATE Threads::Threads) ++endif() ++target_include_directories(test_mutex_destroy PRIVATE ++ "${PS3RECOMP_TREE_ROOT}" "${PS3RECOMP_TREE_ROOT}/include" ++ "${RUNTIME_SYNC_DIR}" "${PS3RECOMP_TREE_ROOT}/runtime") ++if(MSVC) ++ target_compile_definitions(test_mutex_destroy PRIVATE _CRT_SECURE_NO_WARNINGS) ++endif() ++add_test(NAME mutex_destroy COMMAND test_mutex_destroy) ++set_tests_properties(mutex_destroy PROPERTIES LABELS "runtime;sync" TIMEOUT 20) ++ + # The focused condition tests use Win32 host threads. POSIX execution also + # needs the waitable-handle implementation supplied by the native host port. + if(WIN32) +diff --git a/tests/sync_stress/test_mutex_destroy.c b/tests/sync_stress/test_mutex_destroy.c +new file mode 100644 +index 00000000..ed1f219d +--- /dev/null ++++ b/tests/sync_stress/test_mutex_destroy.c +@@ -0,0 +1,114 @@ ++/* sys_mutex_destroy refuses a mutex that is held or has a thread blocked ++ * acquiring it, with EBUSY, as lv2 does. It used to destroy the host mutex ++ * under the blocked thread; the next sys_mutex_create in that slot then ++ * initialised a new mutex over it, and the blocked thread waited on the dead ++ * one for good. ++ * ++ * The blocked acquires are counted in sys_mutex_info.waiters: sys_mutex_lock ++ * (both timeouts give the count back) and sys_cond_wait's re-lock. */ ++#include "runtime/platform/win32_compat.h" ++#include "runtime/syscalls/sys_cond.h" ++#include ++#include ++#include ++ ++uint8_t* vm_base; ++static uint32_t mid, cid; ++static int failures; ++#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #x); failures++; } } while (0) ++static int32_t call(int64_t (*f)(ppu_context*), ppu_context* c, uint64_t a, uint64_t b, uint64_t d) { ++ c->gpr[3]=a; c->gpr[4]=b; c->gpr[5]=d; ++ return (int32_t)f(c); ++} ++static uint32_t be_read(unsigned off) { ++ uint8_t* p=vm_base+off; ++ return ((uint32_t)p[0]<<24)|((uint32_t)p[1]<<16)|((uint32_t)p[2]<<8)|p[3]; ++} ++static int waiters(void) { return __atomic_load_n(&g_sys_mutexes[mid-1].waiters, __ATOMIC_SEQ_CST); } ++static int wait_waiters(int want) { ++ for (int i=0;i<2000 && waiters()!=want;i++) Sleep(1); ++ return waiters()==want; ++} ++/* Thread 2: lock (blocking, or with the timeout in raw), record, unlock. */ ++static volatile int32_t s_rc=-1; ++static DWORD WINAPI locker(void* raw) { ++ ppu_context c={0}; c.thread_id=2; ++ s_rc=call(sys_mutex_lock,&c,mid,(uint64_t)(uintptr_t)raw,0); ++ if (s_rc==CELL_OK) call(sys_mutex_unlock,&c,mid,0,0); ++ return 0; ++} ++static DWORD WINAPI signaler(void* raw) { ++ (void)raw; ++ ppu_context c={0}; c.thread_id=3; ++ while (call(sys_mutex_lock,&c,mid,0,0)!=CELL_OK) Sleep(1); ++ call(sys_cond_signal,&c,cid,0,0); ++ /* Hold it: the waiter is now blocked re-acquiring. */ ++ CHECK(wait_waiters(1)); ++ CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY); ++ call(sys_mutex_unlock,&c,mid,0,0); ++ return 0; ++} ++int main(void) { ++ vm_base=calloc(1,65536); ++ ppu_context c={0}; c.thread_id=1; ++ vm_base[0x103]=1; vm_base[0x107]=0x20; /* FIFO, not recursive */ ++ CHECK(call(sys_mutex_create,&c,0x200,0x100,0)==CELL_OK); ++ mid=be_read(0x200); ++ ++ /* 1. Held: EBUSY. */ ++ CHECK(call(sys_mutex_lock,&c,mid,0,0)==CELL_OK); ++ CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY); ++ ++ /* 2. Held, with a thread blocked on it: EBUSY, and the blocked thread ++ * gets the mutex once it is released. */ ++ HANDLE h=CreateThread(NULL,0,locker,NULL,0,NULL); ++ CHECK(wait_waiters(1)); ++ CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY); ++ CHECK(call(sys_mutex_unlock,&c,mid,0,0)==CELL_OK); ++ CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h); ++ CHECK(s_rc==CELL_OK && waiters()==0); ++ ++ /* 3. A timed lock that times out gives its count back. */ ++ CHECK(call(sys_mutex_lock,&c,mid,0,0)==CELL_OK); ++ s_rc=-1; ++ h=CreateThread(NULL,0,locker,(void*)(uintptr_t)20000,0,NULL); ++ CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h); ++ CHECK(s_rc==(int32_t)CELL_ETIMEDOUT && waiters()==0); ++ CHECK(call(sys_mutex_unlock,&c,mid,0,0)==CELL_OK); ++ ++ /* 4. A thread blocked on the host lock while the guest count is 0 (the ++ * window in which a released mutex passes to a waiter): EBUSY. */ ++ sys_mutex_info* m=&g_sys_mutexes[mid-1]; ++#ifdef _WIN32 ++ EnterCriticalSection(&m->cs); ++#else ++ pthread_mutex_lock(&m->mtx); ++#endif ++ h=CreateThread(NULL,0,locker,NULL,0,NULL); ++ CHECK(wait_waiters(1) && m->lock_count==0); ++ CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY); ++#ifdef _WIN32 ++ LeaveCriticalSection(&m->cs); ++#else ++ pthread_mutex_unlock(&m->mtx); ++#endif ++ CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h); ++ ++ /* 5. sys_cond_wait's re-lock counts as a waiter. */ ++ CHECK(call(sys_cond_create,&c,0x204,mid,0)==CELL_OK); ++ cid=be_read(0x204); ++ CHECK(call(sys_mutex_lock,&c,mid,0,0)==CELL_OK); ++ h=CreateThread(NULL,0,signaler,NULL,0,NULL); ++ CHECK(call(sys_cond_wait,&c,cid,0,0)==CELL_OK); ++ CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h); ++ CHECK(call(sys_mutex_unlock,&c,mid,0,0)==CELL_OK); ++ CHECK(call(sys_cond_destroy,&c,cid,0,0)==CELL_OK); ++ ++ /* 6. Free and uncontended: destroyed. */ ++ CHECK(waiters()==0); ++ CHECK(call(sys_mutex_destroy,&c,mid,0,0)==CELL_OK); ++ CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_ESRCH); ++ ++ printf("mutex destroy: %s\n",failures?"FAIL":"PASS"); ++ return failures?1:0; ++} diff --git a/tasks/sp00nznet__ps3recomp-490/solution/solve.sh b/tasks/sp00nznet__ps3recomp-490/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-490/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-490/task.toml b/tasks/sp00nznet__ps3recomp-490/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3a60f1379ae09d5044d6656c0ac3adf35e5accb4 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-490/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-490" +description = "sys_mutex: destroy refuses a mutex that is held or has waiters (EBUSY)" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "a6d76c895f77eb30b90a806c830544e61821b77f" +reference = "https://github.com/sp00nznet/ps3recomp/pull/490" +source_access = "auto" +built_at = "2026-11-16T16:09:59.863839+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3bd934c95535d0d165fbde05729492d959cc9cbbb4f0c97384bc4fbe3c48db3f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-26T15:32:55Z" +diff_format = "unified" +context_files = [ + "runtime/syscalls/sys_cond.c", + "runtime/syscalls/sys_mutex.c", + "runtime/syscalls/sys_mutex.h", + "tests/sync_stress/CMakeLists.txt", + "tests/sync_stress/test_mutex_destroy.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 159 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.116999+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-490/tests/capture.py b/tasks/sp00nznet__ps3recomp-490/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-490/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-490/tests/instruction.md b/tasks/sp00nznet__ps3recomp-490/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..91527192ea91203c7df3c45be8291c284309cc84 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-490/tests/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** sys_mutex: destroy refuses a mutex that is held or has waiters (EBUSY) + +## Description + +## Why + +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. + +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. + +## What + +- `sys_mutex_info.waiters` counts the threads blocked acquiring the mutex: + - around the acquire in `sys_mutex_lock`, on both hosts; both timeout returns give the count back; + - around the re-lock in `sys_cond_wait`. +- `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. + +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. + +## Tests + +- 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`: + 1. while the mutex is held; + 2. while it is held and another thread is blocked on it. That thread then gets the mutex once it is released; + 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; + 4. while a `sys_cond_wait` re-lock is blocked, from the signaler that still holds the mutex. + + 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`. + + Without the check in `sys_mutex_destroy`, cases 1 to 3 get `CELL_OK` and the checks after them fail too. +- `sync_stress` passes. macOS; the Windows build is clang-cl, which has the `__atomic` builtins (`sys_rwlock.c` already uses them). + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-490/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-490/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..814af5da2176e7817b70f7e369c5d053ca885649 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-490/tests/oracle.patch @@ -0,0 +1,235 @@ +diff --git a/runtime/syscalls/sys_cond.c b/runtime/syscalls/sys_cond.c +index 45235ea6..e1311a27 100644 +--- a/runtime/syscalls/sys_cond.c ++++ b/runtime/syscalls/sys_cond.c +@@ -195,7 +195,10 @@ int64_t sys_cond_wait(ppu_context* ctx) + while (*link != &waiter) link = &(*link)->next; + *link = waiter.next; + cond_unlock(c); ++ /* Re-acquiring counts as waiting on the mutex (sys_mutex_destroy). */ ++ __atomic_add_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); + for (int i = 0; i < depth; ++i) guest_lock(m); ++ __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); + m->owner_tid = ctx->thread_id; + m->lock_count = depth; + return result; +diff --git a/runtime/syscalls/sys_mutex.c b/runtime/syscalls/sys_mutex.c +index 2e760ea5..76f4c0d4 100644 +--- a/runtime/syscalls/sys_mutex.c ++++ b/runtime/syscalls/sys_mutex.c +@@ -159,6 +159,22 @@ int64_t sys_mutex_destroy(ppu_context* ctx) + return (int64_t)(int32_t)CELL_ESRCH; + } + ++ /* lv2 refuses to destroy a mutex that is held or has waiters (EBUSY). ++ * Destroying it anyway freed the host mutex under a thread blocked on it, ++ * and the next sys_mutex_create in the same slot initialised a new one ++ * over it: everyone else then used the new mutex and the blocked thread ++ * waited on the dead one for good. */ ++ if (m->lock_count > 0 || __atomic_load_n(&m->waiters, __ATOMIC_SEQ_CST) > 0) { ++ static int n = 0; ++ if (n++ < 16) ++ fprintf(stderr, "[mutex] destroy of mutex %u '%.8s' refused: owner tid=%llu " ++ "count=%d waiters=%d (EBUSY)\n", mutex_id, m->name, ++ (unsigned long long)m->owner_tid, m->lock_count, ++ __atomic_load_n(&m->waiters, __ATOMIC_SEQ_CST)); ++ mtx_table_unlock(); ++ return (int64_t)(int32_t)CELL_EBUSY; ++ } ++ + #ifdef _WIN32 + DeleteCriticalSection(&m->cs); + if (m->wait_handle) CloseHandle(m->wait_handle); +@@ -195,6 +211,7 @@ int64_t sys_mutex_lock(ppu_context* ctx) + return (int64_t)(int32_t)CELL_EDEADLK; + } + ++ __atomic_add_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); /* see sys_mutex_destroy */ + #ifdef _WIN32 + if (timeout_us == 0) { + /* Infinite wait */ +@@ -210,6 +227,7 @@ int64_t sys_mutex_lock(ppu_context* ctx) + int64_t deadline = lv2_usec_deadline(timeout_us); + while (!TryEnterCriticalSection(&m->cs)) { + if (lv2_deadline_passed(deadline)) { ++ __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); + return (int64_t)(int32_t)CELL_ETIMEDOUT; + } + if (timeout_us < 1000) SwitchToThread(); +@@ -230,10 +248,12 @@ int64_t sys_mutex_lock(ppu_context* ctx) + } + int rc = pthread_mutex_timedlock(&m->mtx, &ts); + if (rc == ETIMEDOUT) { ++ __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); + return (int64_t)(int32_t)CELL_ETIMEDOUT; + } + } + #endif ++ __atomic_sub_fetch(&m->waiters, 1, __ATOMIC_SEQ_CST); + + m->owner_tid = caller_tid; + m->lock_count++; +diff --git a/runtime/syscalls/sys_mutex.h b/runtime/syscalls/sys_mutex.h +index bfe849d8..08b20e46 100644 +--- a/runtime/syscalls/sys_mutex.h ++++ b/runtime/syscalls/sys_mutex.h +@@ -62,6 +62,7 @@ typedef struct sys_mutex_info { + int recursive; + uint64_t owner_tid; /* thread_id of current owner (for recursive/error checking) */ + int lock_count; /* recursive lock count */ ++ volatile int waiters; /* threads blocked acquiring it (sys_mutex_lock, cond re-lock) */ + + #ifdef _WIN32 + CRITICAL_SECTION cs; +diff --git a/tests/sync_stress/CMakeLists.txt b/tests/sync_stress/CMakeLists.txt +index 52fb8216..df1ccc35 100644 +--- a/tests/sync_stress/CMakeLists.txt ++++ b/tests/sync_stress/CMakeLists.txt +@@ -89,6 +89,27 @@ set_tests_properties(sync_stress PROPERTIES + TIMEOUT 120 + ) + ++# sys_mutex_destroy: EBUSY while the mutex is held or a thread is blocked ++# acquiring it. Win32 host threads, through the shim off Windows. ++add_executable(test_mutex_destroy ++ test_mutex_destroy.c test_shims.c ++ "${RUNTIME_SYNC_DIR}/sys_mutex.c" ++ "${RUNTIME_SYNC_DIR}/sys_cond.c") ++if(NOT WIN32) ++ target_sources(test_mutex_destroy PRIVATE ++ "${PS3RECOMP_TREE_ROOT}/runtime/platform/win32_compat.c") ++ find_package(Threads REQUIRED) ++ target_link_libraries(test_mutex_destroy PRIVATE Threads::Threads) ++endif() ++target_include_directories(test_mutex_destroy PRIVATE ++ "${PS3RECOMP_TREE_ROOT}" "${PS3RECOMP_TREE_ROOT}/include" ++ "${RUNTIME_SYNC_DIR}" "${PS3RECOMP_TREE_ROOT}/runtime") ++if(MSVC) ++ target_compile_definitions(test_mutex_destroy PRIVATE _CRT_SECURE_NO_WARNINGS) ++endif() ++add_test(NAME mutex_destroy COMMAND test_mutex_destroy) ++set_tests_properties(mutex_destroy PROPERTIES LABELS "runtime;sync" TIMEOUT 20) ++ + # The focused condition tests use Win32 host threads. POSIX execution also + # needs the waitable-handle implementation supplied by the native host port. + if(WIN32) +diff --git a/tests/sync_stress/test_mutex_destroy.c b/tests/sync_stress/test_mutex_destroy.c +new file mode 100644 +index 00000000..ed1f219d +--- /dev/null ++++ b/tests/sync_stress/test_mutex_destroy.c +@@ -0,0 +1,114 @@ ++/* sys_mutex_destroy refuses a mutex that is held or has a thread blocked ++ * acquiring it, with EBUSY, as lv2 does. It used to destroy the host mutex ++ * under the blocked thread; the next sys_mutex_create in that slot then ++ * initialised a new mutex over it, and the blocked thread waited on the dead ++ * one for good. ++ * ++ * The blocked acquires are counted in sys_mutex_info.waiters: sys_mutex_lock ++ * (both timeouts give the count back) and sys_cond_wait's re-lock. */ ++#include "runtime/platform/win32_compat.h" ++#include "runtime/syscalls/sys_cond.h" ++#include ++#include ++#include ++ ++uint8_t* vm_base; ++static uint32_t mid, cid; ++static int failures; ++#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #x); failures++; } } while (0) ++static int32_t call(int64_t (*f)(ppu_context*), ppu_context* c, uint64_t a, uint64_t b, uint64_t d) { ++ c->gpr[3]=a; c->gpr[4]=b; c->gpr[5]=d; ++ return (int32_t)f(c); ++} ++static uint32_t be_read(unsigned off) { ++ uint8_t* p=vm_base+off; ++ return ((uint32_t)p[0]<<24)|((uint32_t)p[1]<<16)|((uint32_t)p[2]<<8)|p[3]; ++} ++static int waiters(void) { return __atomic_load_n(&g_sys_mutexes[mid-1].waiters, __ATOMIC_SEQ_CST); } ++static int wait_waiters(int want) { ++ for (int i=0;i<2000 && waiters()!=want;i++) Sleep(1); ++ return waiters()==want; ++} ++/* Thread 2: lock (blocking, or with the timeout in raw), record, unlock. */ ++static volatile int32_t s_rc=-1; ++static DWORD WINAPI locker(void* raw) { ++ ppu_context c={0}; c.thread_id=2; ++ s_rc=call(sys_mutex_lock,&c,mid,(uint64_t)(uintptr_t)raw,0); ++ if (s_rc==CELL_OK) call(sys_mutex_unlock,&c,mid,0,0); ++ return 0; ++} ++static DWORD WINAPI signaler(void* raw) { ++ (void)raw; ++ ppu_context c={0}; c.thread_id=3; ++ while (call(sys_mutex_lock,&c,mid,0,0)!=CELL_OK) Sleep(1); ++ call(sys_cond_signal,&c,cid,0,0); ++ /* Hold it: the waiter is now blocked re-acquiring. */ ++ CHECK(wait_waiters(1)); ++ CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY); ++ call(sys_mutex_unlock,&c,mid,0,0); ++ return 0; ++} ++int main(void) { ++ vm_base=calloc(1,65536); ++ ppu_context c={0}; c.thread_id=1; ++ vm_base[0x103]=1; vm_base[0x107]=0x20; /* FIFO, not recursive */ ++ CHECK(call(sys_mutex_create,&c,0x200,0x100,0)==CELL_OK); ++ mid=be_read(0x200); ++ ++ /* 1. Held: EBUSY. */ ++ CHECK(call(sys_mutex_lock,&c,mid,0,0)==CELL_OK); ++ CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY); ++ ++ /* 2. Held, with a thread blocked on it: EBUSY, and the blocked thread ++ * gets the mutex once it is released. */ ++ HANDLE h=CreateThread(NULL,0,locker,NULL,0,NULL); ++ CHECK(wait_waiters(1)); ++ CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY); ++ CHECK(call(sys_mutex_unlock,&c,mid,0,0)==CELL_OK); ++ CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h); ++ CHECK(s_rc==CELL_OK && waiters()==0); ++ ++ /* 3. A timed lock that times out gives its count back. */ ++ CHECK(call(sys_mutex_lock,&c,mid,0,0)==CELL_OK); ++ s_rc=-1; ++ h=CreateThread(NULL,0,locker,(void*)(uintptr_t)20000,0,NULL); ++ CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h); ++ CHECK(s_rc==(int32_t)CELL_ETIMEDOUT && waiters()==0); ++ CHECK(call(sys_mutex_unlock,&c,mid,0,0)==CELL_OK); ++ ++ /* 4. A thread blocked on the host lock while the guest count is 0 (the ++ * window in which a released mutex passes to a waiter): EBUSY. */ ++ sys_mutex_info* m=&g_sys_mutexes[mid-1]; ++#ifdef _WIN32 ++ EnterCriticalSection(&m->cs); ++#else ++ pthread_mutex_lock(&m->mtx); ++#endif ++ h=CreateThread(NULL,0,locker,NULL,0,NULL); ++ CHECK(wait_waiters(1) && m->lock_count==0); ++ CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_EBUSY); ++#ifdef _WIN32 ++ LeaveCriticalSection(&m->cs); ++#else ++ pthread_mutex_unlock(&m->mtx); ++#endif ++ CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h); ++ ++ /* 5. sys_cond_wait's re-lock counts as a waiter. */ ++ CHECK(call(sys_cond_create,&c,0x204,mid,0)==CELL_OK); ++ cid=be_read(0x204); ++ CHECK(call(sys_mutex_lock,&c,mid,0,0)==CELL_OK); ++ h=CreateThread(NULL,0,signaler,NULL,0,NULL); ++ CHECK(call(sys_cond_wait,&c,cid,0,0)==CELL_OK); ++ CHECK(WaitForSingleObject(h,2000)==WAIT_OBJECT_0); CloseHandle(h); ++ CHECK(call(sys_mutex_unlock,&c,mid,0,0)==CELL_OK); ++ CHECK(call(sys_cond_destroy,&c,cid,0,0)==CELL_OK); ++ ++ /* 6. Free and uncontended: destroyed. */ ++ CHECK(waiters()==0); ++ CHECK(call(sys_mutex_destroy,&c,mid,0,0)==CELL_OK); ++ CHECK(call(sys_mutex_destroy,&c,mid,0,0)==(int32_t)CELL_ESRCH); ++ ++ printf("mutex destroy: %s\n",failures?"FAIL":"PASS"); ++ return failures?1:0; ++} diff --git a/tasks/sp00nznet__ps3recomp-490/tests/test.sh b/tasks/sp00nznet__ps3recomp-490/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-490/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-490/tests/verifier.py b/tasks/sp00nznet__ps3recomp-490/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-490/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-494/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-494/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e58bcfa58777d72bba591f37e690838b686d5be --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-494/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-494/instruction.md b/tasks/sp00nznet__ps3recomp-494/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fba828c7ab71b15268c191c4b4a8c06da5ad7f10 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-494/instruction.md @@ -0,0 +1,69 @@ +# Issue + +**Title:** cellPad: load XInput at run time, do not import it + +## Description + +## Why + +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`. + +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. + +## Change + +- `CMakeLists.txt`: drop `xinput` from the Windows link libraries. +- `libs/input/cellPad.c`: + - Remove `#pragma comment(lib, "xinput.lib")` (MinGW ignores it). Keep `` for the types only. + - 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`. + - 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. + - `pad_init_backend()` calls it once at `cellPadInit`. The DLL stays loaded until exit. + - If no DLL loads, every slot reads as unplugged. The keyboard fallback on port 0 still works. Rumble does nothing. + - It prints one line: `[cellPad] XInput from `, or a "no XInput DLL" line. + +Linux, macOS and the SDL2 backend are not touched. + +## Tests + +Against master `a6d76c8`: + +- `git apply --check` and `patch -p1 --dry-run` both apply the patch cleanly (one `+++` header per file). +- 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). +- `libs/input/tests/test_pad_rumble.c`, built as `linux.yml` builds it: `test_pad_rumble: ok` on gcc and clang, before and after. +- 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. +- The `windows.yml` clang-cl build was not run here. Please let CI run it. + +## Evidence + +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: + +- Before: the exe does not start, exit code `0xC0000135` (`XINPUT1_3.dll` not found). +- After: it starts and runs. + +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. + +PE imports of a probe exe built from the toolkit's `cellPad.c.obj` (`x86_64-w64-mingw32-objdump -p`, `DLL Name` lines): + +``` +before after +KERNEL32.dll KERNEL32.dll +msvcrt.dll msvcrt.dll +USER32.dll USER32.dll +XINPUT1_3.dll +``` + +Import entries that mention XInput or the loader: + +``` +before: GetProcAddress; XINPUT1_3.dll: XInputGetState, XInputSetState +after: FreeLibrary, GetProcAddress, LoadLibraryExW (no XInput import) +``` + +## Overlap + +- #472 (reopen a controller that is switched off and on again) and #466: each applies cleanly together with this change, in either order. +- #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. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-494/solution/patch.diff b/tasks/sp00nznet__ps3recomp-494/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..44a0a25be7e3b7b440f1816a765609ccb9e6fb2f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-494/solution/patch.diff @@ -0,0 +1,108 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index bdd2f85a..5d14c1b2 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -132,7 +132,6 @@ target_include_directories(ps3recomp_runtime PRIVATE + if(WIN32) + target_link_libraries(ps3recomp_runtime PRIVATE + ws2_32 # Winsock for network modules +- xinput # XInput for gamepad + ole32 # COM for WASAPI audio + bcrypt # BCryptGenRandom for SSL RNG + ) +diff --git a/libs/input/cellPad.c b/libs/input/cellPad.c +index 7fa8cab9..0f3c9324 100644 +--- a/libs/input/cellPad.c ++++ b/libs/input/cellPad.c +@@ -4,7 +4,8 @@ + * Reads real gamepad input from the host and translates to PS3 pad format. + * + * Backend selection: +- * - Windows default: XInput (no extra dependencies) ++ * - Windows default: XInput, loaded at run time from System32 (XInput1_4.dll, ++ * XInput1_3.dll, XInput9_1_0.dll); no XInput DLL means no pads + * - Everywhere else / if PS3RECOMP_PAD_USE_SDL2 is defined: SDL2 GameController + * + * Define PS3RECOMP_PAD_USE_SDL2 to force SDL2 backend on Windows. +@@ -53,8 +54,11 @@ static double pad_clock(unsigned long long t0_ms) + #define WIN32_LEAN_AND_MEAN + #endif + #include ++ /* Types only. The exe must not import an XInput DLL: MinGW's libxinput is ++ * xinput1_3.dll, which only the DirectX June 2010 redistributable installs, ++ * so on a stock Windows 10/11 the exe did not start (0xC0000135). The DLL is ++ * loaded at run time instead, see pad_xinput_load(). */ + #include +- #pragma comment(lib, "xinput.lib") + #endif + + #if PAD_BACKEND_SDL2 +@@ -143,6 +147,39 @@ static void pad_rumble_levels(u8 small_on, u8 large, u16* lo, u16* hi) + #define PAD_STICK_DEADZONE 7849 + #define PAD_TRIGGER_THRESHOLD 30 + ++/* XInput is resolved at run time. Only XInputGetState and XInputSetState are ++ * called, and XInput9_1_0.dll exports both, so any of the three DLLs serves. ++ * Loaded once, from System32 only (not the exe folder, the working directory ++ * or PATH), and kept loaded until exit. No DLL, or one without the two entry ++ * points, means every slot reads as unplugged. */ ++typedef DWORD (WINAPI *pad_xi_get_state_fn)(DWORD, XINPUT_STATE*); ++typedef DWORD (WINAPI *pad_xi_set_state_fn)(DWORD, XINPUT_VIBRATION*); ++static pad_xi_get_state_fn p_xi_get_state; ++static pad_xi_set_state_fn p_xi_set_state; ++static int s_xi_tried; ++ ++static int pad_xinput_load(void) ++{ ++ static const wchar_t* const names[] = { L"XInput1_4.dll", L"XInput1_3.dll", L"XInput9_1_0.dll" }; ++ if (s_xi_tried) return p_xi_get_state != NULL; ++ s_xi_tried = 1; ++ for (size_t k = 0; k < sizeof(names) / sizeof(names[0]); k++) { ++ HMODULE m = LoadLibraryExW(names[k], NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); ++ pad_xi_get_state_fn g; ++ pad_xi_set_state_fn st; ++ if (!m) continue; ++ g = (pad_xi_get_state_fn)(void (*)(void))GetProcAddress(m, "XInputGetState"); ++ st = (pad_xi_set_state_fn)(void (*)(void))GetProcAddress(m, "XInputSetState"); ++ if (!g || !st) { FreeLibrary(m); continue; } ++ p_xi_get_state = g; ++ p_xi_set_state = st; ++ printf("[cellPad] XInput from %ls\n", names[k]); ++ return 1; ++ } ++ printf("[cellPad] no XInput DLL (XInput1_4, XInput1_3, XInput9_1_0): no XInput pads\n"); ++ return 0; ++} ++ + static u8 pad_xinput_stick_to_u8(short raw, short deadzone) + { + float normalized; +@@ -240,7 +277,8 @@ static void pad_poll_xinput(void) + XINPUT_STATE state; + memset(&state, 0, sizeof(state)); + +- DWORD result = XInputGetState((DWORD)i, &state); ++ DWORD result = p_xi_get_state ? p_xi_get_state((DWORD)i, &state) ++ : ERROR_DEVICE_NOT_CONNECTED; + if (result != ERROR_SUCCESS) { + s_host_state[i].connected = 0; + continue; +@@ -299,7 +337,8 @@ static void pad_poll_xinput(void) + + static void pad_init_backend(void) + { +- /* XInput needs no explicit init */ ++ /* XInput needs no explicit init, only the run-time load of the DLL */ ++ pad_xinput_load(); + } + + static void pad_shutdown_backend(void) +@@ -1151,7 +1190,7 @@ s32 cellPadSetActDirect(u32 port_no, CellPadActParam* param) + XINPUT_VIBRATION vib; + vib.wLeftMotorSpeed = (WORD)lo; + vib.wRightMotorSpeed = (WORD)hi; +- XInputSetState((DWORD)port_no, &vib); ++ if (p_xi_set_state) p_xi_set_state((DWORD)port_no, &vib); + } + #endif + diff --git a/tasks/sp00nznet__ps3recomp-494/solution/solve.sh b/tasks/sp00nznet__ps3recomp-494/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-494/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-494/task.toml b/tasks/sp00nznet__ps3recomp-494/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2bae57e13de8a83aef947b8da1070d8027d80b31 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-494/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-494" +description = "cellPad: load XInput at run time, do not import it" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "a6d76c895f77eb30b90a806c830544e61821b77f" +reference = "https://github.com/sp00nznet/ps3recomp/pull/494" +source_access = "auto" +built_at = "2026-11-16T16:09:59.826729+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d092db26d28604c9aec44f95a4984acde163825341968f1da569c771f8044cf2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-26T15:32:55Z" +diff_format = "unified" +context_files = [ + "CMakeLists.txt", + "libs/input/cellPad.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 50 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.117579+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-494/tests/capture.py b/tasks/sp00nznet__ps3recomp-494/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-494/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-494/tests/instruction.md b/tasks/sp00nznet__ps3recomp-494/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fba828c7ab71b15268c191c4b4a8c06da5ad7f10 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-494/tests/instruction.md @@ -0,0 +1,69 @@ +# Issue + +**Title:** cellPad: load XInput at run time, do not import it + +## Description + +## Why + +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`. + +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. + +## Change + +- `CMakeLists.txt`: drop `xinput` from the Windows link libraries. +- `libs/input/cellPad.c`: + - Remove `#pragma comment(lib, "xinput.lib")` (MinGW ignores it). Keep `` for the types only. + - 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`. + - 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. + - `pad_init_backend()` calls it once at `cellPadInit`. The DLL stays loaded until exit. + - If no DLL loads, every slot reads as unplugged. The keyboard fallback on port 0 still works. Rumble does nothing. + - It prints one line: `[cellPad] XInput from `, or a "no XInput DLL" line. + +Linux, macOS and the SDL2 backend are not touched. + +## Tests + +Against master `a6d76c8`: + +- `git apply --check` and `patch -p1 --dry-run` both apply the patch cleanly (one `+++` header per file). +- 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). +- `libs/input/tests/test_pad_rumble.c`, built as `linux.yml` builds it: `test_pad_rumble: ok` on gcc and clang, before and after. +- 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. +- The `windows.yml` clang-cl build was not run here. Please let CI run it. + +## Evidence + +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: + +- Before: the exe does not start, exit code `0xC0000135` (`XINPUT1_3.dll` not found). +- After: it starts and runs. + +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. + +PE imports of a probe exe built from the toolkit's `cellPad.c.obj` (`x86_64-w64-mingw32-objdump -p`, `DLL Name` lines): + +``` +before after +KERNEL32.dll KERNEL32.dll +msvcrt.dll msvcrt.dll +USER32.dll USER32.dll +XINPUT1_3.dll +``` + +Import entries that mention XInput or the loader: + +``` +before: GetProcAddress; XINPUT1_3.dll: XInputGetState, XInputSetState +after: FreeLibrary, GetProcAddress, LoadLibraryExW (no XInput import) +``` + +## Overlap + +- #472 (reopen a controller that is switched off and on again) and #466: each applies cleanly together with this change, in either order. +- #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. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-494/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-494/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..44a0a25be7e3b7b440f1816a765609ccb9e6fb2f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-494/tests/oracle.patch @@ -0,0 +1,108 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index bdd2f85a..5d14c1b2 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -132,7 +132,6 @@ target_include_directories(ps3recomp_runtime PRIVATE + if(WIN32) + target_link_libraries(ps3recomp_runtime PRIVATE + ws2_32 # Winsock for network modules +- xinput # XInput for gamepad + ole32 # COM for WASAPI audio + bcrypt # BCryptGenRandom for SSL RNG + ) +diff --git a/libs/input/cellPad.c b/libs/input/cellPad.c +index 7fa8cab9..0f3c9324 100644 +--- a/libs/input/cellPad.c ++++ b/libs/input/cellPad.c +@@ -4,7 +4,8 @@ + * Reads real gamepad input from the host and translates to PS3 pad format. + * + * Backend selection: +- * - Windows default: XInput (no extra dependencies) ++ * - Windows default: XInput, loaded at run time from System32 (XInput1_4.dll, ++ * XInput1_3.dll, XInput9_1_0.dll); no XInput DLL means no pads + * - Everywhere else / if PS3RECOMP_PAD_USE_SDL2 is defined: SDL2 GameController + * + * Define PS3RECOMP_PAD_USE_SDL2 to force SDL2 backend on Windows. +@@ -53,8 +54,11 @@ static double pad_clock(unsigned long long t0_ms) + #define WIN32_LEAN_AND_MEAN + #endif + #include ++ /* Types only. The exe must not import an XInput DLL: MinGW's libxinput is ++ * xinput1_3.dll, which only the DirectX June 2010 redistributable installs, ++ * so on a stock Windows 10/11 the exe did not start (0xC0000135). The DLL is ++ * loaded at run time instead, see pad_xinput_load(). */ + #include +- #pragma comment(lib, "xinput.lib") + #endif + + #if PAD_BACKEND_SDL2 +@@ -143,6 +147,39 @@ static void pad_rumble_levels(u8 small_on, u8 large, u16* lo, u16* hi) + #define PAD_STICK_DEADZONE 7849 + #define PAD_TRIGGER_THRESHOLD 30 + ++/* XInput is resolved at run time. Only XInputGetState and XInputSetState are ++ * called, and XInput9_1_0.dll exports both, so any of the three DLLs serves. ++ * Loaded once, from System32 only (not the exe folder, the working directory ++ * or PATH), and kept loaded until exit. No DLL, or one without the two entry ++ * points, means every slot reads as unplugged. */ ++typedef DWORD (WINAPI *pad_xi_get_state_fn)(DWORD, XINPUT_STATE*); ++typedef DWORD (WINAPI *pad_xi_set_state_fn)(DWORD, XINPUT_VIBRATION*); ++static pad_xi_get_state_fn p_xi_get_state; ++static pad_xi_set_state_fn p_xi_set_state; ++static int s_xi_tried; ++ ++static int pad_xinput_load(void) ++{ ++ static const wchar_t* const names[] = { L"XInput1_4.dll", L"XInput1_3.dll", L"XInput9_1_0.dll" }; ++ if (s_xi_tried) return p_xi_get_state != NULL; ++ s_xi_tried = 1; ++ for (size_t k = 0; k < sizeof(names) / sizeof(names[0]); k++) { ++ HMODULE m = LoadLibraryExW(names[k], NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); ++ pad_xi_get_state_fn g; ++ pad_xi_set_state_fn st; ++ if (!m) continue; ++ g = (pad_xi_get_state_fn)(void (*)(void))GetProcAddress(m, "XInputGetState"); ++ st = (pad_xi_set_state_fn)(void (*)(void))GetProcAddress(m, "XInputSetState"); ++ if (!g || !st) { FreeLibrary(m); continue; } ++ p_xi_get_state = g; ++ p_xi_set_state = st; ++ printf("[cellPad] XInput from %ls\n", names[k]); ++ return 1; ++ } ++ printf("[cellPad] no XInput DLL (XInput1_4, XInput1_3, XInput9_1_0): no XInput pads\n"); ++ return 0; ++} ++ + static u8 pad_xinput_stick_to_u8(short raw, short deadzone) + { + float normalized; +@@ -240,7 +277,8 @@ static void pad_poll_xinput(void) + XINPUT_STATE state; + memset(&state, 0, sizeof(state)); + +- DWORD result = XInputGetState((DWORD)i, &state); ++ DWORD result = p_xi_get_state ? p_xi_get_state((DWORD)i, &state) ++ : ERROR_DEVICE_NOT_CONNECTED; + if (result != ERROR_SUCCESS) { + s_host_state[i].connected = 0; + continue; +@@ -299,7 +337,8 @@ static void pad_poll_xinput(void) + + static void pad_init_backend(void) + { +- /* XInput needs no explicit init */ ++ /* XInput needs no explicit init, only the run-time load of the DLL */ ++ pad_xinput_load(); + } + + static void pad_shutdown_backend(void) +@@ -1151,7 +1190,7 @@ s32 cellPadSetActDirect(u32 port_no, CellPadActParam* param) + XINPUT_VIBRATION vib; + vib.wLeftMotorSpeed = (WORD)lo; + vib.wRightMotorSpeed = (WORD)hi; +- XInputSetState((DWORD)port_no, &vib); ++ if (p_xi_set_state) p_xi_set_state((DWORD)port_no, &vib); + } + #endif + diff --git a/tasks/sp00nznet__ps3recomp-494/tests/test.sh b/tasks/sp00nznet__ps3recomp-494/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-494/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-494/tests/verifier.py b/tasks/sp00nznet__ps3recomp-494/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-494/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-495/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-495/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e58bcfa58777d72bba591f37e690838b686d5be --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-495/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-495/instruction.md b/tasks/sp00nznet__ps3recomp-495/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..65b3786be258af709761071c87da04950f167059 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-495/instruction.md @@ -0,0 +1,81 @@ +# Issue + +**Title:** cellVdec: never hand out handle 0 + +## Description + +## Why + +`cellVdecOpen` wrote the slot index as the handle, so the first decoder a title opens gets handle 0. Some titles treat a 0 handle as "no decoder open". + +Found while porting Killzone 2 with ps3recomp. Its movie player keeps the vdec handle as its "decoder open" flag. Its AU submit returns early (0x9B) when the handle is 0, so `cellVdecDecodeAu` was never called and the intro movie stalled. + +## Change + +`libs/codec/cellVdec.c`: + +- The handle the guest sees is the slot index + 1 (`VDEC_HANDLE_OF`). +- Every entry point maps it back with `VDEC_SLOT_OF` (Close, StartSeq, EndSeq, DecodeAu, GetPicItem, GetPicture, GetPictureExt, SetFrameRate). 0 and out-of-range handles map to `MAX_VDEC`, so they get `CELL_VDEC_ERROR_ARG` as before. GetPictureExt keeps its existing `CELL_OK` for an unknown handle. +- `vdec_notify` takes the slot and passes the guest handle to the callback, so the callback's first argument is the handle Open returned. +- The log lines print the guest handle. + +`libs/codec/tests/test_vdec_decode.c`: + +- `open_decoder` checks that Open never returns 0, and that `StartSeq(0)` and `StartSeq(0xFFFFFFFF)` return `CELL_VDEC_ERROR_ARG`. +- The fake guest caller checks that the callback's first argument equals Open's handle. +- The test no longer indexes `s_vdec[]` with the handle. It finds the slot Open used by looking for the one in-use slot. + +## Tests + +Linux x64, Debug, gcc 16.2.0 and clang 21.1.8, each run the way `linux.yml` does: + +- `cmake --build build` (default options): builds with both compilers. No warnings in `cellVdec.c`. +- `for t in tools/test_*.py` with `CI=1`: 75 passed, 0 failed, with both compilers. +- No workflow builds `libs/codec/tests`, so I also ran them: `-DPS3RECOMP_BUILD_TESTS=ON -DPS3RECOMP_FFMPEG_RUNTIME=ON` with libavcodec present, then `ctest -R vdec`. Result: `100% tests passed out of 10` with both compilers (vdec_stub, vdec_ffmpeg_disabled, vdec_ffmpeg_missing, vdec_media_gen, and vdec_decode / vdec_rgba / vdec_disabled for avc and mpeg2). +- I also built `test_vdec_decode.c` standalone with `-std=gnu17 -Wall -Wextra` (stub mode, as the other library tests are run in CI). No warnings with either compiler. It passes. + +New test against the old `cellVdec.c` (master's source, only the test file replaced), with both compilers: + +- All 9 vdec tests that open a decoder fail at `FAIL test_vdec_decode.c:147: s_open_handle != 0`. +- With that check taken out, `StartSeq(0)` fails next: `FAIL test_vdec_decode.c:148: cellVdecStartSeq(0) == (s32)CELL_VDEC_ERROR_ARG`. Master accepts it because slot 0 is in use. +- The callback-argument check cannot fail on master. There the handle and the callback argument are both the slot index (0), so they match. That check guards against a fix that changes one and not the other. + +Callers: nothing outside `cellVdec.c` calls the cellVdec entry points, `vdec_notify` or `s_vdec` directly. `cellVdecDivx` has its own handles. `tools/triage_elf.py` only lists the name `cellVdec`. No test cuts a cellVdec function out of the source by name. The only test is `test_vdec_decode.c`, which `#include`s the whole file and is updated here. + +## Evidence + +Killzone 2 (BCUS98116) through ps3recomp: + +- Before: cellVdecOpen and StartSeq run with handle 0, then no AU is ever submitted. The demuxer's video queue fills, and every movie thread waits. +- With this change: the intro decodes about 6,400 AUs and reaches the title screen. + +## Overlap + +**#471** (cellVdec idle drain) touches the same files. I applied it both ways on top of master: + +- #471 first, then this patch: one text conflict, in `cellVdecOpen`. +- This patch first, then #471: the same single conflict. + +Both orders resolve to identical files. The resolution keeps #471's `VDEC_UNLOCK();`, its `if (s_vdec[i].ff) {` brace and its `vdec_idle_thread_start();`, and this PR's `VDEC_HANDLE_OF(i)` in the `vm_write32` and in the "Open -> handle" log line: + +```c + VDEC_UNLOCK(); + vm_write32((u32)(uintptr_t)handle, (u32)VDEC_HANDLE_OF(i)); + printf("[cellVdec] Open -> handle=%u\n", (u32)VDEC_HANDLE_OF(i)); + if (s_vdec[i].ff) { + printf("[cellVdec] decoding with libavcodec\n"); + vdec_idle_thread_start(); + } +``` + +- **Semantic overlap:** #471's new `mode_idle` test indexes `s_vdec[h]` with the handle from Open. After the text merge it builds, but all four idle tests fail at `CHECK(s_vdec[h].ff)`, because handle 1 is slot 0. The fix is to use `s_open_slot->` instead of `s_vdec[h].` in `mode_idle` (4 lines). +- With that change, `ctest -R vdec` passes 14 of 14 with gcc and clang, including vdec_idle and vdec_idle_off for avc and mpeg2. +- #471's `cellVdec.c` code needs no change. Its idle thread loops over slot indices (`h = 0 .. MAX_VDEC-1`) and passes them to `vdec_notify_new_pics` / `vdec_notify`, which take a slot. The callback still receives the guest handle; the idle test's callback check passes. The idle thread's log line prints the slot index; that is cosmetic only. + +**#489** (guest callback stacks) is independent. It changes `runtime/memory/vm.h`, `runtime/ppu/ppu_loader.cpp` and adds its own tests; none of them are cellVdec files. It applies cleanly on top of this branch. It changes the stack a callback runs on, not the callback's arguments. That is a different cause: two decoders' callbacks clobbering each other's frames, not a 0 handle. + +Follow-up, not in this PR: cellAdec, cellDmux, cellVpost and cellSail also hand out 0 as their first handle. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-495/solution/patch.diff b/tasks/sp00nznet__ps3recomp-495/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..814d9093b9ffccf7d2146594937775d5d04d4b21 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-495/solution/patch.diff @@ -0,0 +1,207 @@ +diff --git a/libs/codec/cellVdec.c b/libs/codec/cellVdec.c +index 204a0055..28de1bdb 100644 +--- a/libs/codec/cellVdec.c ++++ b/libs/codec/cellVdec.c +@@ -58,18 +58,27 @@ typedef struct { + + static VdecSlot s_vdec[MAX_VDEC]; + ++/* The handle the guest sees is the slot index plus one, never 0: some ++ * titles treat a 0 handle as "no decoder open". ++ * Killzone 2's movie player keeps the handle as its "decoder open" flag and ++ * never submits an AU while it is 0, so slot 0's old handle 0 stalled its ++ * intro movie. VDEC_SLOT_OF maps 0 and any other handle out of range to ++ * MAX_VDEC, which every entry point rejects with CELL_VDEC_ERROR_ARG. */ ++#define VDEC_HANDLE_OF(slot) ((CellVdecHandle)((u32)(slot) + 1u)) ++#define VDEC_SLOT_OF(h) (((u32)(h) - 1u) < MAX_VDEC ? (u32)(h) - 1u : (u32)MAX_VDEC) ++ + /* Deliver a vdec message to the guest callback (handle, msgType, msgData, + * cbArg). It is a guest OPD, so it goes through g_ps3_guest_caller; this used + * to call it as a host function pointer, which crashes the first time a + * title's callback is reached. + * ponytail: synchronous on the caller's thread, like adec_notify; give it a + * decoder thread if a title's callback ever blocks on the DecodeAu caller. */ +-static void vdec_notify(CellVdecHandle handle, u32 msg_type, s32 msg_data) ++static void vdec_notify(u32 slot, u32 msg_type, s32 msg_data) + { +- if (handle >= MAX_VDEC || !s_vdec[handle].in_use) return; +- const VdecSlot* v = &s_vdec[handle]; ++ if (slot >= MAX_VDEC || !s_vdec[slot].in_use) return; ++ const VdecSlot* v = &s_vdec[slot]; + if (!v->cbFunc || !g_ps3_guest_caller) return; +- g_ps3_guest_caller(v->cbFunc, (u64)handle, (u64)msg_type, ++ g_ps3_guest_caller(v->cbFunc, (u64)VDEC_HANDLE_OF(slot), (u64)msg_type, + (u64)(s64)msg_data, (u64)v->cbArg, 0, 0, 0, 0); + } + +@@ -182,8 +191,8 @@ s32 cellVdecOpen(const CellVdecType* type, const CellVdecResource* res, + s_vdec[i].cbFunc = cb_ea ? vm_read32(cb_ea + 0) : 0; + s_vdec[i].cbArg = cb_ea ? vm_read32(cb_ea + 4) : 0; + s_vdec[i].ff = vdec_ff_open(codec_type); +- vm_write32((u32)(uintptr_t)handle, (u32)i); +- printf("[cellVdec] Open -> handle=%u\n", i); ++ vm_write32((u32)(uintptr_t)handle, (u32)VDEC_HANDLE_OF(i)); ++ printf("[cellVdec] Open -> handle=%u\n", (u32)VDEC_HANDLE_OF(i)); + if (s_vdec[i].ff) + printf("[cellVdec] decoding with libavcodec\n"); + return CELL_OK; +@@ -211,6 +220,7 @@ s32 cellVdecOpenEx(const CellVdecType* type, const CellVdecResource* res, + s32 cellVdecClose(CellVdecHandle handle) + { + printf("[cellVdec] Close(handle=%u)\n", handle); ++ handle = VDEC_SLOT_OF(handle); + + if (handle >= MAX_VDEC || !s_vdec[handle].in_use) + return (s32)CELL_VDEC_ERROR_ARG; +@@ -227,6 +237,7 @@ s32 cellVdecClose(CellVdecHandle handle) + s32 cellVdecStartSeq(CellVdecHandle handle) + { + printf("[cellVdec] StartSeq(handle=%u)\n", handle); ++ handle = VDEC_SLOT_OF(handle); + + if (handle >= MAX_VDEC || !s_vdec[handle].in_use) + return (s32)CELL_VDEC_ERROR_ARG; +@@ -244,6 +255,7 @@ s32 cellVdecStartSeq(CellVdecHandle handle) + s32 cellVdecEndSeq(CellVdecHandle handle) + { + printf("[cellVdec] EndSeq(handle=%u)\n", handle); ++ handle = VDEC_SLOT_OF(handle); + + if (handle >= MAX_VDEC || !s_vdec[handle].in_use) + return (s32)CELL_VDEC_ERROR_ARG; +@@ -266,6 +278,7 @@ s32 cellVdecEndSeq(CellVdecHandle handle) + s32 cellVdecDecodeAu(CellVdecHandle handle, s32 mode, const CellVdecAuInfo* auInfo) + { + (void)mode; ++ handle = VDEC_SLOT_OF(handle); + + if (handle >= MAX_VDEC || !s_vdec[handle].in_use) + return (s32)CELL_VDEC_ERROR_ARG; +@@ -286,7 +299,7 @@ s32 cellVdecDecodeAu(CellVdecHandle handle, s32 mode, const CellVdecAuInfo* auIn + au.userData = vm_read64(au_ea + (u32)offsetof(CellVdecAuInfo, userData)); + + printf("[cellVdec] DecodeAu(handle=%u, addr=0x%X, size=%u, pts=%llu)\n", +- handle, au.startAddr, au.size, ++ (u32)VDEC_HANDLE_OF(handle), au.startAddr, au.size, + (unsigned long long)au.pts); + + if (v->ff) { +@@ -412,6 +425,7 @@ static void vdec_write_pic_type(CellVdecHandle handle, const VdecPic* q) + * consuming it; cellVdecGetPicture is what takes it off the queue. */ + s32 cellVdecGetPicItem(CellVdecHandle handle, const CellVdecPicItem** picItem) + { ++ handle = VDEC_SLOT_OF(handle); + u32 out = (u32)(uintptr_t)picItem; + if (handle >= MAX_VDEC || !s_vdec[handle].in_use || !out) + return (s32)CELL_VDEC_ERROR_ARG; +@@ -456,6 +470,7 @@ static s32 vdec_take_picture(VdecSlot* v, u32 dst, u32 type, u32 matrix, u8 alph + + s32 cellVdecGetPicture(CellVdecHandle handle, const void* format, void* outBuff) + { ++ handle = VDEC_SLOT_OF(handle); + u32 fmt_ea = (u32)(uintptr_t)format, dst = (u32)(uintptr_t)outBuff; + if (handle >= MAX_VDEC || !s_vdec[handle].in_use || !fmt_ea) + return (s32)CELL_VDEC_ERROR_ARG; +@@ -504,6 +519,7 @@ s32 cellVdecGetPictureExt(CellVdecHandle handle, const void* format, + void* outBuff, u32 arg4) + { + (void)arg4; ++ handle = VDEC_SLOT_OF(handle); + u32 fmt_ea = (u32)(uintptr_t)format, dst = (u32)(uintptr_t)outBuff; + if (handle >= MAX_VDEC || !s_vdec[handle].in_use || !s_vdec[handle].ff) + return CELL_OK; +@@ -517,6 +533,7 @@ s32 cellVdecSetFrameRate(CellVdecHandle handle, u32 frameRateCode) + { + printf("[cellVdec] SetFrameRate(handle=%u, code=%u)\n", + handle, frameRateCode); ++ handle = VDEC_SLOT_OF(handle); + + if (handle >= MAX_VDEC || !s_vdec[handle].in_use) + return (s32)CELL_VDEC_ERROR_ARG; +diff --git a/libs/codec/tests/test_vdec_decode.c b/libs/codec/tests/test_vdec_decode.c +index 5aa78d9b..ff3ceab8 100644 +--- a/libs/codec/tests/test_vdec_decode.c ++++ b/libs/codec/tests/test_vdec_decode.c +@@ -60,12 +60,15 @@ void spu_lockline_unlock(void) {} + /* The guest callback: record the messages. */ + static u32 s_msgs[4096]; + static int s_nmsg; ++static u32 s_open_handle; /* the handle cellVdecOpen gave back */ ++static VdecSlot* s_open_slot; /* the slot it opened */ + static void fake_guest_call(uint32_t opd, uint64_t a0, uint64_t a1, uint64_t a2, + uint64_t a3, uint64_t a4, uint64_t a5, uint64_t a6, + uint64_t a7) + { +- (void)a0; (void)a2; (void)a4; (void)a5; (void)a6; (void)a7; ++ (void)a2; (void)a4; (void)a5; (void)a6; (void)a7; + CHECK(opd == CB_OPD && a3 == 0xC0FFEEu); ++ CHECK(a0 == s_open_handle); /* the callback names the guest's handle */ + if (s_nmsg < 4096) s_msgs[s_nmsg++] = (u32)a1; + } + ps3_guest_caller_fn g_ps3_guest_caller = fake_guest_call; +@@ -135,7 +138,16 @@ static u32 open_decoder(u32 codec) + CHECK(cellVdecOpen((const CellVdecType*)(uintptr_t)G_TYPE, NULL, + (const CellVdecCb*)(uintptr_t)G_CB, + (CellVdecHandle*)(uintptr_t)G_HANDLE) == CELL_OK); +- return vm_read32(G_HANDLE); ++ s_open_handle = vm_read32(G_HANDLE); ++ s_open_slot = NULL; ++ for (int i = 0; i < MAX_VDEC; i++) ++ if (s_vdec[i].in_use) { CHECK(!s_open_slot); s_open_slot = &s_vdec[i]; } ++ CHECK(s_open_slot); ++ /* Some titles read a 0 handle as "no decoder open". */ ++ CHECK(s_open_handle != 0); ++ CHECK(cellVdecStartSeq(0) == (s32)CELL_VDEC_ERROR_ARG); ++ CHECK(cellVdecStartSeq(0xFFFFFFFFu) == (s32)CELL_VDEC_ERROR_ARG); ++ return s_open_handle; + } + + static u64 au_pts(int i) { return 90000ull + 3600ull * (u64)i; } +@@ -241,7 +253,7 @@ static int mode_stub(int argc, char** argv) + s_nau = 8; for (int i = 0; i <= 8; i++) s_au_off[i] = (size_t)i * 64; } + + u32 h = open_decoder(codec); +- CHECK(s_vdec[h].ff == NULL); ++ CHECK(s_open_slot->ff == NULL); + s_nmsg = 0; + CHECK(cellVdecStartSeq(h) == CELL_OK); + for (int i = 0; i < 3 && i < s_nau; i++) { +@@ -251,7 +263,7 @@ static int mode_stub(int argc, char** argv) + && s_msgs[m0 + 1] == CELL_VDEC_MSG_TYPE_PICOUT); + CHECK(cellVdecGetPicItem(h, (const CellVdecPicItem**)(uintptr_t)G_ITEMPTR) == CELL_OK); + u32 it = vm_read32(G_ITEMPTR); +- CHECK(it == VDEC_ITEM_EA(h)); ++ CHECK(it == VDEC_ITEM_EA(s_open_slot - s_vdec)); + CHECK(vm_read32(it + 0x00) == codec); + CHECK(vm_read32(it + 0x04) == G_AU); + CHECK(vm_read32(it + 0x08) == (u32)(s_au_off[i + 1] - s_au_off[i])); +@@ -259,7 +271,7 @@ static int mode_stub(int argc, char** argv) + CHECK(vm_read32(it + 0x10) == (u32)(au_pts(i) >> 32) && vm_read32(it + 0x14) == (u32)au_pts(i)); + CHECK(vm_read32(it + 0x18) == 0xFFFFFFFFu && vm_read32(it + 0x1C) == 0xFFFFFFFFu); + CHECK(vm_read64(it + 0x30) == 0xABCD0000ull + (u64)i); +- CHECK(vm_read32(it + 0x48) == VDEC_INFO_EA(h)); ++ CHECK(vm_read32(it + 0x48) == VDEC_INFO_EA(s_open_slot - s_vdec)); + CHECK(vm_read16(it + 0x80) == 1280 && vm_read16(it + 0x82) == 720); + for (u32 o = 0x84; o < 0x100; o++) CHECK(vm_read8(it + o) == 0); + /* GetPictureExt never existed without a decoder: CELL_OK, nothing done. */ +@@ -297,7 +309,7 @@ static int mode_decode(int argc, char** argv) + s_frames = (u8*)malloc((size_t)MAX_AU * 2 * s_frame_size); + + u32 h = open_decoder(codec); +- if (!s_vdec[h].ff) { ++ if (!s_open_slot->ff) { + /* No loadable libavcodec here (not installed, or not on the loader + * path): a skip, not a failure. A library that loads but cannot open + * the decoder is still a failure. */ +@@ -373,9 +385,9 @@ static int mode_rgba(int argc, char** argv) + s_frames = (u8*)malloc((size_t)MAX_AU * 2 * s_frame_size); + u32 h = open_decoder(codec); + #ifdef PS3RECOMP_FFMPEG_RUNTIME +- if (!s_vdec[h].ff && !ps3_ffmpeg_get()) { printf("SKIP: libavcodec not loadable\n"); return 77; } ++ if (!s_open_slot->ff && !ps3_ffmpeg_get()) { printf("SKIP: libavcodec not loadable\n"); return 77; } + #endif +- CHECK(s_vdec[h].ff); ++ CHECK(s_open_slot->ff); + + /* RGBA32: bytes R G B A. */ + run_sequence(h, codec, es, -1, 1); diff --git a/tasks/sp00nznet__ps3recomp-495/solution/solve.sh b/tasks/sp00nznet__ps3recomp-495/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-495/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-495/task.toml b/tasks/sp00nznet__ps3recomp-495/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..155308354665dc7598ab10bb3f9bcff6793e6714 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-495/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-495" +description = "cellVdec: never hand out handle 0" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "a6d76c895f77eb30b90a806c830544e61821b77f" +reference = "https://github.com/sp00nznet/ps3recomp/pull/495" +source_access = "auto" +built_at = "2026-11-16T16:09:59.810886+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3e199b8c2ac800370b1b6cc9739e8ee981be9ffb720e7e60261d4978e1865754" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-26T15:32:55Z" +diff_format = "unified" +context_files = [ + "libs/codec/cellVdec.c", + "libs/codec/tests/test_vdec_decode.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 59 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.118094+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-495/tests/capture.py b/tasks/sp00nznet__ps3recomp-495/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-495/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-495/tests/instruction.md b/tasks/sp00nznet__ps3recomp-495/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..65b3786be258af709761071c87da04950f167059 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-495/tests/instruction.md @@ -0,0 +1,81 @@ +# Issue + +**Title:** cellVdec: never hand out handle 0 + +## Description + +## Why + +`cellVdecOpen` wrote the slot index as the handle, so the first decoder a title opens gets handle 0. Some titles treat a 0 handle as "no decoder open". + +Found while porting Killzone 2 with ps3recomp. Its movie player keeps the vdec handle as its "decoder open" flag. Its AU submit returns early (0x9B) when the handle is 0, so `cellVdecDecodeAu` was never called and the intro movie stalled. + +## Change + +`libs/codec/cellVdec.c`: + +- The handle the guest sees is the slot index + 1 (`VDEC_HANDLE_OF`). +- Every entry point maps it back with `VDEC_SLOT_OF` (Close, StartSeq, EndSeq, DecodeAu, GetPicItem, GetPicture, GetPictureExt, SetFrameRate). 0 and out-of-range handles map to `MAX_VDEC`, so they get `CELL_VDEC_ERROR_ARG` as before. GetPictureExt keeps its existing `CELL_OK` for an unknown handle. +- `vdec_notify` takes the slot and passes the guest handle to the callback, so the callback's first argument is the handle Open returned. +- The log lines print the guest handle. + +`libs/codec/tests/test_vdec_decode.c`: + +- `open_decoder` checks that Open never returns 0, and that `StartSeq(0)` and `StartSeq(0xFFFFFFFF)` return `CELL_VDEC_ERROR_ARG`. +- The fake guest caller checks that the callback's first argument equals Open's handle. +- The test no longer indexes `s_vdec[]` with the handle. It finds the slot Open used by looking for the one in-use slot. + +## Tests + +Linux x64, Debug, gcc 16.2.0 and clang 21.1.8, each run the way `linux.yml` does: + +- `cmake --build build` (default options): builds with both compilers. No warnings in `cellVdec.c`. +- `for t in tools/test_*.py` with `CI=1`: 75 passed, 0 failed, with both compilers. +- No workflow builds `libs/codec/tests`, so I also ran them: `-DPS3RECOMP_BUILD_TESTS=ON -DPS3RECOMP_FFMPEG_RUNTIME=ON` with libavcodec present, then `ctest -R vdec`. Result: `100% tests passed out of 10` with both compilers (vdec_stub, vdec_ffmpeg_disabled, vdec_ffmpeg_missing, vdec_media_gen, and vdec_decode / vdec_rgba / vdec_disabled for avc and mpeg2). +- I also built `test_vdec_decode.c` standalone with `-std=gnu17 -Wall -Wextra` (stub mode, as the other library tests are run in CI). No warnings with either compiler. It passes. + +New test against the old `cellVdec.c` (master's source, only the test file replaced), with both compilers: + +- All 9 vdec tests that open a decoder fail at `FAIL test_vdec_decode.c:147: s_open_handle != 0`. +- With that check taken out, `StartSeq(0)` fails next: `FAIL test_vdec_decode.c:148: cellVdecStartSeq(0) == (s32)CELL_VDEC_ERROR_ARG`. Master accepts it because slot 0 is in use. +- The callback-argument check cannot fail on master. There the handle and the callback argument are both the slot index (0), so they match. That check guards against a fix that changes one and not the other. + +Callers: nothing outside `cellVdec.c` calls the cellVdec entry points, `vdec_notify` or `s_vdec` directly. `cellVdecDivx` has its own handles. `tools/triage_elf.py` only lists the name `cellVdec`. No test cuts a cellVdec function out of the source by name. The only test is `test_vdec_decode.c`, which `#include`s the whole file and is updated here. + +## Evidence + +Killzone 2 (BCUS98116) through ps3recomp: + +- Before: cellVdecOpen and StartSeq run with handle 0, then no AU is ever submitted. The demuxer's video queue fills, and every movie thread waits. +- With this change: the intro decodes about 6,400 AUs and reaches the title screen. + +## Overlap + +**#471** (cellVdec idle drain) touches the same files. I applied it both ways on top of master: + +- #471 first, then this patch: one text conflict, in `cellVdecOpen`. +- This patch first, then #471: the same single conflict. + +Both orders resolve to identical files. The resolution keeps #471's `VDEC_UNLOCK();`, its `if (s_vdec[i].ff) {` brace and its `vdec_idle_thread_start();`, and this PR's `VDEC_HANDLE_OF(i)` in the `vm_write32` and in the "Open -> handle" log line: + +```c + VDEC_UNLOCK(); + vm_write32((u32)(uintptr_t)handle, (u32)VDEC_HANDLE_OF(i)); + printf("[cellVdec] Open -> handle=%u\n", (u32)VDEC_HANDLE_OF(i)); + if (s_vdec[i].ff) { + printf("[cellVdec] decoding with libavcodec\n"); + vdec_idle_thread_start(); + } +``` + +- **Semantic overlap:** #471's new `mode_idle` test indexes `s_vdec[h]` with the handle from Open. After the text merge it builds, but all four idle tests fail at `CHECK(s_vdec[h].ff)`, because handle 1 is slot 0. The fix is to use `s_open_slot->` instead of `s_vdec[h].` in `mode_idle` (4 lines). +- With that change, `ctest -R vdec` passes 14 of 14 with gcc and clang, including vdec_idle and vdec_idle_off for avc and mpeg2. +- #471's `cellVdec.c` code needs no change. Its idle thread loops over slot indices (`h = 0 .. MAX_VDEC-1`) and passes them to `vdec_notify_new_pics` / `vdec_notify`, which take a slot. The callback still receives the guest handle; the idle test's callback check passes. The idle thread's log line prints the slot index; that is cosmetic only. + +**#489** (guest callback stacks) is independent. It changes `runtime/memory/vm.h`, `runtime/ppu/ppu_loader.cpp` and adds its own tests; none of them are cellVdec files. It applies cleanly on top of this branch. It changes the stack a callback runs on, not the callback's arguments. That is a different cause: two decoders' callbacks clobbering each other's frames, not a 0 handle. + +Follow-up, not in this PR: cellAdec, cellDmux, cellVpost and cellSail also hand out 0 as their first handle. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-495/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-495/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..814d9093b9ffccf7d2146594937775d5d04d4b21 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-495/tests/oracle.patch @@ -0,0 +1,207 @@ +diff --git a/libs/codec/cellVdec.c b/libs/codec/cellVdec.c +index 204a0055..28de1bdb 100644 +--- a/libs/codec/cellVdec.c ++++ b/libs/codec/cellVdec.c +@@ -58,18 +58,27 @@ typedef struct { + + static VdecSlot s_vdec[MAX_VDEC]; + ++/* The handle the guest sees is the slot index plus one, never 0: some ++ * titles treat a 0 handle as "no decoder open". ++ * Killzone 2's movie player keeps the handle as its "decoder open" flag and ++ * never submits an AU while it is 0, so slot 0's old handle 0 stalled its ++ * intro movie. VDEC_SLOT_OF maps 0 and any other handle out of range to ++ * MAX_VDEC, which every entry point rejects with CELL_VDEC_ERROR_ARG. */ ++#define VDEC_HANDLE_OF(slot) ((CellVdecHandle)((u32)(slot) + 1u)) ++#define VDEC_SLOT_OF(h) (((u32)(h) - 1u) < MAX_VDEC ? (u32)(h) - 1u : (u32)MAX_VDEC) ++ + /* Deliver a vdec message to the guest callback (handle, msgType, msgData, + * cbArg). It is a guest OPD, so it goes through g_ps3_guest_caller; this used + * to call it as a host function pointer, which crashes the first time a + * title's callback is reached. + * ponytail: synchronous on the caller's thread, like adec_notify; give it a + * decoder thread if a title's callback ever blocks on the DecodeAu caller. */ +-static void vdec_notify(CellVdecHandle handle, u32 msg_type, s32 msg_data) ++static void vdec_notify(u32 slot, u32 msg_type, s32 msg_data) + { +- if (handle >= MAX_VDEC || !s_vdec[handle].in_use) return; +- const VdecSlot* v = &s_vdec[handle]; ++ if (slot >= MAX_VDEC || !s_vdec[slot].in_use) return; ++ const VdecSlot* v = &s_vdec[slot]; + if (!v->cbFunc || !g_ps3_guest_caller) return; +- g_ps3_guest_caller(v->cbFunc, (u64)handle, (u64)msg_type, ++ g_ps3_guest_caller(v->cbFunc, (u64)VDEC_HANDLE_OF(slot), (u64)msg_type, + (u64)(s64)msg_data, (u64)v->cbArg, 0, 0, 0, 0); + } + +@@ -182,8 +191,8 @@ s32 cellVdecOpen(const CellVdecType* type, const CellVdecResource* res, + s_vdec[i].cbFunc = cb_ea ? vm_read32(cb_ea + 0) : 0; + s_vdec[i].cbArg = cb_ea ? vm_read32(cb_ea + 4) : 0; + s_vdec[i].ff = vdec_ff_open(codec_type); +- vm_write32((u32)(uintptr_t)handle, (u32)i); +- printf("[cellVdec] Open -> handle=%u\n", i); ++ vm_write32((u32)(uintptr_t)handle, (u32)VDEC_HANDLE_OF(i)); ++ printf("[cellVdec] Open -> handle=%u\n", (u32)VDEC_HANDLE_OF(i)); + if (s_vdec[i].ff) + printf("[cellVdec] decoding with libavcodec\n"); + return CELL_OK; +@@ -211,6 +220,7 @@ s32 cellVdecOpenEx(const CellVdecType* type, const CellVdecResource* res, + s32 cellVdecClose(CellVdecHandle handle) + { + printf("[cellVdec] Close(handle=%u)\n", handle); ++ handle = VDEC_SLOT_OF(handle); + + if (handle >= MAX_VDEC || !s_vdec[handle].in_use) + return (s32)CELL_VDEC_ERROR_ARG; +@@ -227,6 +237,7 @@ s32 cellVdecClose(CellVdecHandle handle) + s32 cellVdecStartSeq(CellVdecHandle handle) + { + printf("[cellVdec] StartSeq(handle=%u)\n", handle); ++ handle = VDEC_SLOT_OF(handle); + + if (handle >= MAX_VDEC || !s_vdec[handle].in_use) + return (s32)CELL_VDEC_ERROR_ARG; +@@ -244,6 +255,7 @@ s32 cellVdecStartSeq(CellVdecHandle handle) + s32 cellVdecEndSeq(CellVdecHandle handle) + { + printf("[cellVdec] EndSeq(handle=%u)\n", handle); ++ handle = VDEC_SLOT_OF(handle); + + if (handle >= MAX_VDEC || !s_vdec[handle].in_use) + return (s32)CELL_VDEC_ERROR_ARG; +@@ -266,6 +278,7 @@ s32 cellVdecEndSeq(CellVdecHandle handle) + s32 cellVdecDecodeAu(CellVdecHandle handle, s32 mode, const CellVdecAuInfo* auInfo) + { + (void)mode; ++ handle = VDEC_SLOT_OF(handle); + + if (handle >= MAX_VDEC || !s_vdec[handle].in_use) + return (s32)CELL_VDEC_ERROR_ARG; +@@ -286,7 +299,7 @@ s32 cellVdecDecodeAu(CellVdecHandle handle, s32 mode, const CellVdecAuInfo* auIn + au.userData = vm_read64(au_ea + (u32)offsetof(CellVdecAuInfo, userData)); + + printf("[cellVdec] DecodeAu(handle=%u, addr=0x%X, size=%u, pts=%llu)\n", +- handle, au.startAddr, au.size, ++ (u32)VDEC_HANDLE_OF(handle), au.startAddr, au.size, + (unsigned long long)au.pts); + + if (v->ff) { +@@ -412,6 +425,7 @@ static void vdec_write_pic_type(CellVdecHandle handle, const VdecPic* q) + * consuming it; cellVdecGetPicture is what takes it off the queue. */ + s32 cellVdecGetPicItem(CellVdecHandle handle, const CellVdecPicItem** picItem) + { ++ handle = VDEC_SLOT_OF(handle); + u32 out = (u32)(uintptr_t)picItem; + if (handle >= MAX_VDEC || !s_vdec[handle].in_use || !out) + return (s32)CELL_VDEC_ERROR_ARG; +@@ -456,6 +470,7 @@ static s32 vdec_take_picture(VdecSlot* v, u32 dst, u32 type, u32 matrix, u8 alph + + s32 cellVdecGetPicture(CellVdecHandle handle, const void* format, void* outBuff) + { ++ handle = VDEC_SLOT_OF(handle); + u32 fmt_ea = (u32)(uintptr_t)format, dst = (u32)(uintptr_t)outBuff; + if (handle >= MAX_VDEC || !s_vdec[handle].in_use || !fmt_ea) + return (s32)CELL_VDEC_ERROR_ARG; +@@ -504,6 +519,7 @@ s32 cellVdecGetPictureExt(CellVdecHandle handle, const void* format, + void* outBuff, u32 arg4) + { + (void)arg4; ++ handle = VDEC_SLOT_OF(handle); + u32 fmt_ea = (u32)(uintptr_t)format, dst = (u32)(uintptr_t)outBuff; + if (handle >= MAX_VDEC || !s_vdec[handle].in_use || !s_vdec[handle].ff) + return CELL_OK; +@@ -517,6 +533,7 @@ s32 cellVdecSetFrameRate(CellVdecHandle handle, u32 frameRateCode) + { + printf("[cellVdec] SetFrameRate(handle=%u, code=%u)\n", + handle, frameRateCode); ++ handle = VDEC_SLOT_OF(handle); + + if (handle >= MAX_VDEC || !s_vdec[handle].in_use) + return (s32)CELL_VDEC_ERROR_ARG; +diff --git a/libs/codec/tests/test_vdec_decode.c b/libs/codec/tests/test_vdec_decode.c +index 5aa78d9b..ff3ceab8 100644 +--- a/libs/codec/tests/test_vdec_decode.c ++++ b/libs/codec/tests/test_vdec_decode.c +@@ -60,12 +60,15 @@ void spu_lockline_unlock(void) {} + /* The guest callback: record the messages. */ + static u32 s_msgs[4096]; + static int s_nmsg; ++static u32 s_open_handle; /* the handle cellVdecOpen gave back */ ++static VdecSlot* s_open_slot; /* the slot it opened */ + static void fake_guest_call(uint32_t opd, uint64_t a0, uint64_t a1, uint64_t a2, + uint64_t a3, uint64_t a4, uint64_t a5, uint64_t a6, + uint64_t a7) + { +- (void)a0; (void)a2; (void)a4; (void)a5; (void)a6; (void)a7; ++ (void)a2; (void)a4; (void)a5; (void)a6; (void)a7; + CHECK(opd == CB_OPD && a3 == 0xC0FFEEu); ++ CHECK(a0 == s_open_handle); /* the callback names the guest's handle */ + if (s_nmsg < 4096) s_msgs[s_nmsg++] = (u32)a1; + } + ps3_guest_caller_fn g_ps3_guest_caller = fake_guest_call; +@@ -135,7 +138,16 @@ static u32 open_decoder(u32 codec) + CHECK(cellVdecOpen((const CellVdecType*)(uintptr_t)G_TYPE, NULL, + (const CellVdecCb*)(uintptr_t)G_CB, + (CellVdecHandle*)(uintptr_t)G_HANDLE) == CELL_OK); +- return vm_read32(G_HANDLE); ++ s_open_handle = vm_read32(G_HANDLE); ++ s_open_slot = NULL; ++ for (int i = 0; i < MAX_VDEC; i++) ++ if (s_vdec[i].in_use) { CHECK(!s_open_slot); s_open_slot = &s_vdec[i]; } ++ CHECK(s_open_slot); ++ /* Some titles read a 0 handle as "no decoder open". */ ++ CHECK(s_open_handle != 0); ++ CHECK(cellVdecStartSeq(0) == (s32)CELL_VDEC_ERROR_ARG); ++ CHECK(cellVdecStartSeq(0xFFFFFFFFu) == (s32)CELL_VDEC_ERROR_ARG); ++ return s_open_handle; + } + + static u64 au_pts(int i) { return 90000ull + 3600ull * (u64)i; } +@@ -241,7 +253,7 @@ static int mode_stub(int argc, char** argv) + s_nau = 8; for (int i = 0; i <= 8; i++) s_au_off[i] = (size_t)i * 64; } + + u32 h = open_decoder(codec); +- CHECK(s_vdec[h].ff == NULL); ++ CHECK(s_open_slot->ff == NULL); + s_nmsg = 0; + CHECK(cellVdecStartSeq(h) == CELL_OK); + for (int i = 0; i < 3 && i < s_nau; i++) { +@@ -251,7 +263,7 @@ static int mode_stub(int argc, char** argv) + && s_msgs[m0 + 1] == CELL_VDEC_MSG_TYPE_PICOUT); + CHECK(cellVdecGetPicItem(h, (const CellVdecPicItem**)(uintptr_t)G_ITEMPTR) == CELL_OK); + u32 it = vm_read32(G_ITEMPTR); +- CHECK(it == VDEC_ITEM_EA(h)); ++ CHECK(it == VDEC_ITEM_EA(s_open_slot - s_vdec)); + CHECK(vm_read32(it + 0x00) == codec); + CHECK(vm_read32(it + 0x04) == G_AU); + CHECK(vm_read32(it + 0x08) == (u32)(s_au_off[i + 1] - s_au_off[i])); +@@ -259,7 +271,7 @@ static int mode_stub(int argc, char** argv) + CHECK(vm_read32(it + 0x10) == (u32)(au_pts(i) >> 32) && vm_read32(it + 0x14) == (u32)au_pts(i)); + CHECK(vm_read32(it + 0x18) == 0xFFFFFFFFu && vm_read32(it + 0x1C) == 0xFFFFFFFFu); + CHECK(vm_read64(it + 0x30) == 0xABCD0000ull + (u64)i); +- CHECK(vm_read32(it + 0x48) == VDEC_INFO_EA(h)); ++ CHECK(vm_read32(it + 0x48) == VDEC_INFO_EA(s_open_slot - s_vdec)); + CHECK(vm_read16(it + 0x80) == 1280 && vm_read16(it + 0x82) == 720); + for (u32 o = 0x84; o < 0x100; o++) CHECK(vm_read8(it + o) == 0); + /* GetPictureExt never existed without a decoder: CELL_OK, nothing done. */ +@@ -297,7 +309,7 @@ static int mode_decode(int argc, char** argv) + s_frames = (u8*)malloc((size_t)MAX_AU * 2 * s_frame_size); + + u32 h = open_decoder(codec); +- if (!s_vdec[h].ff) { ++ if (!s_open_slot->ff) { + /* No loadable libavcodec here (not installed, or not on the loader + * path): a skip, not a failure. A library that loads but cannot open + * the decoder is still a failure. */ +@@ -373,9 +385,9 @@ static int mode_rgba(int argc, char** argv) + s_frames = (u8*)malloc((size_t)MAX_AU * 2 * s_frame_size); + u32 h = open_decoder(codec); + #ifdef PS3RECOMP_FFMPEG_RUNTIME +- if (!s_vdec[h].ff && !ps3_ffmpeg_get()) { printf("SKIP: libavcodec not loadable\n"); return 77; } ++ if (!s_open_slot->ff && !ps3_ffmpeg_get()) { printf("SKIP: libavcodec not loadable\n"); return 77; } + #endif +- CHECK(s_vdec[h].ff); ++ CHECK(s_open_slot->ff); + + /* RGBA32: bytes R G B A. */ + run_sequence(h, codec, es, -1, 1); diff --git a/tasks/sp00nznet__ps3recomp-495/tests/test.sh b/tasks/sp00nznet__ps3recomp-495/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-495/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-495/tests/verifier.py b/tasks/sp00nznet__ps3recomp-495/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-495/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-503/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-503/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e58bcfa58777d72bba591f37e690838b686d5be --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-503/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-503/instruction.md b/tasks/sp00nznet__ps3recomp-503/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..76fd4bbd68be27d6e5bc2e270a1449c96edac1eb --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-503/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** cellNetCtl: offline, the net-start dialog ends cancelled + +## Description + +## Why + +From the inFAMOUS 2 native port. `cellNetCtlNetStartDialogUnloadAsync` always reported `result = 0` (connected), even offline, where `cellNetCtlGetState` fails and `GetInfo` reports the link down. inFAMOUS 2 believed the dialog and went on to the PSN terms-of-service check, which never answers offline, so it sat behind an endless "Please wait..." box. + +RPCS3 ends the dialog with `CELL_NET_CTL_ERROR_DIALOG_CANCELED` when there is no network (`result->result = nph.get_net_status() == CELL_NET_CTL_STATE_IPObtained ? 0 : CELL_NET_CTL_ERROR_DIALOG_CANCELED;` in `cellNetCtl.cpp`). A cancelled connection is a path every title handles. + +## What + +- Offline (the default) the dialog's result is `CELL_NET_CTL_ERROR_DIALOG_CANCELED` (0x80130190), written big-endian. The old 0 was the same in either byte order, so the store never had to swap before. +- `PS3_NET_ONLINE=1` keeps the old answer, connected, in line with what `GetState` says in that mode. +- The LOADED / FINISHED / UNLOADED events are unchanged. +- The log line names the result. + +To get the old behaviour back, set `PS3_NET_ONLINE=1`. + +## Tests + +- New `libs/network/tests/test_netctl_netstart.c` (in the macOS and Linux workflows). It runs twice: offline the result word reads 0x80130190 big-endian, and with `PS3_NET_ONLINE=1` it reads 0. In both runs UNLOADED goes to every callback slot. +- In the port, the "Please wait..." box closes and inFAMOUS 2 carries on offline. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-503/solution/patch.diff b/tasks/sp00nznet__ps3recomp-503/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..252b99502380c17d54cc926acd7bb0f4c62bbc77 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-503/solution/patch.diff @@ -0,0 +1,153 @@ +diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml +index 67bb40b3..cb846514 100644 +--- a/.github/workflows/linux.yml ++++ b/.github/workflows/linux.yml +@@ -144,6 +144,14 @@ jobs: + ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} -std=gnu17 -I include -o /tmp/test_np_identity libs/network/tests/test_np_identity.c + /tmp/test_np_identity + ++ # The net-start dialog ends cancelled offline and connected with ++ # PS3_NET_ONLINE=1, its result word big-endian. ++ - name: Run the net-start dialog test ++ run: | ++ ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} -std=gnu17 -I include -I libs/system -o /tmp/test_netctl_netstart libs/network/tests/test_netctl_netstart.c ++ /tmp/test_netctl_netstart ++ PS3_NET_ONLINE=1 /tmp/test_netctl_netstart ++ + # cellVideoOutSetGamma's float argument comes from f1, and the value + # reaches the presenter. + - name: Run the video out gamma test +diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml +index 19e9eb18..dd524f17 100644 +--- a/.github/workflows/macos.yml ++++ b/.github/workflows/macos.yml +@@ -102,6 +102,14 @@ jobs: + clang -std=gnu17 -I include -o /tmp/test_np_identity libs/network/tests/test_np_identity.c + /tmp/test_np_identity + ++ # The net-start dialog ends cancelled offline and connected with ++ # PS3_NET_ONLINE=1, its result word big-endian. ++ - name: Run the net-start dialog test ++ run: | ++ clang -std=gnu17 -I include -I libs/system -o /tmp/test_netctl_netstart libs/network/tests/test_netctl_netstart.c ++ /tmp/test_netctl_netstart ++ PS3_NET_ONLINE=1 /tmp/test_netctl_netstart ++ + # cellVideoOutSetGamma's float argument comes from f1, and the value + # reaches the presenter. + - name: Run the video out gamma test +diff --git a/libs/network/cellNetCtl.c b/libs/network/cellNetCtl.c +index c7926c0c..8c0594b7 100644 +--- a/libs/network/cellNetCtl.c ++++ b/libs/network/cellNetCtl.c +@@ -330,10 +330,11 @@ s32 cellNetCtlDelHandler(s32 hid) + * Real hardware shows a system dialog and signals progress asynchronously + * through the cellSysutil callback queue (LOADED -> FINISHED), after which the + * game calls UnloadAsync to retrieve the result. In an offline native recomp +- * there is nothing to show and we are already "connected", so we immediately +- * post LOADED + FINISHED to every registered sysutil callback slot and report a +- * successful result on unload. This unblocks the common boot-time "connecting +- * to network" gate without requiring a real PSN session. ++ * there is nothing to show, so we immediately post LOADED + FINISHED to every ++ * registered sysutil callback slot. On unload the result is "connected" with ++ * PS3_NET_ONLINE=1 and "cancelled" otherwise, matching what GetState reports. ++ * This unblocks the common boot-time "connecting to network" gate without ++ * requiring a real PSN session. + * -----------------------------------------------------------------------*/ + + static void netstart_broadcast(u32 status) +@@ -361,11 +362,18 @@ s32 cellNetCtlNetStartDialogAbortAsync(void) + + s32 cellNetCtlNetStartDialogUnloadAsync(CellNetCtlNetStartDialogResult* result) + { ++ /* Offline (the default), the dialog ends as if the player cancelled it, ++ * as RPCS3 reports it without a network: "connected" while GetState says ++ * there is no network sent inFAMOUS 2 on to a PSN terms-of-service check ++ * that never answers, behind an endless "Please wait...". A cancelled ++ * connection is a path every title handles. PS3_NET_ONLINE=1: connected. */ ++ const u32 res = netctl_online() ? 0u : (u32)CELL_NET_CTL_ERROR_DIALOG_CANCELED; + if (result) { + result = GUEST_PTR(result, CellNetCtlNetStartDialogResult*); +- result->result = 0; /* 0 = connected; endian-safe */ ++ result->result = (s32)ps3_bswap32(res); /* guest big-endian */ + } +- printf("[cellNetCtl] NetStartDialogUnloadAsync() -> result=0 (connected)\n"); ++ printf("[cellNetCtl] NetStartDialogUnloadAsync() -> result=0x%08X (%s)\n", res, ++ res ? "cancelled: offline" : "connected"); + netstart_broadcast(CELL_SYSUTIL_NET_CTL_NETSTART_UNLOADED); + return CELL_OK; + } +diff --git a/libs/network/cellNetCtl.h b/libs/network/cellNetCtl.h +index c5ab148b..f433becb 100644 +--- a/libs/network/cellNetCtl.h ++++ b/libs/network/cellNetCtl.h +@@ -182,7 +182,8 @@ s32 cellNetCtlAddHandler(cellNetCtlHandler handler, void* arg, s32* hid); + s32 cellNetCtlDelHandler(s32 hid); + + /* Net-start ("connect to PSN") dialog. In an offline native recomp we never +- * show it — these report an immediate successful connection. */ ++ * show it: it finishes at once, connected with PS3_NET_ONLINE=1 and cancelled ++ * (CELL_NET_CTL_ERROR_DIALOG_CANCELED) otherwise. */ + s32 cellNetCtlNetStartDialogLoadAsync(const CellNetCtlNetStartDialogParam* param); + s32 cellNetCtlNetStartDialogAbortAsync(void); + s32 cellNetCtlNetStartDialogUnloadAsync(CellNetCtlNetStartDialogResult* result); +diff --git a/libs/network/tests/test_netctl_netstart.c b/libs/network/tests/test_netctl_netstart.c +new file mode 100644 +index 00000000..3d6bdef3 +--- /dev/null ++++ b/libs/network/tests/test_netctl_netstart.c +@@ -0,0 +1,54 @@ ++/* ++ * test_netctl_netstart - the result the net-start dialog ends with. ++ * ++ * cc -std=gnu17 -I include -I libs/system -o test_netctl_netstart libs/network/tests/test_netctl_netstart.c ++ * ++ * Offline the dialog ends cancelled (CELL_NET_CTL_ERROR_DIALOG_CANCELED, as ++ * RPCS3 reports it without a network), so a title does not go on to the PSN ++ * steps GetState already said are unreachable; PS3_NET_ONLINE=1 ends it ++ * connected. The result word is big-endian in guest memory. Run it with and ++ * without PS3_NET_ONLINE=1. ++ */ ++#include "../cellNetCtl.c" ++ ++#include ++ ++uint8_t* vm_base; ++int g_resv_store_active; ++uint32_t g_ww_lo, g_ww_hi; ++void ppu_resv_break_store(uint64_t ea) { (void)ea; } ++void ps3_ww_report_inline(uint32_t a, uint64_t v, int w) { (void)a; (void)v; (void)w; } ++int spu_coh_is_reserved(uint32_t a) { (void)a; return 0; } ++void spu_coh_notify_write(uint32_t a) { (void)a; } ++void spu_lockline_lock(void) {} ++void spu_lockline_unlock(void) {} ++ ++static int s_unloaded; ++void cellSysutilQueueEvent(int slot, u32 status, u32 param) ++{ ++ (void)slot; (void)param; ++ if (status == CELL_SYSUTIL_NET_CTL_NETSTART_UNLOADED) s_unloaded++; ++} ++const char* np_psnr_identity(void) { return "PS3Player"; } ++ ++static u32 be32_at(u32 ea) ++{ ++ const uint8_t* p = vm_base + ea; ++ return (u32)p[0] << 24 | (u32)p[1] << 16 | (u32)p[2] << 8 | p[3]; ++} ++ ++int main(void) ++{ ++ static uint8_t mem[0x10000]; ++ vm_base = mem; ++ const u32 ea = 0x1000; /* CellNetCtlNetStartDialogResult: size, result */ ++ ++ const int online = getenv("PS3_NET_ONLINE") != NULL; ++ mem[ea + 4] = 0xAA; /* the result word is written, not left */ ++ assert(cellNetCtlNetStartDialogUnloadAsync((CellNetCtlNetStartDialogResult*)(uintptr_t)ea) == CELL_OK); ++ if (online) assert(be32_at(ea + 4) == 0u); ++ else assert(be32_at(ea + 4) == 0x80130190u); /* CELL_NET_CTL_ERROR_DIALOG_CANCELED */ ++ assert(s_unloaded == CELL_SYSUTIL_MAX_CALLBACKS); ++ printf("%s: result 0x%08X\n", online ? "PS3_NET_ONLINE=1" : "offline", be32_at(ea + 4)); ++ return 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-503/solution/solve.sh b/tasks/sp00nznet__ps3recomp-503/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-503/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-503/task.toml b/tasks/sp00nznet__ps3recomp-503/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..de75ca3b48e6fde6b349c1e414cbe7f8c37c1d87 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-503/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-503" +description = "cellNetCtl: offline, the net-start dialog ends cancelled" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "a6d76c895f77eb30b90a806c830544e61821b77f" +reference = "https://github.com/sp00nznet/ps3recomp/pull/503" +source_access = "auto" +built_at = "2026-11-16T16:09:59.862060+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ab510ebd3e9f78bc707d5cc3710865b09ec04ad9ab5ca92a327c4b6fea094794" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-26T15:32:55Z" +diff_format = "unified" +context_files = [ + ".github/workflows/linux.yml", + ".github/workflows/macos.yml", + "libs/network/cellNetCtl.c", + "libs/network/cellNetCtl.h", + "libs/network/tests/test_netctl_netstart.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 93 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.118606+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-503/tests/capture.py b/tasks/sp00nznet__ps3recomp-503/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-503/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-503/tests/instruction.md b/tasks/sp00nznet__ps3recomp-503/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..76fd4bbd68be27d6e5bc2e270a1449c96edac1eb --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-503/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** cellNetCtl: offline, the net-start dialog ends cancelled + +## Description + +## Why + +From the inFAMOUS 2 native port. `cellNetCtlNetStartDialogUnloadAsync` always reported `result = 0` (connected), even offline, where `cellNetCtlGetState` fails and `GetInfo` reports the link down. inFAMOUS 2 believed the dialog and went on to the PSN terms-of-service check, which never answers offline, so it sat behind an endless "Please wait..." box. + +RPCS3 ends the dialog with `CELL_NET_CTL_ERROR_DIALOG_CANCELED` when there is no network (`result->result = nph.get_net_status() == CELL_NET_CTL_STATE_IPObtained ? 0 : CELL_NET_CTL_ERROR_DIALOG_CANCELED;` in `cellNetCtl.cpp`). A cancelled connection is a path every title handles. + +## What + +- Offline (the default) the dialog's result is `CELL_NET_CTL_ERROR_DIALOG_CANCELED` (0x80130190), written big-endian. The old 0 was the same in either byte order, so the store never had to swap before. +- `PS3_NET_ONLINE=1` keeps the old answer, connected, in line with what `GetState` says in that mode. +- The LOADED / FINISHED / UNLOADED events are unchanged. +- The log line names the result. + +To get the old behaviour back, set `PS3_NET_ONLINE=1`. + +## Tests + +- New `libs/network/tests/test_netctl_netstart.c` (in the macOS and Linux workflows). It runs twice: offline the result word reads 0x80130190 big-endian, and with `PS3_NET_ONLINE=1` it reads 0. In both runs UNLOADED goes to every callback slot. +- In the port, the "Please wait..." box closes and inFAMOUS 2 carries on offline. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-503/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-503/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..252b99502380c17d54cc926acd7bb0f4c62bbc77 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-503/tests/oracle.patch @@ -0,0 +1,153 @@ +diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml +index 67bb40b3..cb846514 100644 +--- a/.github/workflows/linux.yml ++++ b/.github/workflows/linux.yml +@@ -144,6 +144,14 @@ jobs: + ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} -std=gnu17 -I include -o /tmp/test_np_identity libs/network/tests/test_np_identity.c + /tmp/test_np_identity + ++ # The net-start dialog ends cancelled offline and connected with ++ # PS3_NET_ONLINE=1, its result word big-endian. ++ - name: Run the net-start dialog test ++ run: | ++ ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} -std=gnu17 -I include -I libs/system -o /tmp/test_netctl_netstart libs/network/tests/test_netctl_netstart.c ++ /tmp/test_netctl_netstart ++ PS3_NET_ONLINE=1 /tmp/test_netctl_netstart ++ + # cellVideoOutSetGamma's float argument comes from f1, and the value + # reaches the presenter. + - name: Run the video out gamma test +diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml +index 19e9eb18..dd524f17 100644 +--- a/.github/workflows/macos.yml ++++ b/.github/workflows/macos.yml +@@ -102,6 +102,14 @@ jobs: + clang -std=gnu17 -I include -o /tmp/test_np_identity libs/network/tests/test_np_identity.c + /tmp/test_np_identity + ++ # The net-start dialog ends cancelled offline and connected with ++ # PS3_NET_ONLINE=1, its result word big-endian. ++ - name: Run the net-start dialog test ++ run: | ++ clang -std=gnu17 -I include -I libs/system -o /tmp/test_netctl_netstart libs/network/tests/test_netctl_netstart.c ++ /tmp/test_netctl_netstart ++ PS3_NET_ONLINE=1 /tmp/test_netctl_netstart ++ + # cellVideoOutSetGamma's float argument comes from f1, and the value + # reaches the presenter. + - name: Run the video out gamma test +diff --git a/libs/network/cellNetCtl.c b/libs/network/cellNetCtl.c +index c7926c0c..8c0594b7 100644 +--- a/libs/network/cellNetCtl.c ++++ b/libs/network/cellNetCtl.c +@@ -330,10 +330,11 @@ s32 cellNetCtlDelHandler(s32 hid) + * Real hardware shows a system dialog and signals progress asynchronously + * through the cellSysutil callback queue (LOADED -> FINISHED), after which the + * game calls UnloadAsync to retrieve the result. In an offline native recomp +- * there is nothing to show and we are already "connected", so we immediately +- * post LOADED + FINISHED to every registered sysutil callback slot and report a +- * successful result on unload. This unblocks the common boot-time "connecting +- * to network" gate without requiring a real PSN session. ++ * there is nothing to show, so we immediately post LOADED + FINISHED to every ++ * registered sysutil callback slot. On unload the result is "connected" with ++ * PS3_NET_ONLINE=1 and "cancelled" otherwise, matching what GetState reports. ++ * This unblocks the common boot-time "connecting to network" gate without ++ * requiring a real PSN session. + * -----------------------------------------------------------------------*/ + + static void netstart_broadcast(u32 status) +@@ -361,11 +362,18 @@ s32 cellNetCtlNetStartDialogAbortAsync(void) + + s32 cellNetCtlNetStartDialogUnloadAsync(CellNetCtlNetStartDialogResult* result) + { ++ /* Offline (the default), the dialog ends as if the player cancelled it, ++ * as RPCS3 reports it without a network: "connected" while GetState says ++ * there is no network sent inFAMOUS 2 on to a PSN terms-of-service check ++ * that never answers, behind an endless "Please wait...". A cancelled ++ * connection is a path every title handles. PS3_NET_ONLINE=1: connected. */ ++ const u32 res = netctl_online() ? 0u : (u32)CELL_NET_CTL_ERROR_DIALOG_CANCELED; + if (result) { + result = GUEST_PTR(result, CellNetCtlNetStartDialogResult*); +- result->result = 0; /* 0 = connected; endian-safe */ ++ result->result = (s32)ps3_bswap32(res); /* guest big-endian */ + } +- printf("[cellNetCtl] NetStartDialogUnloadAsync() -> result=0 (connected)\n"); ++ printf("[cellNetCtl] NetStartDialogUnloadAsync() -> result=0x%08X (%s)\n", res, ++ res ? "cancelled: offline" : "connected"); + netstart_broadcast(CELL_SYSUTIL_NET_CTL_NETSTART_UNLOADED); + return CELL_OK; + } +diff --git a/libs/network/cellNetCtl.h b/libs/network/cellNetCtl.h +index c5ab148b..f433becb 100644 +--- a/libs/network/cellNetCtl.h ++++ b/libs/network/cellNetCtl.h +@@ -182,7 +182,8 @@ s32 cellNetCtlAddHandler(cellNetCtlHandler handler, void* arg, s32* hid); + s32 cellNetCtlDelHandler(s32 hid); + + /* Net-start ("connect to PSN") dialog. In an offline native recomp we never +- * show it — these report an immediate successful connection. */ ++ * show it: it finishes at once, connected with PS3_NET_ONLINE=1 and cancelled ++ * (CELL_NET_CTL_ERROR_DIALOG_CANCELED) otherwise. */ + s32 cellNetCtlNetStartDialogLoadAsync(const CellNetCtlNetStartDialogParam* param); + s32 cellNetCtlNetStartDialogAbortAsync(void); + s32 cellNetCtlNetStartDialogUnloadAsync(CellNetCtlNetStartDialogResult* result); +diff --git a/libs/network/tests/test_netctl_netstart.c b/libs/network/tests/test_netctl_netstart.c +new file mode 100644 +index 00000000..3d6bdef3 +--- /dev/null ++++ b/libs/network/tests/test_netctl_netstart.c +@@ -0,0 +1,54 @@ ++/* ++ * test_netctl_netstart - the result the net-start dialog ends with. ++ * ++ * cc -std=gnu17 -I include -I libs/system -o test_netctl_netstart libs/network/tests/test_netctl_netstart.c ++ * ++ * Offline the dialog ends cancelled (CELL_NET_CTL_ERROR_DIALOG_CANCELED, as ++ * RPCS3 reports it without a network), so a title does not go on to the PSN ++ * steps GetState already said are unreachable; PS3_NET_ONLINE=1 ends it ++ * connected. The result word is big-endian in guest memory. Run it with and ++ * without PS3_NET_ONLINE=1. ++ */ ++#include "../cellNetCtl.c" ++ ++#include ++ ++uint8_t* vm_base; ++int g_resv_store_active; ++uint32_t g_ww_lo, g_ww_hi; ++void ppu_resv_break_store(uint64_t ea) { (void)ea; } ++void ps3_ww_report_inline(uint32_t a, uint64_t v, int w) { (void)a; (void)v; (void)w; } ++int spu_coh_is_reserved(uint32_t a) { (void)a; return 0; } ++void spu_coh_notify_write(uint32_t a) { (void)a; } ++void spu_lockline_lock(void) {} ++void spu_lockline_unlock(void) {} ++ ++static int s_unloaded; ++void cellSysutilQueueEvent(int slot, u32 status, u32 param) ++{ ++ (void)slot; (void)param; ++ if (status == CELL_SYSUTIL_NET_CTL_NETSTART_UNLOADED) s_unloaded++; ++} ++const char* np_psnr_identity(void) { return "PS3Player"; } ++ ++static u32 be32_at(u32 ea) ++{ ++ const uint8_t* p = vm_base + ea; ++ return (u32)p[0] << 24 | (u32)p[1] << 16 | (u32)p[2] << 8 | p[3]; ++} ++ ++int main(void) ++{ ++ static uint8_t mem[0x10000]; ++ vm_base = mem; ++ const u32 ea = 0x1000; /* CellNetCtlNetStartDialogResult: size, result */ ++ ++ const int online = getenv("PS3_NET_ONLINE") != NULL; ++ mem[ea + 4] = 0xAA; /* the result word is written, not left */ ++ assert(cellNetCtlNetStartDialogUnloadAsync((CellNetCtlNetStartDialogResult*)(uintptr_t)ea) == CELL_OK); ++ if (online) assert(be32_at(ea + 4) == 0u); ++ else assert(be32_at(ea + 4) == 0x80130190u); /* CELL_NET_CTL_ERROR_DIALOG_CANCELED */ ++ assert(s_unloaded == CELL_SYSUTIL_MAX_CALLBACKS); ++ printf("%s: result 0x%08X\n", online ? "PS3_NET_ONLINE=1" : "offline", be32_at(ea + 4)); ++ return 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-503/tests/test.sh b/tasks/sp00nznet__ps3recomp-503/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-503/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-503/tests/verifier.py b/tasks/sp00nznet__ps3recomp-503/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-503/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-532/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-532/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e58bcfa58777d72bba591f37e690838b686d5be --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-532/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-532/instruction.md b/tasks/sp00nznet__ps3recomp-532/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..de7dab44e59b5d5b4416be2c9518cd31b4f1164e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-532/instruction.md @@ -0,0 +1,53 @@ +# Issue + +**Title:** vulkan: VK_DRAW_BATCH=1 records engine draws, snapshots, uploads and clears into one submission + +## Description + +## Why + +On the register-file engine path the Vulkan backend submits a command buffer and waits on a fence for **every** draw (`vk_eng_draw` → `vk_submit_and_wait`). The vertex, index and uniform buffers and the descriptor set are single objects rewritten per draw, so each draw has to finish before the next is recorded. The walker thread then spends most of its time blocked on the GPU, and anything that waits for the walker waits with it: a title whose SPU jobs wait on RSX ring space ends up bound by one fenced draw at a time. + +## Change + +`VK_DRAW_BATCH=1` (off by default): + +- A draw takes slices of three host-visible ring buffers (vertices, indices, constants) and a descriptor set from a pool. It records into the open command buffer behind a full memory barrier, which keeps render-to-texture ordering without hazard tracking. Only a pending counter grows. +- Depth snapshots copy through a persistent device-local buffer recorded into the batch. Texture uploads stage through a ring and record a buffer-to-image copy. Colour and depth/stencil clears record into the batch too. +- `vk_begin`, every object destroy, the present and the engine's `submit_and_wait` flush first, so all other backend work still sees everything before it complete (the invariant the rest of the file relies on). +- `VK_DRAW_BATCH_MAX` (default 512, max 1024) caps the draws per submission. + +## Evidence + +God of War: Ascension (BCUS98232), first level, on a Windows port of this same backend (clang-cl; the backend is built there by a downstream patch, the batching code itself is the same). + +`PS3_FTRACE` timeline of 20 s of gameplay, time the walker spends waiting on the GPU: + +| | GPU wait / 20 s | +|---|---| +| per-draw submit (today) | 13.1 s (54,759 draws, ~168 us each) | +| draws batched | 8.4 s | +| + snapshots and uploads batched | 5.6 s | +| + clears batched | 2.9 s | + +Game frames per second over 600-1080 s of gameplay. Same exe, two instances run side by side and swapped halfway: + +- draws batched vs per-draw: 1.03 / 1.15 / 1.23 / 1.19 vs 0.74 / 0.79 / 0.89 / 0.89 (+39%, 4 of 4 pairs) +- + snapshots and uploads: 0.90 / 1.29 / 1.27 / 1.32 vs 0.89 / 1.18 / 1.17 / 1.19 (+8%, 4 of 4) +- + clears: within noise (+0.7%) + +16 runs of 18 minutes: no hangs, and the game's own error checks (its VRAM copy-queue `invalid size`) stayed silent. Frame dumps every 300 flips look the same with batching on and off. + +Compile on Linux: `gcc -std=c17 -Wall -Wextra` builds the file with no warnings, the same as `master`. + +## Not measured + +- Not run on Linux, macOS (Metal is untouched) or with other titles; Linux was compile-checked only. +- No Vulkan validation layer run. +- Behaviour with `VK_DRAW_BATCH` unset is the existing path. The flush hooks are a no-op with nothing pending. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-532/solution/patch.diff b/tasks/sp00nznet__ps3recomp-532/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c8528f7abd18cf32fdc79959d1d1912aa42f3a65 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-532/solution/patch.diff @@ -0,0 +1,545 @@ +diff --git a/libs/video/rsx_vulkan_backend.c b/libs/video/rsx_vulkan_backend.c +index b22e08f6..6f16a35c 100644 +--- a/libs/video/rsx_vulkan_backend.c ++++ b/libs/video/rsx_vulkan_backend.c +@@ -90,7 +90,7 @@ + X(vkCreateShaderModule) X(vkDestroyShaderModule) \ + X(vkCreateDescriptorSetLayout) X(vkDestroyDescriptorSetLayout) \ + X(vkCreateDescriptorPool) X(vkDestroyDescriptorPool) \ +- X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) \ ++ X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) X(vkResetDescriptorPool) \ + X(vkCreatePipelineLayout) X(vkDestroyPipelineLayout) \ + X(vkCreateGraphicsPipelines) X(vkDestroyPipeline) \ + X(vkCreateSampler) X(vkDestroySampler) \ +@@ -446,8 +446,22 @@ static int vk_create_image(vk_image* im, VkFormat fmt, u32 w, u32 h, + + static void vk_present_wait_gpu(void); + ++/* VK_DRAW_BATCH (vk_eng_draw): draws recorded into s_vk.cmd and not yet ++ * submitted. Anything that records other work, destroys an object or reads ++ * results flushes them first, so everything else keeps the invariant that ++ * all earlier work has completed. */ ++static u32 s_eb_pending; ++static void vk_eng_flush(void); ++static int vk_eb_active(void); /* batching decided on and on */ ++static u32 vk_eb_max(void); ++static void vk_eb_recorded(void); /* one more command in the open batch */ ++static void vk_eb_release(void); /* engine shutdown: rings and pool */ ++static int vk_eb_upload(VkImage img, VkBufferImageCopy* region, const void* src, size_t tight, ++ u32 rows, u32 row_bytes); /* -2: not batched, do it the old way */ ++ + static void vk_destroy_image(vk_image* im) + { ++ if (s_eb_pending) vk_eng_flush(); + /* Never under a present's copy that may still read it. */ + if (im->img) vk_present_wait_gpu(); + if (im->view) pvkDestroyImageView(s_vk.device, im->view, NULL); +@@ -488,8 +502,29 @@ static int vk_create_host_buffer(vk_buffer* b, VkDeviceSize size, VkBufferUsageF + return 0; + } + ++/* A buffer only the GPU touches (copies through it stay in VRAM). */ ++static int vk_create_device_buffer(vk_buffer* b, VkDeviceSize size, VkBufferUsageFlags usage) ++{ ++ VkBufferCreateInfo bci = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, ++ .size = size, .usage = usage, ++ .sharingMode = VK_SHARING_MODE_EXCLUSIVE }; ++ VK_CHECK(pvkCreateBuffer(s_vk.device, &bci, NULL, &b->buf), "vkCreateBuffer"); ++ VkMemoryRequirements req; ++ pvkGetBufferMemoryRequirements(s_vk.device, b->buf, &req); ++ u32 type; ++ if (vk_find_memory_type(req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &type) && ++ vk_find_memory_type(req.memoryTypeBits, 0, &type)) { VK_LOG("no memory for a device buffer\n"); return -1; } ++ VkMemoryAllocateInfo mai = { .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, ++ .allocationSize = req.size, .memoryTypeIndex = type }; ++ VK_CHECK(pvkAllocateMemory(s_vk.device, &mai, NULL, &b->mem), "vkAllocateMemory(device buffer)"); ++ VK_CHECK(pvkBindBufferMemory(s_vk.device, b->buf, b->mem, 0), "vkBindBufferMemory"); ++ b->ptr = NULL; b->coherent = 0; b->size = size; ++ return 0; ++} ++ + static void vk_destroy_buffer(vk_buffer* b) + { ++ if (s_eb_pending) vk_eng_flush(); + if (b->ptr) pvkUnmapMemory(s_vk.device, b->mem); + if (b->buf) pvkDestroyBuffer(s_vk.device, b->buf, NULL); + if (b->mem) pvkFreeMemory(s_vk.device, b->mem, NULL); +@@ -550,6 +585,7 @@ static void vk_cmd_after_everything(VkCommandBuffer cb) + + static int vk_begin(void) + { ++ if (s_eb_pending) vk_eng_flush(); + VK_CHECK(pvkResetCommandBuffer(s_vk.cmd, 0), "vkResetCommandBuffer"); + VkCommandBufferBeginInfo bi = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, + .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT }; +@@ -2124,6 +2160,15 @@ static int vk_eng_upload_region(VkImage img, u32 layer, u32 mip, u32 x, u32 y, + const void* src, u32 row_bytes) + { + if (tight > row_bytes) tight = row_bytes; ++ { /* VK_DRAW_BATCH: staged in a ring and recorded into the open batch. */ ++ VkBufferImageCopy region = { ++ .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1 }, ++ .imageOffset = { (int32_t)x, (int32_t)y, 0 }, ++ .imageExtent = { w, h, 1 }, ++ }; ++ const int b = vk_eb_upload(img, ®ion, src, tight, rows, row_bytes); ++ if (b != -2) return b; ++ } + vk_buffer st = {0}; + if (vk_create_host_buffer(&st, (VkDeviceSize)tight * rows, VK_BUFFER_USAGE_TRANSFER_SRC_BIT) || + !st.coherent) { vk_destroy_buffer(&st); return -1; } +@@ -2237,11 +2282,13 @@ static void vk_eng_shutdown(void* user) + vk_eng2_shutdown(user); + for (u32 i = 1; i < VK_ENG_MAX_OBJ; i++) vk_eng_release(user, i); + vk_eng_snapshot_pool_drain(); ++ vk_eb_release(); + } + + static void vk_eng_submit_and_wait(void* user, u32 reason) + { +- (void)user; (void)reason; /* every submission has already completed */ ++ (void)user; (void)reason; /* every other submission has already completed */ ++ if (s_eb_pending) vk_eng_flush(); + } + + static u32 vk_eng_color_target_create(void* user, rsx_be_format fmt, u32 w, u32 h, +@@ -2321,13 +2368,16 @@ static void vk_eng_clear_color(void* user, u32 surface, const float rgba[4]) + ((u32)(rgba[1] * 255.0f + 0.5f) << 8) | + (u32)(rgba[2] * 255.0f + 0.5f); + vk_eng_obj* o = vk_eng_get(surface, VK_ENG_COLOR); +- if (!o || vk_begin()) return; ++ if (!o) return; ++ const int batched = vk_eb_active(); ++ if (batched ? (!s_eb_pending && vk_begin()) : vk_begin()) return; + VkClearColorValue v; + memcpy(v.float32, rgba, sizeof v.float32); + VkImageSubresourceRange r = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; + vk_barrier_image(o->im.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL); + pvkCmdClearColorImage(s_vk.cmd, o->im.img, VK_IMAGE_LAYOUT_GENERAL, &v, 1, &r); +- vk_submit_and_wait(); ++ if (batched) vk_eb_recorded(); ++ else vk_submit_and_wait(); + } + + static void vk_eng_clear_depth_stencil(void* user, u32 depth, u32 flags, +@@ -2338,12 +2388,15 @@ static void vk_eng_clear_depth_stencil(void* user, u32 depth, u32 flags, + VkImageAspectFlags aspect = 0; + if (flags & RSX_BE_CLEAR_DEPTH) aspect |= VK_IMAGE_ASPECT_DEPTH_BIT; + if (flags & RSX_BE_CLEAR_STENCIL) aspect |= s_vk.depth_aspect & VK_IMAGE_ASPECT_STENCIL_BIT; +- if (!o || !aspect || vk_begin()) return; ++ if (!o || !aspect) return; ++ const int batched = vk_eb_active(); ++ if (batched ? (!s_eb_pending && vk_begin()) : vk_begin()) return; + VkClearDepthStencilValue d = { depth_value, stencil }; + VkImageSubresourceRange r = { aspect, 0, 1, 0, 1 }; + vk_barrier_image(o->im.img, s_vk.depth_aspect, VK_IMAGE_LAYOUT_GENERAL); + pvkCmdClearDepthStencilImage(s_vk.cmd, o->im.img, VK_IMAGE_LAYOUT_GENERAL, &d, 1, &r); +- vk_submit_and_wait(); ++ if (batched) vk_eb_recorded(); ++ else vk_submit_and_wait(); + } + + /* The named surface becomes the frame: blit it onto the display image, then +@@ -2352,6 +2405,7 @@ static void vk_eng_present(void* user, u32 surface) + { + (void)user; + if (!s_vk.device) return; ++ if (s_eb_pending) vk_eng_flush(); /* the present records on its own buffer */ + vk_eng_obj* o = vk_eng_get(surface, VK_ENG_COLOR); + pthread_mutex_lock(&s_vk.present_mu); + VkCommandBuffer cb = vk_present_record_begin(); +@@ -2529,6 +2583,7 @@ static u32 vk_eng_surface_view(void* user, u32 surface, u32 remap, u32 rsx_forma + #define VK_SNAP_POOL 8 + static struct { vk_image im; VkFormat fmt; u32 w, h; } s_snap_pool[VK_SNAP_POOL]; + static u32 s_snap_pool_n; ++static vk_buffer s_snap_st; /* depth snapshot bounce buffer (vk_eng_depth_snapshot) */ + + static void vk_eng_snapshot_recycle(vk_eng_obj* o) + { +@@ -2547,6 +2602,7 @@ static void vk_eng_snapshot_pool_drain(void) + { + for (u32 i = 0; i < s_snap_pool_n; i++) vk_destroy_image(&s_snap_pool[i].im); + s_snap_pool_n = 0; ++ vk_destroy_buffer(&s_snap_st); + } + + static u32 vk_eng_color_snapshot(void* user, u32 surface) +@@ -2637,12 +2693,24 @@ static u32 vk_eng_depth_snapshot(void* user, u32 depth, u32 w, u32 h) + if (vk_submit_and_wait()) return 0; + } + +- vk_buffer st = {0}; +- if (vk_create_host_buffer(&st, (VkDeviceSize)w * h * 4u, +- VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT)) { +- vk_destroy_buffer(&st); return 0; ++ /* The bounce buffer stays (device-local when the device has it, grown as ++ * needed): a fresh host buffer per snapshot cost ~4.8 ms each, 375 times ++ * in 20 s of God of War: Ascension's first level. With draw batching the ++ * copies join the open batch instead of a submission of their own; the ++ * draws that sample the snapshot come after them in the same buffer, and ++ * each batched draw starts with a full memory barrier. */ ++ const VkDeviceSize need = (VkDeviceSize)w * h * 4u; ++ if (s_snap_st.size < need) { ++ vk_destroy_buffer(&s_snap_st); /* flushes a pending batch first */ ++ if (vk_create_device_buffer(&s_snap_st, need, ++ VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT)) { ++ vk_destroy_buffer(&s_snap_st); return 0; ++ } + } +- int rc = vk_begin(); ++ vk_buffer st = s_snap_st; ++ const int batch = vk_eb_active(); ++ int rc = (batch && s_eb_pending) ? 0 : vk_begin(); ++ if (!rc && batch) vk_cmd_after_everything(s_vk.cmd); + if (!rc) { + vk_barrier_image(z->im.img, s_vk.depth_aspect, VK_IMAGE_LAYOUT_GENERAL); + vk_barrier_image(t->im.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL); +@@ -2659,9 +2727,12 @@ static u32 vk_eng_depth_snapshot(void* user, u32 depth, u32 w, u32 h) + VkBufferImageCopy in = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, + .imageExtent = { w, h, 1 } }; + pvkCmdCopyBufferToImage(s_vk.cmd, st.buf, t->im.img, VK_IMAGE_LAYOUT_GENERAL, 1, &in); +- rc = vk_submit_and_wait(); ++ if (batch) { ++ vk_barrier_image(t->im.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL); ++ if (++s_eb_pending >= vk_eb_max()) vk_eng_flush(); ++ } else ++ rc = vk_submit_and_wait(); + } +- vk_destroy_buffer(&st); + return rc ? 0 : snap; + } + /* The depth aspect of a D32_SFLOAT target copies out as 32-bit floats, which +@@ -2748,6 +2819,7 @@ static struct { + u32 scratch_w, scratch_h; + u32 pipeline; + u32 vs_bytes, ps_bytes; ++ u8* ucpu; /* the constants, in the shared UBO's layout */ + u32 tex[RSX_BE_MAX_TEXTURES]; + rsx_be_sampler_desc samp[RSX_BE_MAX_TEXTURES]; + u32 tex_mask; +@@ -2774,6 +2846,7 @@ static u32 s_esamp_count; + + static void vk_eng_drop_framebuffers(void) + { ++ if (s_eb_pending) vk_eng_flush(); + for (u32 i = 0; i < s_e2.fb_count; i++) + if (s_e2.fb[i].fb) pvkDestroyFramebuffer(s_vk.device, s_e2.fb[i].fb, NULL); + s_e2.fb_count = 0; +@@ -2983,6 +3056,7 @@ static u32 vk_eng_pipeline_create(void* user, const char* vs_hlsl, const char* p + static void vk_eng_pipeline_release(void* user, u32 pipeline) + { + (void)user; ++ if (s_eb_pending) vk_eng_flush(); + if (!pipeline || pipeline > VK_ENG_MAX_PIPE || !s_epipe[pipeline - 1].used) return; + vk_eng_pipe* P = &s_epipe[pipeline - 1]; + for (u32 t = 0; t < VK_ENG_TOPOLOGIES; t++) +@@ -3115,29 +3189,39 @@ static void vk_eng2_shutdown(void* user) + if (s_e2.split_pipe_layout) pvkDestroyPipelineLayout(s_vk.device, s_e2.split_pipe_layout, NULL); + if (s_e2.split_pool) pvkDestroyDescriptorPool(s_vk.device, s_e2.split_pool, NULL); + if (s_e2.split_layout) pvkDestroyDescriptorSetLayout(s_vk.device, s_e2.split_layout, NULL); ++ free(s_e2.ucpu); + memset(&s_e2, 0, sizeof s_e2); + for (u32 i = 0; i < s_esamp_count; i++) pvkDestroySampler(s_vk.device, s_esamp[i].s, NULL); + s_esamp_count = 0; + } + +-/* Constants go straight into the shared UBO: vertex at 0, pixel at ps_off. +- * Every operation is waited on, so overwriting per draw is safe. */ ++/* Constants are kept in ordinary memory laid out like the shared UBO (vertex ++ * at 0, pixel at ps_off) and copied to the GPU per draw: into the draw's ring ++ * slice when batched, into the shared UBO otherwise (every such draw is waited ++ * on, so overwriting it is safe). Writing them straight into the UBO meant a ++ * batched draw read them back out of it, and that memory is host-coherent, ++ * i.e. write-combined and uncached on most drivers. */ ++static u8* vk_eng_ucpu(void) ++{ ++ if (!s_e2.ucpu && s_g.ubo.size) s_e2.ucpu = (u8*)calloc(1, (size_t)s_g.ubo.size); ++ return s_e2.ucpu; ++} + static void vk_eng_bind_vs_constants(void* user, const void* data, u32 bytes) + { + (void)user; +- if (!s_g.on || !data) { s_e2.vs_bytes = 0; return; } ++ if (!s_g.on || !data || !vk_eng_ucpu()) { s_e2.vs_bytes = 0; return; } + const u32 cap = (u32)s_g.ps_off; + if (bytes > cap) { bytes = cap; if (!(s_e2.warned & 2u)) { VK_LOG("engine: VS constants truncated\n"); s_e2.warned |= 2u; } } +- memcpy(s_g.ubo.ptr, data, bytes); ++ memcpy(s_e2.ucpu, data, bytes); + s_e2.vs_bytes = bytes; + } + static void vk_eng_bind_ps_constants(void* user, const void* data, u32 bytes) + { + (void)user; +- if (!s_g.on || !data) { s_e2.ps_bytes = 0; return; } ++ if (!s_g.on || !data || !vk_eng_ucpu()) { s_e2.ps_bytes = 0; return; } + const u32 cap = (u32)(s_g.ubo.size - s_g.ps_off); + if (bytes > cap) { bytes = cap; if (!(s_e2.warned & 4u)) { VK_LOG("engine: PS constants truncated\n"); s_e2.warned |= 4u; } } +- memcpy((u8*)s_g.ubo.ptr + s_g.ps_off, data, bytes); ++ memcpy(s_e2.ucpu + s_g.ps_off, data, bytes); + s_e2.ps_bytes = bytes; + } + static void vk_eng_bind_textures(void* user, const u32* textures, +@@ -3296,19 +3380,160 @@ static VkImageView vk_eng_dummy_cube_view(void) + return s_eobj[s_e2.dummy_cube].im.view; + } + ++/* --------------------------------------------------------------------------- ++ * Draw batching (VK_DRAW_BATCH=1) ++ * ++ * Every vk_eng_draw used to submit its own command buffer and wait on a ++ * fence, because the vertex, index and uniform buffers and the descriptor set ++ * are single objects rewritten per draw. In God of War: Ascension's first level ++ * that was 54,759 draws in 20 s at ~168 us each: the FIFO walker spent 46% of ++ * its time blocked on the GPU, the RSX ring drained one draw at a time and the ++ * SPU geometry jobs waited for ring space. Batched, a draw takes slices of ++ * three ring buffers and a descriptor set from a pool, records into the open ++ * command buffer, and only s_eb_pending grows. vk_eng_flush() submits, waits ++ * once, and resets the rings and the pool; vk_begin, every object destroy, the ++ * present and the engine's own submit point call it first, so all other work ++ * keeps seeing everything before it complete. Between batched draws a full ++ * memory barrier keeps render-to-texture ordering without tracking. ++ * VK_DRAW_BATCH_MAX (default 512) caps the draws per submission. ++ * -------------------------------------------------------------------------*/ ++#define VK_EB_VB_BYTES (64u << 20) ++#define VK_EB_IB_BYTES (16u << 20) ++#define VK_EB_UB_BYTES (32u << 20) ++#define VK_EB_SB_BYTES (64u << 20) /* texture upload staging */ ++#define VK_EB_MAX_SETS 1024u ++ ++static struct { ++ int on; /* -1 undecided, 0 off, 1 on */ ++ u32 max_draws; ++ vk_buffer vb, ib, ub, sb; ++ VkDeviceSize vb_head, ib_head, ub_head, sb_head, ub_align; ++ VkDescriptorPool pool; ++ u32 sets; ++ unsigned long long draws, flushes; ++} s_eb = { .on = -1 }; ++ ++static int vk_eb_on(void) ++{ ++ if (s_eb.on >= 0) return s_eb.on; ++ const char* e = getenv("VK_DRAW_BATCH"); ++ s_eb.on = 0; ++ if (!e || *e != '1' || !s_g.on) return 0; ++ const char* m = getenv("VK_DRAW_BATCH_MAX"); ++ s_eb.max_draws = m && atoi(m) > 0 ? (u32)atoi(m) : 512u; ++ if (s_eb.max_draws > VK_EB_MAX_SETS) s_eb.max_draws = VK_EB_MAX_SETS; ++ VkPhysicalDeviceProperties p; ++ pvkGetPhysicalDeviceProperties(s_vk.phys, &p); ++ s_eb.ub_align = p.limits.minUniformBufferOffsetAlignment ? p.limits.minUniformBufferOffsetAlignment : 256; ++ VkDescriptorPoolSize ps[3] = { ++ { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2 * VK_EB_MAX_SETS }, ++ { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, RSX_MAX_TEXTURES * VK_EB_MAX_SETS }, ++ { VK_DESCRIPTOR_TYPE_SAMPLER, RSX_MAX_TEXTURES * VK_EB_MAX_SETS }, ++ }; ++ VkDescriptorPoolCreateInfo pci = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, ++ .maxSets = VK_EB_MAX_SETS, .poolSizeCount = 3, .pPoolSizes = ps }; ++ if (vk_create_host_buffer(&s_eb.vb, VK_EB_VB_BYTES, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT) || !s_eb.vb.coherent || ++ vk_create_host_buffer(&s_eb.ib, VK_EB_IB_BYTES, VK_BUFFER_USAGE_INDEX_BUFFER_BIT) || !s_eb.ib.coherent || ++ vk_create_host_buffer(&s_eb.ub, VK_EB_UB_BYTES, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT) || !s_eb.ub.coherent || ++ vk_create_host_buffer(&s_eb.sb, VK_EB_SB_BYTES, VK_BUFFER_USAGE_TRANSFER_SRC_BIT) || !s_eb.sb.coherent || ++ pvkCreateDescriptorPool(s_vk.device, &pci, NULL, &s_eb.pool) != VK_SUCCESS) { ++ VK_LOG("draw batching: no host-coherent ring memory, staying off\n"); ++ return 0; ++ } ++ VK_LOG("draw batching: on (up to %u draws per submission)\n", s_eb.max_draws); ++ s_eb.on = 1; ++ return 1; ++} ++ ++/* The rings and the pool live until the engine shuts down; a later vk_eb_on ++ * decides again. Also frees what a failed vk_eb_on had already created. */ ++static void vk_eb_release(void) ++{ ++ if (s_eb_pending) vk_eng_flush(); ++ vk_destroy_buffer(&s_eb.vb); ++ vk_destroy_buffer(&s_eb.ib); ++ vk_destroy_buffer(&s_eb.ub); ++ vk_destroy_buffer(&s_eb.sb); ++ if (s_eb.pool) pvkDestroyDescriptorPool(s_vk.device, s_eb.pool, NULL); ++ memset(&s_eb, 0, sizeof s_eb); ++ s_eb.on = -1; ++} ++ ++static int vk_eb_active(void) { return s_eb.on == 1; } ++static u32 vk_eb_max(void) { return s_eb.max_draws; } ++static void vk_eb_recorded(void) { if (++s_eb_pending >= s_eb.max_draws) vk_eng_flush(); } ++ ++static VkDeviceSize vk_eb_take(VkDeviceSize* head, VkDeviceSize cap, VkDeviceSize bytes, VkDeviceSize align); ++ ++/* A texture upload as one more batched operation: rows staged in the ring, the ++ * copy recorded behind a full memory barrier (earlier draws of the batch may ++ * still sample the old texels) and followed by one on the image (later draws ++ * sample the new ones). Each used to allocate a host buffer and wait on its own ++ * submission, ~3000 times in 20 s of God of War: Ascension's first level. */ ++static int vk_eb_upload(VkImage img, VkBufferImageCopy* region, const void* src, size_t tight, ++ u32 rows, u32 row_bytes) ++{ ++ if (!vk_eb_active()) return -2; ++ const VkDeviceSize bytes = (VkDeviceSize)tight * rows; ++ if (!bytes || bytes > VK_EB_SB_BYTES) return -2; ++ VkDeviceSize off = vk_eb_take(&s_eb.sb_head, VK_EB_SB_BYTES, bytes, 16u); ++ if (off == (VkDeviceSize)-1) { ++ vk_eng_flush(); ++ off = vk_eb_take(&s_eb.sb_head, VK_EB_SB_BYTES, bytes, 16u); ++ if (off == (VkDeviceSize)-1) return -2; ++ } ++ for (u32 y = 0; y < rows; y++) ++ memcpy((u8*)s_eb.sb.ptr + off + (size_t)y * tight, (const u8*)src + (size_t)y * row_bytes, tight); ++ if (!s_eb_pending && vk_begin()) return -1; ++ vk_cmd_after_everything(s_vk.cmd); ++ region->bufferOffset = off; ++ pvkCmdCopyBufferToImage(s_vk.cmd, s_eb.sb.buf, img, VK_IMAGE_LAYOUT_GENERAL, 1, region); ++ vk_barrier_image(img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL); ++ if (++s_eb_pending >= s_eb.max_draws) vk_eng_flush(); ++ return 0; ++} ++ ++static void vk_eng_flush(void) ++{ ++ if (!s_eb_pending) return; ++ s_eb_pending = 0; /* first: the submit below must not re-enter */ ++ vk_submit_and_wait(); ++ s_eb.vb_head = s_eb.ib_head = s_eb.ub_head = s_eb.sb_head = 0; ++ if (s_eb.sets) { pvkResetDescriptorPool(s_vk.device, s_eb.pool, 0); s_eb.sets = 0; } ++ if ((++s_eb.flushes & 0x3FFFu) == 0) ++ VK_LOG("draw batching: %llu draws in %llu submissions\n", s_eb.draws, s_eb.flushes); ++} ++ ++static VkDeviceSize vk_eb_take(VkDeviceSize* head, VkDeviceSize cap, VkDeviceSize bytes, VkDeviceSize align) ++{ ++ const VkDeviceSize at = (*head + align - 1u) / align * align; ++ if (at + bytes > cap) return (VkDeviceSize)-1; ++ *head = at + bytes; ++ return at; ++} ++ ++static VkDescriptorSet vk_eng_write_descriptors_to(const vk_eng_pipe* P, VkDescriptorSet set, ++ VkBuffer ubo, VkDeviceSize vs_off, VkDeviceSize ps_off); ++ + /* Fill the set the bound pipeline uses: the shared one (sixteen textures in + * one binding), or for a pipeline with cube units the split one (one binding + * per unit). Returns the set, or VK_NULL_HANDLE. */ + static VkDescriptorSet vk_eng_write_descriptors(const vk_eng_pipe* P) ++{ ++ const VkDescriptorSet set = P->cube_mask ? s_e2.split_set : s_g.set; ++ return vk_eng_write_descriptors_to(P, set, s_g.ubo.buf, 0, s_g.ps_off); ++} ++ ++static VkDescriptorSet vk_eng_write_descriptors_to(const vk_eng_pipe* P, VkDescriptorSet set, ++ VkBuffer ubo, VkDeviceSize vs_off, VkDeviceSize ps_off) + { + const int split = P->cube_mask != 0; +- const VkDescriptorSet set = split ? s_e2.split_set : s_g.set; + if (!set) return VK_NULL_HANDLE; + const VkImageView dummy_cube = split ? vk_eng_dummy_cube_view() : VK_NULL_HANDLE; + if (split && !dummy_cube) return VK_NULL_HANDLE; + VkDescriptorBufferInfo bi[2] = { +- { s_g.ubo.buf, 0, s_e2.vs_bytes ? s_e2.vs_bytes : 16u }, +- { s_g.ubo.buf, s_g.ps_off, s_e2.ps_bytes ? s_e2.ps_bytes : 16u }, ++ { ubo, vs_off, s_e2.vs_bytes ? s_e2.vs_bytes : 16u }, ++ { ubo, ps_off, s_e2.ps_bytes ? s_e2.ps_bytes : 16u }, + }; + VkDescriptorImageInfo ii[RSX_MAX_TEXTURES], si[RSX_MAX_TEXTURES]; + for (u32 u = 0; u < RSX_MAX_TEXTURES; u++) { +@@ -3381,16 +3606,67 @@ static void vk_eng_draw(void* user, rsx_topology topology, const void* vertices, + if (!pipe || !rp || !fb) return; + + const VkDeviceSize vbytes = (VkDeviceSize)vertex_count * stride; +- if (vk_ensure_vertex_buffer(vbytes)) return; +- memcpy(s_vk.vertices.ptr, vertices, (size_t)vbytes); +- if (indices && index_count) { +- if (vk_eng_ensure_indices((VkDeviceSize)index_count * 4u)) return; +- memcpy(s_e2.indices.ptr, indices, (size_t)index_count * 4u); ++ const VkDeviceSize ibytes = (indices && index_count) ? (VkDeviceSize)index_count * 4u : 0; ++ VkBuffer vbuf = s_vk.vertices.buf, ibuf = s_e2.indices.buf; ++ VkDeviceSize voff = 0, ioff = 0; ++ VkDescriptorSet set = VK_NULL_HANDLE; ++ const u32 vsb = s_e2.vs_bytes ? s_e2.vs_bytes : 16u, psb = s_e2.ps_bytes ? s_e2.ps_bytes : 16u; ++ int batched = vk_eb_on() && vbytes <= VK_EB_VB_BYTES && ibytes <= VK_EB_IB_BYTES; ++ if (batched && P->cube_mask && !vk_eng_dummy_cube_view()) return; /* may flush: before any slice */ ++ if (batched) { ++ /* Slices of the rings and a set from the pool; a full one flushes the ++ * batch (which empties them all) and the draw takes its slices again. */ ++ for (int tries = 0; tries < 2; tries++) { ++ VkDeviceSize vh = s_eb.vb_head, ih = s_eb.ib_head, uh = s_eb.ub_head; ++ voff = vk_eb_take(&vh, VK_EB_VB_BYTES, vbytes, 16u); ++ ioff = ibytes ? vk_eb_take(&ih, VK_EB_IB_BYTES, ibytes, 16u) : 0; ++ const VkDeviceSize uvs = vk_eb_take(&uh, VK_EB_UB_BYTES, vsb, s_eb.ub_align); ++ const VkDeviceSize ups = uvs == (VkDeviceSize)-1 ? uvs : vk_eb_take(&uh, VK_EB_UB_BYTES, psb, s_eb.ub_align); ++ if (voff != (VkDeviceSize)-1 && ioff != (VkDeviceSize)-1 && ups != (VkDeviceSize)-1 && ++ s_eb.sets < VK_EB_MAX_SETS) { ++ VkDescriptorSetLayout lay = P->cube_mask ? s_e2.split_layout : s_g.set_layout; ++ VkDescriptorSetAllocateInfo dai = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, ++ .descriptorPool = s_eb.pool, .descriptorSetCount = 1, ++ .pSetLayouts = &lay }; ++ if (pvkAllocateDescriptorSets(s_vk.device, &dai, &set) == VK_SUCCESS) { ++ s_eb.sets++; ++ s_eb.vb_head = vh; s_eb.ib_head = ih; s_eb.ub_head = uh; ++ memcpy((u8*)s_eb.ub.ptr + uvs, vk_eng_ucpu(), vsb); ++ memcpy((u8*)s_eb.ub.ptr + ups, vk_eng_ucpu() + s_g.ps_off, psb); ++ if (!vk_eng_write_descriptors_to(P, set, s_eb.ub.buf, uvs, ups)) return; ++ break; ++ } ++ set = VK_NULL_HANDLE; ++ } ++ if (tries || !s_eb_pending) { batched = 0; break; } ++ vk_eng_flush(); ++ } ++ if (batched && !set) batched = 0; ++ } ++ if (batched) { ++ memcpy((u8*)s_eb.vb.ptr + voff, vertices, (size_t)vbytes); ++ if (ibytes) memcpy((u8*)s_eb.ib.ptr + ioff, indices, (size_t)ibytes); ++ vbuf = s_eb.vb.buf; ibuf = s_eb.ib.buf; ++ if (!s_eb_pending && vk_begin()) return; ++ /* Earlier draws of this batch may have rendered what this one samples ++ * or blends over: order it after all of them. */ ++ vk_cmd_after_everything(s_vk.cmd); ++ } else { ++ if (s_eb_pending) vk_eng_flush(); ++ if (vk_ensure_vertex_buffer(vbytes)) return; ++ memcpy(s_vk.vertices.ptr, vertices, (size_t)vbytes); ++ if (ibytes) { ++ if (vk_eng_ensure_indices(ibytes)) return; ++ memcpy(s_e2.indices.ptr, indices, (size_t)ibytes); ++ } ++ vbuf = s_vk.vertices.buf; ibuf = s_e2.indices.buf; voff = ioff = 0; ++ if (!vk_eng_ucpu()) return; ++ memcpy(s_g.ubo.ptr, s_e2.ucpu, vsb); ++ memcpy((u8*)s_g.ubo.ptr + s_g.ps_off, s_e2.ucpu + s_g.ps_off, psb); ++ set = vk_eng_write_descriptors(P); ++ if (!set) return; ++ if (vk_begin()) return; + } +- const VkDescriptorSet set = vk_eng_write_descriptors(P); +- if (!set) return; +- +- if (vk_begin()) return; + /* Everything submitted before is complete (each submission is waited + * on); this orders memory for the surfaces this draw touches. */ + for (u32 i = 0; i < n; i++) +@@ -3421,16 +3697,17 @@ static void vk_eng_draw(void* user, rsx_topology topology, const void* vertices, + pvkCmdBindDescriptorSets(s_vk.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, + P->cube_mask ? s_e2.split_pipe_layout : s_g.pipe_layout, + 0, 1, &set, 0, NULL); +- VkDeviceSize off = 0; +- pvkCmdBindVertexBuffers(s_vk.cmd, 0, 1, &s_vk.vertices.buf, &off); +- if (indices && index_count) { +- pvkCmdBindIndexBuffer(s_vk.cmd, s_e2.indices.buf, 0, VK_INDEX_TYPE_UINT32); ++ pvkCmdBindVertexBuffers(s_vk.cmd, 0, 1, &vbuf, &voff); ++ if (ibytes) { ++ pvkCmdBindIndexBuffer(s_vk.cmd, ibuf, ioff, VK_INDEX_TYPE_UINT32); + pvkCmdDrawIndexed(s_vk.cmd, index_count, 1, 0, 0, 0); + } else { + pvkCmdDraw(s_vk.cmd, vertex_count, 1, 0, 0); + } + pvkCmdEndRenderPass(s_vk.cmd); +- vk_submit_and_wait(); ++ if (!batched) { vk_submit_and_wait(); return; } ++ s_eb.draws++; ++ if (++s_eb_pending >= s_eb.max_draws) vk_eng_flush(); + } + + static const rsx_draw_backend s_vk_engine_backend = { diff --git a/tasks/sp00nznet__ps3recomp-532/solution/solve.sh b/tasks/sp00nznet__ps3recomp-532/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-532/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-532/task.toml b/tasks/sp00nznet__ps3recomp-532/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a5b77a651632689d7d738fd57f89e757f092cc04 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-532/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-532" +description = "vulkan: VK_DRAW_BATCH=1 records engine draws, snapshots, uploads and clears into one submission" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "a6d76c895f77eb30b90a806c830544e61821b77f" +reference = "https://github.com/sp00nznet/ps3recomp/pull/532" +source_access = "auto" +built_at = "2026-11-16T16:09:59.935783+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e7f8c37a09cd7afcec528ab181e5d1a2248e8bcebdd96bae5e02b2e87a8f82d8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-26T15:32:54Z" +diff_format = "unified" +context_files = [ + "libs/video/rsx_vulkan_backend.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 349 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.119142+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-532/tests/capture.py b/tasks/sp00nznet__ps3recomp-532/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-532/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-532/tests/instruction.md b/tasks/sp00nznet__ps3recomp-532/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..de7dab44e59b5d5b4416be2c9518cd31b4f1164e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-532/tests/instruction.md @@ -0,0 +1,53 @@ +# Issue + +**Title:** vulkan: VK_DRAW_BATCH=1 records engine draws, snapshots, uploads and clears into one submission + +## Description + +## Why + +On the register-file engine path the Vulkan backend submits a command buffer and waits on a fence for **every** draw (`vk_eng_draw` → `vk_submit_and_wait`). The vertex, index and uniform buffers and the descriptor set are single objects rewritten per draw, so each draw has to finish before the next is recorded. The walker thread then spends most of its time blocked on the GPU, and anything that waits for the walker waits with it: a title whose SPU jobs wait on RSX ring space ends up bound by one fenced draw at a time. + +## Change + +`VK_DRAW_BATCH=1` (off by default): + +- A draw takes slices of three host-visible ring buffers (vertices, indices, constants) and a descriptor set from a pool. It records into the open command buffer behind a full memory barrier, which keeps render-to-texture ordering without hazard tracking. Only a pending counter grows. +- Depth snapshots copy through a persistent device-local buffer recorded into the batch. Texture uploads stage through a ring and record a buffer-to-image copy. Colour and depth/stencil clears record into the batch too. +- `vk_begin`, every object destroy, the present and the engine's `submit_and_wait` flush first, so all other backend work still sees everything before it complete (the invariant the rest of the file relies on). +- `VK_DRAW_BATCH_MAX` (default 512, max 1024) caps the draws per submission. + +## Evidence + +God of War: Ascension (BCUS98232), first level, on a Windows port of this same backend (clang-cl; the backend is built there by a downstream patch, the batching code itself is the same). + +`PS3_FTRACE` timeline of 20 s of gameplay, time the walker spends waiting on the GPU: + +| | GPU wait / 20 s | +|---|---| +| per-draw submit (today) | 13.1 s (54,759 draws, ~168 us each) | +| draws batched | 8.4 s | +| + snapshots and uploads batched | 5.6 s | +| + clears batched | 2.9 s | + +Game frames per second over 600-1080 s of gameplay. Same exe, two instances run side by side and swapped halfway: + +- draws batched vs per-draw: 1.03 / 1.15 / 1.23 / 1.19 vs 0.74 / 0.79 / 0.89 / 0.89 (+39%, 4 of 4 pairs) +- + snapshots and uploads: 0.90 / 1.29 / 1.27 / 1.32 vs 0.89 / 1.18 / 1.17 / 1.19 (+8%, 4 of 4) +- + clears: within noise (+0.7%) + +16 runs of 18 minutes: no hangs, and the game's own error checks (its VRAM copy-queue `invalid size`) stayed silent. Frame dumps every 300 flips look the same with batching on and off. + +Compile on Linux: `gcc -std=c17 -Wall -Wextra` builds the file with no warnings, the same as `master`. + +## Not measured + +- Not run on Linux, macOS (Metal is untouched) or with other titles; Linux was compile-checked only. +- No Vulkan validation layer run. +- Behaviour with `VK_DRAW_BATCH` unset is the existing path. The flush hooks are a no-op with nothing pending. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-532/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-532/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c8528f7abd18cf32fdc79959d1d1912aa42f3a65 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-532/tests/oracle.patch @@ -0,0 +1,545 @@ +diff --git a/libs/video/rsx_vulkan_backend.c b/libs/video/rsx_vulkan_backend.c +index b22e08f6..6f16a35c 100644 +--- a/libs/video/rsx_vulkan_backend.c ++++ b/libs/video/rsx_vulkan_backend.c +@@ -90,7 +90,7 @@ + X(vkCreateShaderModule) X(vkDestroyShaderModule) \ + X(vkCreateDescriptorSetLayout) X(vkDestroyDescriptorSetLayout) \ + X(vkCreateDescriptorPool) X(vkDestroyDescriptorPool) \ +- X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) \ ++ X(vkAllocateDescriptorSets) X(vkUpdateDescriptorSets) X(vkResetDescriptorPool) \ + X(vkCreatePipelineLayout) X(vkDestroyPipelineLayout) \ + X(vkCreateGraphicsPipelines) X(vkDestroyPipeline) \ + X(vkCreateSampler) X(vkDestroySampler) \ +@@ -446,8 +446,22 @@ static int vk_create_image(vk_image* im, VkFormat fmt, u32 w, u32 h, + + static void vk_present_wait_gpu(void); + ++/* VK_DRAW_BATCH (vk_eng_draw): draws recorded into s_vk.cmd and not yet ++ * submitted. Anything that records other work, destroys an object or reads ++ * results flushes them first, so everything else keeps the invariant that ++ * all earlier work has completed. */ ++static u32 s_eb_pending; ++static void vk_eng_flush(void); ++static int vk_eb_active(void); /* batching decided on and on */ ++static u32 vk_eb_max(void); ++static void vk_eb_recorded(void); /* one more command in the open batch */ ++static void vk_eb_release(void); /* engine shutdown: rings and pool */ ++static int vk_eb_upload(VkImage img, VkBufferImageCopy* region, const void* src, size_t tight, ++ u32 rows, u32 row_bytes); /* -2: not batched, do it the old way */ ++ + static void vk_destroy_image(vk_image* im) + { ++ if (s_eb_pending) vk_eng_flush(); + /* Never under a present's copy that may still read it. */ + if (im->img) vk_present_wait_gpu(); + if (im->view) pvkDestroyImageView(s_vk.device, im->view, NULL); +@@ -488,8 +502,29 @@ static int vk_create_host_buffer(vk_buffer* b, VkDeviceSize size, VkBufferUsageF + return 0; + } + ++/* A buffer only the GPU touches (copies through it stay in VRAM). */ ++static int vk_create_device_buffer(vk_buffer* b, VkDeviceSize size, VkBufferUsageFlags usage) ++{ ++ VkBufferCreateInfo bci = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, ++ .size = size, .usage = usage, ++ .sharingMode = VK_SHARING_MODE_EXCLUSIVE }; ++ VK_CHECK(pvkCreateBuffer(s_vk.device, &bci, NULL, &b->buf), "vkCreateBuffer"); ++ VkMemoryRequirements req; ++ pvkGetBufferMemoryRequirements(s_vk.device, b->buf, &req); ++ u32 type; ++ if (vk_find_memory_type(req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &type) && ++ vk_find_memory_type(req.memoryTypeBits, 0, &type)) { VK_LOG("no memory for a device buffer\n"); return -1; } ++ VkMemoryAllocateInfo mai = { .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, ++ .allocationSize = req.size, .memoryTypeIndex = type }; ++ VK_CHECK(pvkAllocateMemory(s_vk.device, &mai, NULL, &b->mem), "vkAllocateMemory(device buffer)"); ++ VK_CHECK(pvkBindBufferMemory(s_vk.device, b->buf, b->mem, 0), "vkBindBufferMemory"); ++ b->ptr = NULL; b->coherent = 0; b->size = size; ++ return 0; ++} ++ + static void vk_destroy_buffer(vk_buffer* b) + { ++ if (s_eb_pending) vk_eng_flush(); + if (b->ptr) pvkUnmapMemory(s_vk.device, b->mem); + if (b->buf) pvkDestroyBuffer(s_vk.device, b->buf, NULL); + if (b->mem) pvkFreeMemory(s_vk.device, b->mem, NULL); +@@ -550,6 +585,7 @@ static void vk_cmd_after_everything(VkCommandBuffer cb) + + static int vk_begin(void) + { ++ if (s_eb_pending) vk_eng_flush(); + VK_CHECK(pvkResetCommandBuffer(s_vk.cmd, 0), "vkResetCommandBuffer"); + VkCommandBufferBeginInfo bi = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, + .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT }; +@@ -2124,6 +2160,15 @@ static int vk_eng_upload_region(VkImage img, u32 layer, u32 mip, u32 x, u32 y, + const void* src, u32 row_bytes) + { + if (tight > row_bytes) tight = row_bytes; ++ { /* VK_DRAW_BATCH: staged in a ring and recorded into the open batch. */ ++ VkBufferImageCopy region = { ++ .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, mip, layer, 1 }, ++ .imageOffset = { (int32_t)x, (int32_t)y, 0 }, ++ .imageExtent = { w, h, 1 }, ++ }; ++ const int b = vk_eb_upload(img, ®ion, src, tight, rows, row_bytes); ++ if (b != -2) return b; ++ } + vk_buffer st = {0}; + if (vk_create_host_buffer(&st, (VkDeviceSize)tight * rows, VK_BUFFER_USAGE_TRANSFER_SRC_BIT) || + !st.coherent) { vk_destroy_buffer(&st); return -1; } +@@ -2237,11 +2282,13 @@ static void vk_eng_shutdown(void* user) + vk_eng2_shutdown(user); + for (u32 i = 1; i < VK_ENG_MAX_OBJ; i++) vk_eng_release(user, i); + vk_eng_snapshot_pool_drain(); ++ vk_eb_release(); + } + + static void vk_eng_submit_and_wait(void* user, u32 reason) + { +- (void)user; (void)reason; /* every submission has already completed */ ++ (void)user; (void)reason; /* every other submission has already completed */ ++ if (s_eb_pending) vk_eng_flush(); + } + + static u32 vk_eng_color_target_create(void* user, rsx_be_format fmt, u32 w, u32 h, +@@ -2321,13 +2368,16 @@ static void vk_eng_clear_color(void* user, u32 surface, const float rgba[4]) + ((u32)(rgba[1] * 255.0f + 0.5f) << 8) | + (u32)(rgba[2] * 255.0f + 0.5f); + vk_eng_obj* o = vk_eng_get(surface, VK_ENG_COLOR); +- if (!o || vk_begin()) return; ++ if (!o) return; ++ const int batched = vk_eb_active(); ++ if (batched ? (!s_eb_pending && vk_begin()) : vk_begin()) return; + VkClearColorValue v; + memcpy(v.float32, rgba, sizeof v.float32); + VkImageSubresourceRange r = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; + vk_barrier_image(o->im.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL); + pvkCmdClearColorImage(s_vk.cmd, o->im.img, VK_IMAGE_LAYOUT_GENERAL, &v, 1, &r); +- vk_submit_and_wait(); ++ if (batched) vk_eb_recorded(); ++ else vk_submit_and_wait(); + } + + static void vk_eng_clear_depth_stencil(void* user, u32 depth, u32 flags, +@@ -2338,12 +2388,15 @@ static void vk_eng_clear_depth_stencil(void* user, u32 depth, u32 flags, + VkImageAspectFlags aspect = 0; + if (flags & RSX_BE_CLEAR_DEPTH) aspect |= VK_IMAGE_ASPECT_DEPTH_BIT; + if (flags & RSX_BE_CLEAR_STENCIL) aspect |= s_vk.depth_aspect & VK_IMAGE_ASPECT_STENCIL_BIT; +- if (!o || !aspect || vk_begin()) return; ++ if (!o || !aspect) return; ++ const int batched = vk_eb_active(); ++ if (batched ? (!s_eb_pending && vk_begin()) : vk_begin()) return; + VkClearDepthStencilValue d = { depth_value, stencil }; + VkImageSubresourceRange r = { aspect, 0, 1, 0, 1 }; + vk_barrier_image(o->im.img, s_vk.depth_aspect, VK_IMAGE_LAYOUT_GENERAL); + pvkCmdClearDepthStencilImage(s_vk.cmd, o->im.img, VK_IMAGE_LAYOUT_GENERAL, &d, 1, &r); +- vk_submit_and_wait(); ++ if (batched) vk_eb_recorded(); ++ else vk_submit_and_wait(); + } + + /* The named surface becomes the frame: blit it onto the display image, then +@@ -2352,6 +2405,7 @@ static void vk_eng_present(void* user, u32 surface) + { + (void)user; + if (!s_vk.device) return; ++ if (s_eb_pending) vk_eng_flush(); /* the present records on its own buffer */ + vk_eng_obj* o = vk_eng_get(surface, VK_ENG_COLOR); + pthread_mutex_lock(&s_vk.present_mu); + VkCommandBuffer cb = vk_present_record_begin(); +@@ -2529,6 +2583,7 @@ static u32 vk_eng_surface_view(void* user, u32 surface, u32 remap, u32 rsx_forma + #define VK_SNAP_POOL 8 + static struct { vk_image im; VkFormat fmt; u32 w, h; } s_snap_pool[VK_SNAP_POOL]; + static u32 s_snap_pool_n; ++static vk_buffer s_snap_st; /* depth snapshot bounce buffer (vk_eng_depth_snapshot) */ + + static void vk_eng_snapshot_recycle(vk_eng_obj* o) + { +@@ -2547,6 +2602,7 @@ static void vk_eng_snapshot_pool_drain(void) + { + for (u32 i = 0; i < s_snap_pool_n; i++) vk_destroy_image(&s_snap_pool[i].im); + s_snap_pool_n = 0; ++ vk_destroy_buffer(&s_snap_st); + } + + static u32 vk_eng_color_snapshot(void* user, u32 surface) +@@ -2637,12 +2693,24 @@ static u32 vk_eng_depth_snapshot(void* user, u32 depth, u32 w, u32 h) + if (vk_submit_and_wait()) return 0; + } + +- vk_buffer st = {0}; +- if (vk_create_host_buffer(&st, (VkDeviceSize)w * h * 4u, +- VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT)) { +- vk_destroy_buffer(&st); return 0; ++ /* The bounce buffer stays (device-local when the device has it, grown as ++ * needed): a fresh host buffer per snapshot cost ~4.8 ms each, 375 times ++ * in 20 s of God of War: Ascension's first level. With draw batching the ++ * copies join the open batch instead of a submission of their own; the ++ * draws that sample the snapshot come after them in the same buffer, and ++ * each batched draw starts with a full memory barrier. */ ++ const VkDeviceSize need = (VkDeviceSize)w * h * 4u; ++ if (s_snap_st.size < need) { ++ vk_destroy_buffer(&s_snap_st); /* flushes a pending batch first */ ++ if (vk_create_device_buffer(&s_snap_st, need, ++ VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT)) { ++ vk_destroy_buffer(&s_snap_st); return 0; ++ } + } +- int rc = vk_begin(); ++ vk_buffer st = s_snap_st; ++ const int batch = vk_eb_active(); ++ int rc = (batch && s_eb_pending) ? 0 : vk_begin(); ++ if (!rc && batch) vk_cmd_after_everything(s_vk.cmd); + if (!rc) { + vk_barrier_image(z->im.img, s_vk.depth_aspect, VK_IMAGE_LAYOUT_GENERAL); + vk_barrier_image(t->im.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL); +@@ -2659,9 +2727,12 @@ static u32 vk_eng_depth_snapshot(void* user, u32 depth, u32 w, u32 h) + VkBufferImageCopy in = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, + .imageExtent = { w, h, 1 } }; + pvkCmdCopyBufferToImage(s_vk.cmd, st.buf, t->im.img, VK_IMAGE_LAYOUT_GENERAL, 1, &in); +- rc = vk_submit_and_wait(); ++ if (batch) { ++ vk_barrier_image(t->im.img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL); ++ if (++s_eb_pending >= vk_eb_max()) vk_eng_flush(); ++ } else ++ rc = vk_submit_and_wait(); + } +- vk_destroy_buffer(&st); + return rc ? 0 : snap; + } + /* The depth aspect of a D32_SFLOAT target copies out as 32-bit floats, which +@@ -2748,6 +2819,7 @@ static struct { + u32 scratch_w, scratch_h; + u32 pipeline; + u32 vs_bytes, ps_bytes; ++ u8* ucpu; /* the constants, in the shared UBO's layout */ + u32 tex[RSX_BE_MAX_TEXTURES]; + rsx_be_sampler_desc samp[RSX_BE_MAX_TEXTURES]; + u32 tex_mask; +@@ -2774,6 +2846,7 @@ static u32 s_esamp_count; + + static void vk_eng_drop_framebuffers(void) + { ++ if (s_eb_pending) vk_eng_flush(); + for (u32 i = 0; i < s_e2.fb_count; i++) + if (s_e2.fb[i].fb) pvkDestroyFramebuffer(s_vk.device, s_e2.fb[i].fb, NULL); + s_e2.fb_count = 0; +@@ -2983,6 +3056,7 @@ static u32 vk_eng_pipeline_create(void* user, const char* vs_hlsl, const char* p + static void vk_eng_pipeline_release(void* user, u32 pipeline) + { + (void)user; ++ if (s_eb_pending) vk_eng_flush(); + if (!pipeline || pipeline > VK_ENG_MAX_PIPE || !s_epipe[pipeline - 1].used) return; + vk_eng_pipe* P = &s_epipe[pipeline - 1]; + for (u32 t = 0; t < VK_ENG_TOPOLOGIES; t++) +@@ -3115,29 +3189,39 @@ static void vk_eng2_shutdown(void* user) + if (s_e2.split_pipe_layout) pvkDestroyPipelineLayout(s_vk.device, s_e2.split_pipe_layout, NULL); + if (s_e2.split_pool) pvkDestroyDescriptorPool(s_vk.device, s_e2.split_pool, NULL); + if (s_e2.split_layout) pvkDestroyDescriptorSetLayout(s_vk.device, s_e2.split_layout, NULL); ++ free(s_e2.ucpu); + memset(&s_e2, 0, sizeof s_e2); + for (u32 i = 0; i < s_esamp_count; i++) pvkDestroySampler(s_vk.device, s_esamp[i].s, NULL); + s_esamp_count = 0; + } + +-/* Constants go straight into the shared UBO: vertex at 0, pixel at ps_off. +- * Every operation is waited on, so overwriting per draw is safe. */ ++/* Constants are kept in ordinary memory laid out like the shared UBO (vertex ++ * at 0, pixel at ps_off) and copied to the GPU per draw: into the draw's ring ++ * slice when batched, into the shared UBO otherwise (every such draw is waited ++ * on, so overwriting it is safe). Writing them straight into the UBO meant a ++ * batched draw read them back out of it, and that memory is host-coherent, ++ * i.e. write-combined and uncached on most drivers. */ ++static u8* vk_eng_ucpu(void) ++{ ++ if (!s_e2.ucpu && s_g.ubo.size) s_e2.ucpu = (u8*)calloc(1, (size_t)s_g.ubo.size); ++ return s_e2.ucpu; ++} + static void vk_eng_bind_vs_constants(void* user, const void* data, u32 bytes) + { + (void)user; +- if (!s_g.on || !data) { s_e2.vs_bytes = 0; return; } ++ if (!s_g.on || !data || !vk_eng_ucpu()) { s_e2.vs_bytes = 0; return; } + const u32 cap = (u32)s_g.ps_off; + if (bytes > cap) { bytes = cap; if (!(s_e2.warned & 2u)) { VK_LOG("engine: VS constants truncated\n"); s_e2.warned |= 2u; } } +- memcpy(s_g.ubo.ptr, data, bytes); ++ memcpy(s_e2.ucpu, data, bytes); + s_e2.vs_bytes = bytes; + } + static void vk_eng_bind_ps_constants(void* user, const void* data, u32 bytes) + { + (void)user; +- if (!s_g.on || !data) { s_e2.ps_bytes = 0; return; } ++ if (!s_g.on || !data || !vk_eng_ucpu()) { s_e2.ps_bytes = 0; return; } + const u32 cap = (u32)(s_g.ubo.size - s_g.ps_off); + if (bytes > cap) { bytes = cap; if (!(s_e2.warned & 4u)) { VK_LOG("engine: PS constants truncated\n"); s_e2.warned |= 4u; } } +- memcpy((u8*)s_g.ubo.ptr + s_g.ps_off, data, bytes); ++ memcpy(s_e2.ucpu + s_g.ps_off, data, bytes); + s_e2.ps_bytes = bytes; + } + static void vk_eng_bind_textures(void* user, const u32* textures, +@@ -3296,19 +3380,160 @@ static VkImageView vk_eng_dummy_cube_view(void) + return s_eobj[s_e2.dummy_cube].im.view; + } + ++/* --------------------------------------------------------------------------- ++ * Draw batching (VK_DRAW_BATCH=1) ++ * ++ * Every vk_eng_draw used to submit its own command buffer and wait on a ++ * fence, because the vertex, index and uniform buffers and the descriptor set ++ * are single objects rewritten per draw. In God of War: Ascension's first level ++ * that was 54,759 draws in 20 s at ~168 us each: the FIFO walker spent 46% of ++ * its time blocked on the GPU, the RSX ring drained one draw at a time and the ++ * SPU geometry jobs waited for ring space. Batched, a draw takes slices of ++ * three ring buffers and a descriptor set from a pool, records into the open ++ * command buffer, and only s_eb_pending grows. vk_eng_flush() submits, waits ++ * once, and resets the rings and the pool; vk_begin, every object destroy, the ++ * present and the engine's own submit point call it first, so all other work ++ * keeps seeing everything before it complete. Between batched draws a full ++ * memory barrier keeps render-to-texture ordering without tracking. ++ * VK_DRAW_BATCH_MAX (default 512) caps the draws per submission. ++ * -------------------------------------------------------------------------*/ ++#define VK_EB_VB_BYTES (64u << 20) ++#define VK_EB_IB_BYTES (16u << 20) ++#define VK_EB_UB_BYTES (32u << 20) ++#define VK_EB_SB_BYTES (64u << 20) /* texture upload staging */ ++#define VK_EB_MAX_SETS 1024u ++ ++static struct { ++ int on; /* -1 undecided, 0 off, 1 on */ ++ u32 max_draws; ++ vk_buffer vb, ib, ub, sb; ++ VkDeviceSize vb_head, ib_head, ub_head, sb_head, ub_align; ++ VkDescriptorPool pool; ++ u32 sets; ++ unsigned long long draws, flushes; ++} s_eb = { .on = -1 }; ++ ++static int vk_eb_on(void) ++{ ++ if (s_eb.on >= 0) return s_eb.on; ++ const char* e = getenv("VK_DRAW_BATCH"); ++ s_eb.on = 0; ++ if (!e || *e != '1' || !s_g.on) return 0; ++ const char* m = getenv("VK_DRAW_BATCH_MAX"); ++ s_eb.max_draws = m && atoi(m) > 0 ? (u32)atoi(m) : 512u; ++ if (s_eb.max_draws > VK_EB_MAX_SETS) s_eb.max_draws = VK_EB_MAX_SETS; ++ VkPhysicalDeviceProperties p; ++ pvkGetPhysicalDeviceProperties(s_vk.phys, &p); ++ s_eb.ub_align = p.limits.minUniformBufferOffsetAlignment ? p.limits.minUniformBufferOffsetAlignment : 256; ++ VkDescriptorPoolSize ps[3] = { ++ { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2 * VK_EB_MAX_SETS }, ++ { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, RSX_MAX_TEXTURES * VK_EB_MAX_SETS }, ++ { VK_DESCRIPTOR_TYPE_SAMPLER, RSX_MAX_TEXTURES * VK_EB_MAX_SETS }, ++ }; ++ VkDescriptorPoolCreateInfo pci = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, ++ .maxSets = VK_EB_MAX_SETS, .poolSizeCount = 3, .pPoolSizes = ps }; ++ if (vk_create_host_buffer(&s_eb.vb, VK_EB_VB_BYTES, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT) || !s_eb.vb.coherent || ++ vk_create_host_buffer(&s_eb.ib, VK_EB_IB_BYTES, VK_BUFFER_USAGE_INDEX_BUFFER_BIT) || !s_eb.ib.coherent || ++ vk_create_host_buffer(&s_eb.ub, VK_EB_UB_BYTES, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT) || !s_eb.ub.coherent || ++ vk_create_host_buffer(&s_eb.sb, VK_EB_SB_BYTES, VK_BUFFER_USAGE_TRANSFER_SRC_BIT) || !s_eb.sb.coherent || ++ pvkCreateDescriptorPool(s_vk.device, &pci, NULL, &s_eb.pool) != VK_SUCCESS) { ++ VK_LOG("draw batching: no host-coherent ring memory, staying off\n"); ++ return 0; ++ } ++ VK_LOG("draw batching: on (up to %u draws per submission)\n", s_eb.max_draws); ++ s_eb.on = 1; ++ return 1; ++} ++ ++/* The rings and the pool live until the engine shuts down; a later vk_eb_on ++ * decides again. Also frees what a failed vk_eb_on had already created. */ ++static void vk_eb_release(void) ++{ ++ if (s_eb_pending) vk_eng_flush(); ++ vk_destroy_buffer(&s_eb.vb); ++ vk_destroy_buffer(&s_eb.ib); ++ vk_destroy_buffer(&s_eb.ub); ++ vk_destroy_buffer(&s_eb.sb); ++ if (s_eb.pool) pvkDestroyDescriptorPool(s_vk.device, s_eb.pool, NULL); ++ memset(&s_eb, 0, sizeof s_eb); ++ s_eb.on = -1; ++} ++ ++static int vk_eb_active(void) { return s_eb.on == 1; } ++static u32 vk_eb_max(void) { return s_eb.max_draws; } ++static void vk_eb_recorded(void) { if (++s_eb_pending >= s_eb.max_draws) vk_eng_flush(); } ++ ++static VkDeviceSize vk_eb_take(VkDeviceSize* head, VkDeviceSize cap, VkDeviceSize bytes, VkDeviceSize align); ++ ++/* A texture upload as one more batched operation: rows staged in the ring, the ++ * copy recorded behind a full memory barrier (earlier draws of the batch may ++ * still sample the old texels) and followed by one on the image (later draws ++ * sample the new ones). Each used to allocate a host buffer and wait on its own ++ * submission, ~3000 times in 20 s of God of War: Ascension's first level. */ ++static int vk_eb_upload(VkImage img, VkBufferImageCopy* region, const void* src, size_t tight, ++ u32 rows, u32 row_bytes) ++{ ++ if (!vk_eb_active()) return -2; ++ const VkDeviceSize bytes = (VkDeviceSize)tight * rows; ++ if (!bytes || bytes > VK_EB_SB_BYTES) return -2; ++ VkDeviceSize off = vk_eb_take(&s_eb.sb_head, VK_EB_SB_BYTES, bytes, 16u); ++ if (off == (VkDeviceSize)-1) { ++ vk_eng_flush(); ++ off = vk_eb_take(&s_eb.sb_head, VK_EB_SB_BYTES, bytes, 16u); ++ if (off == (VkDeviceSize)-1) return -2; ++ } ++ for (u32 y = 0; y < rows; y++) ++ memcpy((u8*)s_eb.sb.ptr + off + (size_t)y * tight, (const u8*)src + (size_t)y * row_bytes, tight); ++ if (!s_eb_pending && vk_begin()) return -1; ++ vk_cmd_after_everything(s_vk.cmd); ++ region->bufferOffset = off; ++ pvkCmdCopyBufferToImage(s_vk.cmd, s_eb.sb.buf, img, VK_IMAGE_LAYOUT_GENERAL, 1, region); ++ vk_barrier_image(img, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL); ++ if (++s_eb_pending >= s_eb.max_draws) vk_eng_flush(); ++ return 0; ++} ++ ++static void vk_eng_flush(void) ++{ ++ if (!s_eb_pending) return; ++ s_eb_pending = 0; /* first: the submit below must not re-enter */ ++ vk_submit_and_wait(); ++ s_eb.vb_head = s_eb.ib_head = s_eb.ub_head = s_eb.sb_head = 0; ++ if (s_eb.sets) { pvkResetDescriptorPool(s_vk.device, s_eb.pool, 0); s_eb.sets = 0; } ++ if ((++s_eb.flushes & 0x3FFFu) == 0) ++ VK_LOG("draw batching: %llu draws in %llu submissions\n", s_eb.draws, s_eb.flushes); ++} ++ ++static VkDeviceSize vk_eb_take(VkDeviceSize* head, VkDeviceSize cap, VkDeviceSize bytes, VkDeviceSize align) ++{ ++ const VkDeviceSize at = (*head + align - 1u) / align * align; ++ if (at + bytes > cap) return (VkDeviceSize)-1; ++ *head = at + bytes; ++ return at; ++} ++ ++static VkDescriptorSet vk_eng_write_descriptors_to(const vk_eng_pipe* P, VkDescriptorSet set, ++ VkBuffer ubo, VkDeviceSize vs_off, VkDeviceSize ps_off); ++ + /* Fill the set the bound pipeline uses: the shared one (sixteen textures in + * one binding), or for a pipeline with cube units the split one (one binding + * per unit). Returns the set, or VK_NULL_HANDLE. */ + static VkDescriptorSet vk_eng_write_descriptors(const vk_eng_pipe* P) ++{ ++ const VkDescriptorSet set = P->cube_mask ? s_e2.split_set : s_g.set; ++ return vk_eng_write_descriptors_to(P, set, s_g.ubo.buf, 0, s_g.ps_off); ++} ++ ++static VkDescriptorSet vk_eng_write_descriptors_to(const vk_eng_pipe* P, VkDescriptorSet set, ++ VkBuffer ubo, VkDeviceSize vs_off, VkDeviceSize ps_off) + { + const int split = P->cube_mask != 0; +- const VkDescriptorSet set = split ? s_e2.split_set : s_g.set; + if (!set) return VK_NULL_HANDLE; + const VkImageView dummy_cube = split ? vk_eng_dummy_cube_view() : VK_NULL_HANDLE; + if (split && !dummy_cube) return VK_NULL_HANDLE; + VkDescriptorBufferInfo bi[2] = { +- { s_g.ubo.buf, 0, s_e2.vs_bytes ? s_e2.vs_bytes : 16u }, +- { s_g.ubo.buf, s_g.ps_off, s_e2.ps_bytes ? s_e2.ps_bytes : 16u }, ++ { ubo, vs_off, s_e2.vs_bytes ? s_e2.vs_bytes : 16u }, ++ { ubo, ps_off, s_e2.ps_bytes ? s_e2.ps_bytes : 16u }, + }; + VkDescriptorImageInfo ii[RSX_MAX_TEXTURES], si[RSX_MAX_TEXTURES]; + for (u32 u = 0; u < RSX_MAX_TEXTURES; u++) { +@@ -3381,16 +3606,67 @@ static void vk_eng_draw(void* user, rsx_topology topology, const void* vertices, + if (!pipe || !rp || !fb) return; + + const VkDeviceSize vbytes = (VkDeviceSize)vertex_count * stride; +- if (vk_ensure_vertex_buffer(vbytes)) return; +- memcpy(s_vk.vertices.ptr, vertices, (size_t)vbytes); +- if (indices && index_count) { +- if (vk_eng_ensure_indices((VkDeviceSize)index_count * 4u)) return; +- memcpy(s_e2.indices.ptr, indices, (size_t)index_count * 4u); ++ const VkDeviceSize ibytes = (indices && index_count) ? (VkDeviceSize)index_count * 4u : 0; ++ VkBuffer vbuf = s_vk.vertices.buf, ibuf = s_e2.indices.buf; ++ VkDeviceSize voff = 0, ioff = 0; ++ VkDescriptorSet set = VK_NULL_HANDLE; ++ const u32 vsb = s_e2.vs_bytes ? s_e2.vs_bytes : 16u, psb = s_e2.ps_bytes ? s_e2.ps_bytes : 16u; ++ int batched = vk_eb_on() && vbytes <= VK_EB_VB_BYTES && ibytes <= VK_EB_IB_BYTES; ++ if (batched && P->cube_mask && !vk_eng_dummy_cube_view()) return; /* may flush: before any slice */ ++ if (batched) { ++ /* Slices of the rings and a set from the pool; a full one flushes the ++ * batch (which empties them all) and the draw takes its slices again. */ ++ for (int tries = 0; tries < 2; tries++) { ++ VkDeviceSize vh = s_eb.vb_head, ih = s_eb.ib_head, uh = s_eb.ub_head; ++ voff = vk_eb_take(&vh, VK_EB_VB_BYTES, vbytes, 16u); ++ ioff = ibytes ? vk_eb_take(&ih, VK_EB_IB_BYTES, ibytes, 16u) : 0; ++ const VkDeviceSize uvs = vk_eb_take(&uh, VK_EB_UB_BYTES, vsb, s_eb.ub_align); ++ const VkDeviceSize ups = uvs == (VkDeviceSize)-1 ? uvs : vk_eb_take(&uh, VK_EB_UB_BYTES, psb, s_eb.ub_align); ++ if (voff != (VkDeviceSize)-1 && ioff != (VkDeviceSize)-1 && ups != (VkDeviceSize)-1 && ++ s_eb.sets < VK_EB_MAX_SETS) { ++ VkDescriptorSetLayout lay = P->cube_mask ? s_e2.split_layout : s_g.set_layout; ++ VkDescriptorSetAllocateInfo dai = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, ++ .descriptorPool = s_eb.pool, .descriptorSetCount = 1, ++ .pSetLayouts = &lay }; ++ if (pvkAllocateDescriptorSets(s_vk.device, &dai, &set) == VK_SUCCESS) { ++ s_eb.sets++; ++ s_eb.vb_head = vh; s_eb.ib_head = ih; s_eb.ub_head = uh; ++ memcpy((u8*)s_eb.ub.ptr + uvs, vk_eng_ucpu(), vsb); ++ memcpy((u8*)s_eb.ub.ptr + ups, vk_eng_ucpu() + s_g.ps_off, psb); ++ if (!vk_eng_write_descriptors_to(P, set, s_eb.ub.buf, uvs, ups)) return; ++ break; ++ } ++ set = VK_NULL_HANDLE; ++ } ++ if (tries || !s_eb_pending) { batched = 0; break; } ++ vk_eng_flush(); ++ } ++ if (batched && !set) batched = 0; ++ } ++ if (batched) { ++ memcpy((u8*)s_eb.vb.ptr + voff, vertices, (size_t)vbytes); ++ if (ibytes) memcpy((u8*)s_eb.ib.ptr + ioff, indices, (size_t)ibytes); ++ vbuf = s_eb.vb.buf; ibuf = s_eb.ib.buf; ++ if (!s_eb_pending && vk_begin()) return; ++ /* Earlier draws of this batch may have rendered what this one samples ++ * or blends over: order it after all of them. */ ++ vk_cmd_after_everything(s_vk.cmd); ++ } else { ++ if (s_eb_pending) vk_eng_flush(); ++ if (vk_ensure_vertex_buffer(vbytes)) return; ++ memcpy(s_vk.vertices.ptr, vertices, (size_t)vbytes); ++ if (ibytes) { ++ if (vk_eng_ensure_indices(ibytes)) return; ++ memcpy(s_e2.indices.ptr, indices, (size_t)ibytes); ++ } ++ vbuf = s_vk.vertices.buf; ibuf = s_e2.indices.buf; voff = ioff = 0; ++ if (!vk_eng_ucpu()) return; ++ memcpy(s_g.ubo.ptr, s_e2.ucpu, vsb); ++ memcpy((u8*)s_g.ubo.ptr + s_g.ps_off, s_e2.ucpu + s_g.ps_off, psb); ++ set = vk_eng_write_descriptors(P); ++ if (!set) return; ++ if (vk_begin()) return; + } +- const VkDescriptorSet set = vk_eng_write_descriptors(P); +- if (!set) return; +- +- if (vk_begin()) return; + /* Everything submitted before is complete (each submission is waited + * on); this orders memory for the surfaces this draw touches. */ + for (u32 i = 0; i < n; i++) +@@ -3421,16 +3697,17 @@ static void vk_eng_draw(void* user, rsx_topology topology, const void* vertices, + pvkCmdBindDescriptorSets(s_vk.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, + P->cube_mask ? s_e2.split_pipe_layout : s_g.pipe_layout, + 0, 1, &set, 0, NULL); +- VkDeviceSize off = 0; +- pvkCmdBindVertexBuffers(s_vk.cmd, 0, 1, &s_vk.vertices.buf, &off); +- if (indices && index_count) { +- pvkCmdBindIndexBuffer(s_vk.cmd, s_e2.indices.buf, 0, VK_INDEX_TYPE_UINT32); ++ pvkCmdBindVertexBuffers(s_vk.cmd, 0, 1, &vbuf, &voff); ++ if (ibytes) { ++ pvkCmdBindIndexBuffer(s_vk.cmd, ibuf, ioff, VK_INDEX_TYPE_UINT32); + pvkCmdDrawIndexed(s_vk.cmd, index_count, 1, 0, 0, 0); + } else { + pvkCmdDraw(s_vk.cmd, vertex_count, 1, 0, 0); + } + pvkCmdEndRenderPass(s_vk.cmd); +- vk_submit_and_wait(); ++ if (!batched) { vk_submit_and_wait(); return; } ++ s_eb.draws++; ++ if (++s_eb_pending >= s_eb.max_draws) vk_eng_flush(); + } + + static const rsx_draw_backend s_vk_engine_backend = { diff --git a/tasks/sp00nznet__ps3recomp-532/tests/test.sh b/tasks/sp00nznet__ps3recomp-532/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-532/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-532/tests/verifier.py b/tasks/sp00nznet__ps3recomp-532/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-532/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-533/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-533/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e58bcfa58777d72bba591f37e690838b686d5be --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-533/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-533/instruction.md b/tasks/sp00nznet__ps3recomp-533/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a7e9d5c410d27fd1726f8ea770c49ae3266fff1e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-533/instruction.md @@ -0,0 +1,48 @@ +# Issue + +**Title:** spu_drain: run the per-hop hooks' common case inline + +## Description + +## Why + +Lifted SPU code passes control between functions through the trampoline, and an SPU thread takes millions of hops a second. On every hop the drain loops called: + +- `yz_lockstep_tick`; +- `spu_task_launch_check`, which in turn called `spu_check_stack_reset` in `spu_channels.c`. + +Each `spu_drain_call` also called `spu_depth_guard`, which wrote a ring and a counter shared by all SPU threads. + +With their switches off, these hooks return almost at once. In God of War HD (NPUA80490) gameplay they still took about a fifth of each SPU thread's samples: + +| Hook | Share of an SPU thread | +|---|---| +| `spu_task_launch_check` | ~11% | +| `spu_check_stack_reset` | ~3% | +| `yz_lockstep_tick` | ~3% | +| `spu_depth_guard` | 2-5% | + +## Change + +- `spu_drain_call` runs the hooks' default work inline, and `SPU_DRAIN` does the same through the new `spu_drain_hop`. That work is: + - the recent-pc ring; + - the step count, with the LS 0 job-complete check; + - the PM flow record. +- `spu_task_launch_check` still runs in full when `SPU_NO_LS0_END`, `SPU_EXITTRACE`, `SPU_STEPTRACE` or `SPU_JOBDRAIN` is set. +- The lockstep tick runs only when lockstep is not off. +- The stack-reset check runs only when an entry is registered. Its count is now `g_spu_stack_reset_count`, and `spu_check_stack_reset` tests it first. +- `spu_drain_call` tests the depth limit inline. +- `spu_depth_guard` no longer keeps the shared ring. When it trips, it reports this thread's recent hops instead. + +## Evidence + +All numbers are from God of War HD gameplay. + +- **Profile:** the four hooks are gone. `spu_drain_call`, with them inlined, is 9-11% of an SPU thread. +- **Frame:** the main thread waits on an SPU job every frame (a `usleep` poll). Measured with `PS3_FTRACE`, that wait went from 7.8 ms to 4-6 ms a frame. The frame median went from 45.4 to 41.5 ms. That run also had the store-path change from the companion PR, which does not touch the SPU side. +- **Behaviour:** the run logs show the same SPURS markers as before (workload waits, job ends). +- **Tests:** `PS3RECOMP_BUILD_TESTS=ON` passes 16/16. `spu_drain.c` and `spu_channels.c` also build with GCC. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-533/solution/patch.diff b/tasks/sp00nznet__ps3recomp-533/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9f2a6e5a92a8b6813f5c8d3606edc1bd4c22ecba --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-533/solution/patch.diff @@ -0,0 +1,206 @@ +diff --git a/runtime/spu/spu_channels.c b/runtime/spu/spu_channels.c +index 59f5e4b8..4fdb4b42 100644 +--- a/runtime/spu/spu_channels.c ++++ b/runtime/spu/spu_channels.c +@@ -1552,12 +1552,12 @@ void spu_overlay_register_region(uint32_t content_ea, uint32_t span, int image_i + * Matching the resolved function, not just its LS address, avoids affecting + * unrelated overlays using the same address. Registration precedes execution. */ + static struct { uint32_t entry; int image_id; } s_stack_reset[16]; +-static unsigned s_stack_reset_count; ++unsigned g_spu_stack_reset_count; /* spu_drain.c skips the check at 0 */ + void spu_register_stack_reset_entry(uint32_t entry, int image_id) + { +- if (s_stack_reset_count < 16) { +- s_stack_reset[s_stack_reset_count].entry = entry & SPU_LS_MASK; +- s_stack_reset[s_stack_reset_count++].image_id = image_id; ++ if (g_spu_stack_reset_count < 16) { ++ s_stack_reset[g_spu_stack_reset_count].entry = entry & SPU_LS_MASK; ++ s_stack_reset[g_spu_stack_reset_count++].image_id = image_id; + } + } + +@@ -1565,8 +1565,8 @@ void spu_register_stack_reset_entry(uint32_t entry, int image_id) + * a stack-switching routine without going through spu_indirect_branch. */ + void spu_check_stack_reset(spu_context* ctx, void (*fn)(spu_context*)) + { +- if (!ctx->host_depth || !s_spu_halt_armed || ctx->policy_mode) return; +- for (unsigned i = 0; i < s_stack_reset_count; ++i) ++ if (!g_spu_stack_reset_count || !ctx->host_depth || !s_spu_halt_armed || ctx->policy_mode) return; ++ for (unsigned i = 0; i < g_spu_stack_reset_count; ++i) + if (ctx->pc == s_stack_reset[i].entry && + fn == spu_lookup(ctx->pc, s_stack_reset[i].image_id)) { + g_spu_trampoline_fn = 0; +diff --git a/runtime/spu/spu_context.h b/runtime/spu/spu_context.h +index f46d415f..e032f857 100644 +--- a/runtime/spu/spu_context.h ++++ b/runtime/spu/spu_context.h +@@ -783,6 +783,8 @@ extern SPU_THREAD_LOCAL unsigned g_spu_pch_n; + /* Central per-transfer hooks (stubbed in spu_drain.c until their milestones). */ + void yz_lockstep_tick(spu_context* ctx); /* round-robin token gate */ + void spu_task_launch_check(spu_context* ctx, void* fn); /* SPURS task-launch */ ++/* Both of the above for one trampoline hop, with the common case inline. */ ++void spu_drain_hop(spu_context* ctx, void (*fn)(spu_context*)); + /* Restore image_id after a call-bracket (adopt-on-serve); re-applies the + * persistent LS-0xA00 workload module if one is set. */ + void spu_img_restore(spu_context* ctx, int32_t saved_img); +@@ -872,8 +874,7 @@ static inline void spu_pchist_tick(const spu_context* ctx) + } \ + void (*_tf)(spu_context*) = g_spu_trampoline_fn; \ + g_spu_trampoline_fn = 0; \ +- yz_lockstep_tick(ctx); \ +- spu_task_launch_check((ctx), (void*)_tf); \ ++ spu_drain_hop((ctx), _tf); \ + if ((ctx)->int_enable && \ + ((ctx)->event_status & (ctx)->event_mask)) \ + _tf = spu_take_interrupt((ctx), _tf); \ +diff --git a/runtime/spu/spu_drain.c b/runtime/spu/spu_drain.c +index fc3cea12..0f4f0754 100644 +--- a/runtime/spu/spu_drain.c ++++ b/runtime/spu/spu_drain.c +@@ -6,6 +6,7 @@ + * functions (not macros) means the SPU_DRAIN/SPU_RET call sites are already in + * place -- later milestones only replace the bodies. */ + #include "spu_context.h" ++#include "spu_lockstep.h" + #include + + /* See spu_context.h `irq_frame`. */ +@@ -58,6 +59,14 @@ unsigned spu_recent_pcs(uint32_t* out, unsigned max) + return k; + } + ++static void spu_job_ls0_note(const spu_context* ctx) ++{ ++ static int _n = 0; ++ if (PS3_LOG_FIRST(_n, 8)) ++ fprintf(stderr, "[spurs-job] img=%d branched to LS 0 -- job complete\n", ++ ctx->image_id); ++} ++ + void spu_task_launch_check(spu_context* ctx, void* fn) + { + t_recent[t_recent_n++ & 31] = (uint32_t)ctx->pc & SPU_LS_MASK; +@@ -84,10 +93,7 @@ void spu_task_launch_check(spu_context* ctx, void* fn) + + if (!s_no_ls0 && ctx->steps++ && (ctx->pc & SPU_LS_MASK) == 0 && + !ctx->policy_mode && ctx->image_id > 0) { +- static int _n = 0; +- if (PS3_LOG_FIRST(_n, 8)) +- fprintf(stderr, "[spurs-job] img=%d branched to LS 0 -- job complete\n", +- ctx->image_id); ++ spu_job_ls0_note(ctx); + if (s_et >= 0 && ctx->image_id == s_et) { + fprintf(stderr, "[spu-exit] img=%d last PCs:", ctx->image_id); + for (int i = 32; i >= 1; i--) +@@ -334,24 +340,14 @@ void (*spu_take_interrupt(spu_context* ctx, + } + + /* See the declaration in spu_context.h. */ ++static uint32_t s_depth_max; /* SPU_HOST_DEPTH_MAX, 0 until read */ + void spu_depth_guard(spu_context* ctx) + { +- static uint32_t s_max = 0; +- if (!s_max) { ++ if (!s_depth_max) { + const char* e = getenv("SPU_HOST_DEPTH_MAX"); +- s_max = e ? (uint32_t)strtoul(e, 0, 0) : 2000u; ++ s_depth_max = e ? (uint32_t)strtoul(e, 0, 0) : 2000u; + } +- +- /* Ring of recent drain sites. When the depth trips, the useful question is +- * not "where are we" but "what cycle got us here" -- one pc names a point, +- * a ring names the loop. */ +- enum { RING = 24 }; +- static uint32_t s_ring[RING]; +- static uint32_t s_n; +- s_ring[s_n % RING] = ((uint32_t)ctx->pc & SPU_LS_MASK); +- s_n++; +- +- if (ctx->host_depth < s_max) return; ++ if (ctx->host_depth < s_depth_max) return; + static int s_reported = 0; + if (s_reported < 1) { /* one report: five SPU threads all trip together */ + s_reported++; +@@ -359,10 +355,14 @@ void spu_depth_guard(spu_context* ctx) + " -- lifted call recursion, halting the SPU\n", + ctx->image_id, (uint32_t)ctx->pc & SPU_LS_MASK, + ctx->gpr[0]._u32[0] & SPU_LS_MASK, ctx->host_depth); +- fprintf(stderr, "[spu-depth] recent drain sites (oldest first):"); +- uint32_t start = (s_n > RING) ? (s_n - RING) : 0; +- for (uint32_t k = start; k < s_n; k++) +- fprintf(stderr, " %05X", s_ring[k % RING]); ++ /* When the depth trips, the useful question is not "where are we" ++ * but "what cycle got us here" -- one pc names a point, a ring names ++ * the loop. The hop ring is this thread's own. */ ++ uint32_t r[32]; ++ const unsigned n = spu_recent_pcs(r, 32); ++ fprintf(stderr, "[spu-depth] recent hops (oldest first):"); ++ for (unsigned k = 0; k < n; k++) ++ fprintf(stderr, " %05X", r[k]); + fprintf(stderr, "\n"); + fflush(stderr); + } +@@ -396,9 +396,52 @@ int spu_tailret_enabled(void) + typedef void (*spu_drain_fn)(spu_context*); + extern spu_drain_fn spu_lookup(uint32_t addr, int image_id); + ++/* The hooks every trampoline hop runs, with their common case inline. Each ++ * SPU thread takes millions of hops a second, and per hop they were three ++ * calls into two files that nearly always returned at once: about a fifth of ++ * an SPU thread's time in God of War HD gameplay. The full checks still run ++ * when one of their switches is set, and the lockstep and stack-reset hooks ++ * whenever those are in use. */ ++static int s_hop_full = -1; /* a switch spu_task_launch_check reads is set */ ++static __attribute__((noinline)) int spu_hop_full_read(void) ++{ ++ s_hop_full = (getenv("SPU_NO_LS0_END") || getenv("SPU_EXITTRACE") || ++ getenv("SPU_STEPTRACE") || getenv("SPU_JOBDRAIN")) ? 1 : 0; ++ return s_hop_full; ++} ++ ++static inline void spu_hop(spu_context* ctx, void (*fn)(spu_context*)) ++{ ++ extern unsigned g_spu_stack_reset_count; /* spu_channels.c */ ++ extern void spu_check_stack_reset(spu_context*, void (*)(spu_context*)); ++ if (g_yz_lockstep_on != 0) yz_lockstep_tick(ctx); ++ if (__builtin_expect(s_hop_full != 0, 0) && (s_hop_full > 0 || spu_hop_full_read())) { ++ spu_task_launch_check(ctx, (void*)fn); ++ return; ++ } ++ /* What spu_task_launch_check does with every switch off. */ ++ const uint32_t pc = (uint32_t)ctx->pc & SPU_LS_MASK; ++ t_recent[t_recent_n++ & 31] = pc; ++ if (g_spu_stack_reset_count) ++ spu_check_stack_reset(ctx, fn); ++ if (ctx->steps++ && pc == 0 && !ctx->policy_mode && ctx->image_id > 0) { ++ spu_job_ls0_note(ctx); ++ spu_halt(ctx); ++ return; ++ } ++ if (g_pm_flow_ctx == (void*)ctx && g_pm_flow_n < 8192) ++ g_pm_flow_buf[g_pm_flow_n++] = ctx->pc; ++} ++ ++void spu_drain_hop(spu_context* ctx, void (*fn)(spu_context*)) ++{ ++ spu_hop(ctx, fn); ++} ++ + void spu_drain_call(spu_context* ctx, uint32_t return_pc) + { +- spu_depth_guard(ctx); ++ if (__builtin_expect(ctx->host_depth >= s_depth_max, 0)) ++ spu_depth_guard(ctx); + /* The frame an interrupt taken in THIS loop returns to. It stays armed + * after the handler's first host function returns -- the handler keeps + * running as trampolines of this loop -- until its iret fires or the +@@ -417,8 +460,7 @@ void spu_drain_call(spu_context* ctx, uint32_t return_pc) + void (*fn)(spu_context*) = g_spu_trampoline_fn; + g_spu_trampoline_fn = 0; + ctx->drain_ret_pc = return_pc & SPU_LS_MASK; /* re-set: a nested drain changed it */ +- yz_lockstep_tick(ctx); +- spu_task_launch_check(ctx, (void*)fn); ++ spu_hop(ctx, fn); + if (ctx->int_enable && (ctx->event_status & ctx->event_mask)) { + void (*vf)(spu_context*) = spu_take_interrupt(ctx, fn); + if (!ctx->int_enable) { /* taken (a take clears the enable; a deferral leaves it) */ diff --git a/tasks/sp00nznet__ps3recomp-533/solution/solve.sh b/tasks/sp00nznet__ps3recomp-533/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-533/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-533/task.toml b/tasks/sp00nznet__ps3recomp-533/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..974bd88cb7ba6b8754d3ccc7a1d2854d9bf40fe7 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-533/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-533" +description = "spu_drain: run the per-hop hooks' common case inline" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "a6d76c895f77eb30b90a806c830544e61821b77f" +reference = "https://github.com/sp00nznet/ps3recomp/pull/533" +source_access = "auto" +built_at = "2026-11-16T16:09:59.933638+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e1af2a935b405728e5234aa3acd3116b18930a9edb7fcabaee3cef69dec3bee1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-26T15:32:54Z" +diff_format = "unified" +context_files = [ + "runtime/spu/spu_channels.c", + "runtime/spu/spu_context.h", + "runtime/spu/spu_drain.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 109 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.119692+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-533/tests/capture.py b/tasks/sp00nznet__ps3recomp-533/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-533/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-533/tests/instruction.md b/tasks/sp00nznet__ps3recomp-533/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a7e9d5c410d27fd1726f8ea770c49ae3266fff1e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-533/tests/instruction.md @@ -0,0 +1,48 @@ +# Issue + +**Title:** spu_drain: run the per-hop hooks' common case inline + +## Description + +## Why + +Lifted SPU code passes control between functions through the trampoline, and an SPU thread takes millions of hops a second. On every hop the drain loops called: + +- `yz_lockstep_tick`; +- `spu_task_launch_check`, which in turn called `spu_check_stack_reset` in `spu_channels.c`. + +Each `spu_drain_call` also called `spu_depth_guard`, which wrote a ring and a counter shared by all SPU threads. + +With their switches off, these hooks return almost at once. In God of War HD (NPUA80490) gameplay they still took about a fifth of each SPU thread's samples: + +| Hook | Share of an SPU thread | +|---|---| +| `spu_task_launch_check` | ~11% | +| `spu_check_stack_reset` | ~3% | +| `yz_lockstep_tick` | ~3% | +| `spu_depth_guard` | 2-5% | + +## Change + +- `spu_drain_call` runs the hooks' default work inline, and `SPU_DRAIN` does the same through the new `spu_drain_hop`. That work is: + - the recent-pc ring; + - the step count, with the LS 0 job-complete check; + - the PM flow record. +- `spu_task_launch_check` still runs in full when `SPU_NO_LS0_END`, `SPU_EXITTRACE`, `SPU_STEPTRACE` or `SPU_JOBDRAIN` is set. +- The lockstep tick runs only when lockstep is not off. +- The stack-reset check runs only when an entry is registered. Its count is now `g_spu_stack_reset_count`, and `spu_check_stack_reset` tests it first. +- `spu_drain_call` tests the depth limit inline. +- `spu_depth_guard` no longer keeps the shared ring. When it trips, it reports this thread's recent hops instead. + +## Evidence + +All numbers are from God of War HD gameplay. + +- **Profile:** the four hooks are gone. `spu_drain_call`, with them inlined, is 9-11% of an SPU thread. +- **Frame:** the main thread waits on an SPU job every frame (a `usleep` poll). Measured with `PS3_FTRACE`, that wait went from 7.8 ms to 4-6 ms a frame. The frame median went from 45.4 to 41.5 ms. That run also had the store-path change from the companion PR, which does not touch the SPU side. +- **Behaviour:** the run logs show the same SPURS markers as before (workload waits, job ends). +- **Tests:** `PS3RECOMP_BUILD_TESTS=ON` passes 16/16. `spu_drain.c` and `spu_channels.c` also build with GCC. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-533/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-533/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9f2a6e5a92a8b6813f5c8d3606edc1bd4c22ecba --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-533/tests/oracle.patch @@ -0,0 +1,206 @@ +diff --git a/runtime/spu/spu_channels.c b/runtime/spu/spu_channels.c +index 59f5e4b8..4fdb4b42 100644 +--- a/runtime/spu/spu_channels.c ++++ b/runtime/spu/spu_channels.c +@@ -1552,12 +1552,12 @@ void spu_overlay_register_region(uint32_t content_ea, uint32_t span, int image_i + * Matching the resolved function, not just its LS address, avoids affecting + * unrelated overlays using the same address. Registration precedes execution. */ + static struct { uint32_t entry; int image_id; } s_stack_reset[16]; +-static unsigned s_stack_reset_count; ++unsigned g_spu_stack_reset_count; /* spu_drain.c skips the check at 0 */ + void spu_register_stack_reset_entry(uint32_t entry, int image_id) + { +- if (s_stack_reset_count < 16) { +- s_stack_reset[s_stack_reset_count].entry = entry & SPU_LS_MASK; +- s_stack_reset[s_stack_reset_count++].image_id = image_id; ++ if (g_spu_stack_reset_count < 16) { ++ s_stack_reset[g_spu_stack_reset_count].entry = entry & SPU_LS_MASK; ++ s_stack_reset[g_spu_stack_reset_count++].image_id = image_id; + } + } + +@@ -1565,8 +1565,8 @@ void spu_register_stack_reset_entry(uint32_t entry, int image_id) + * a stack-switching routine without going through spu_indirect_branch. */ + void spu_check_stack_reset(spu_context* ctx, void (*fn)(spu_context*)) + { +- if (!ctx->host_depth || !s_spu_halt_armed || ctx->policy_mode) return; +- for (unsigned i = 0; i < s_stack_reset_count; ++i) ++ if (!g_spu_stack_reset_count || !ctx->host_depth || !s_spu_halt_armed || ctx->policy_mode) return; ++ for (unsigned i = 0; i < g_spu_stack_reset_count; ++i) + if (ctx->pc == s_stack_reset[i].entry && + fn == spu_lookup(ctx->pc, s_stack_reset[i].image_id)) { + g_spu_trampoline_fn = 0; +diff --git a/runtime/spu/spu_context.h b/runtime/spu/spu_context.h +index f46d415f..e032f857 100644 +--- a/runtime/spu/spu_context.h ++++ b/runtime/spu/spu_context.h +@@ -783,6 +783,8 @@ extern SPU_THREAD_LOCAL unsigned g_spu_pch_n; + /* Central per-transfer hooks (stubbed in spu_drain.c until their milestones). */ + void yz_lockstep_tick(spu_context* ctx); /* round-robin token gate */ + void spu_task_launch_check(spu_context* ctx, void* fn); /* SPURS task-launch */ ++/* Both of the above for one trampoline hop, with the common case inline. */ ++void spu_drain_hop(spu_context* ctx, void (*fn)(spu_context*)); + /* Restore image_id after a call-bracket (adopt-on-serve); re-applies the + * persistent LS-0xA00 workload module if one is set. */ + void spu_img_restore(spu_context* ctx, int32_t saved_img); +@@ -872,8 +874,7 @@ static inline void spu_pchist_tick(const spu_context* ctx) + } \ + void (*_tf)(spu_context*) = g_spu_trampoline_fn; \ + g_spu_trampoline_fn = 0; \ +- yz_lockstep_tick(ctx); \ +- spu_task_launch_check((ctx), (void*)_tf); \ ++ spu_drain_hop((ctx), _tf); \ + if ((ctx)->int_enable && \ + ((ctx)->event_status & (ctx)->event_mask)) \ + _tf = spu_take_interrupt((ctx), _tf); \ +diff --git a/runtime/spu/spu_drain.c b/runtime/spu/spu_drain.c +index fc3cea12..0f4f0754 100644 +--- a/runtime/spu/spu_drain.c ++++ b/runtime/spu/spu_drain.c +@@ -6,6 +6,7 @@ + * functions (not macros) means the SPU_DRAIN/SPU_RET call sites are already in + * place -- later milestones only replace the bodies. */ + #include "spu_context.h" ++#include "spu_lockstep.h" + #include + + /* See spu_context.h `irq_frame`. */ +@@ -58,6 +59,14 @@ unsigned spu_recent_pcs(uint32_t* out, unsigned max) + return k; + } + ++static void spu_job_ls0_note(const spu_context* ctx) ++{ ++ static int _n = 0; ++ if (PS3_LOG_FIRST(_n, 8)) ++ fprintf(stderr, "[spurs-job] img=%d branched to LS 0 -- job complete\n", ++ ctx->image_id); ++} ++ + void spu_task_launch_check(spu_context* ctx, void* fn) + { + t_recent[t_recent_n++ & 31] = (uint32_t)ctx->pc & SPU_LS_MASK; +@@ -84,10 +93,7 @@ void spu_task_launch_check(spu_context* ctx, void* fn) + + if (!s_no_ls0 && ctx->steps++ && (ctx->pc & SPU_LS_MASK) == 0 && + !ctx->policy_mode && ctx->image_id > 0) { +- static int _n = 0; +- if (PS3_LOG_FIRST(_n, 8)) +- fprintf(stderr, "[spurs-job] img=%d branched to LS 0 -- job complete\n", +- ctx->image_id); ++ spu_job_ls0_note(ctx); + if (s_et >= 0 && ctx->image_id == s_et) { + fprintf(stderr, "[spu-exit] img=%d last PCs:", ctx->image_id); + for (int i = 32; i >= 1; i--) +@@ -334,24 +340,14 @@ void (*spu_take_interrupt(spu_context* ctx, + } + + /* See the declaration in spu_context.h. */ ++static uint32_t s_depth_max; /* SPU_HOST_DEPTH_MAX, 0 until read */ + void spu_depth_guard(spu_context* ctx) + { +- static uint32_t s_max = 0; +- if (!s_max) { ++ if (!s_depth_max) { + const char* e = getenv("SPU_HOST_DEPTH_MAX"); +- s_max = e ? (uint32_t)strtoul(e, 0, 0) : 2000u; ++ s_depth_max = e ? (uint32_t)strtoul(e, 0, 0) : 2000u; + } +- +- /* Ring of recent drain sites. When the depth trips, the useful question is +- * not "where are we" but "what cycle got us here" -- one pc names a point, +- * a ring names the loop. */ +- enum { RING = 24 }; +- static uint32_t s_ring[RING]; +- static uint32_t s_n; +- s_ring[s_n % RING] = ((uint32_t)ctx->pc & SPU_LS_MASK); +- s_n++; +- +- if (ctx->host_depth < s_max) return; ++ if (ctx->host_depth < s_depth_max) return; + static int s_reported = 0; + if (s_reported < 1) { /* one report: five SPU threads all trip together */ + s_reported++; +@@ -359,10 +355,14 @@ void spu_depth_guard(spu_context* ctx) + " -- lifted call recursion, halting the SPU\n", + ctx->image_id, (uint32_t)ctx->pc & SPU_LS_MASK, + ctx->gpr[0]._u32[0] & SPU_LS_MASK, ctx->host_depth); +- fprintf(stderr, "[spu-depth] recent drain sites (oldest first):"); +- uint32_t start = (s_n > RING) ? (s_n - RING) : 0; +- for (uint32_t k = start; k < s_n; k++) +- fprintf(stderr, " %05X", s_ring[k % RING]); ++ /* When the depth trips, the useful question is not "where are we" ++ * but "what cycle got us here" -- one pc names a point, a ring names ++ * the loop. The hop ring is this thread's own. */ ++ uint32_t r[32]; ++ const unsigned n = spu_recent_pcs(r, 32); ++ fprintf(stderr, "[spu-depth] recent hops (oldest first):"); ++ for (unsigned k = 0; k < n; k++) ++ fprintf(stderr, " %05X", r[k]); + fprintf(stderr, "\n"); + fflush(stderr); + } +@@ -396,9 +396,52 @@ int spu_tailret_enabled(void) + typedef void (*spu_drain_fn)(spu_context*); + extern spu_drain_fn spu_lookup(uint32_t addr, int image_id); + ++/* The hooks every trampoline hop runs, with their common case inline. Each ++ * SPU thread takes millions of hops a second, and per hop they were three ++ * calls into two files that nearly always returned at once: about a fifth of ++ * an SPU thread's time in God of War HD gameplay. The full checks still run ++ * when one of their switches is set, and the lockstep and stack-reset hooks ++ * whenever those are in use. */ ++static int s_hop_full = -1; /* a switch spu_task_launch_check reads is set */ ++static __attribute__((noinline)) int spu_hop_full_read(void) ++{ ++ s_hop_full = (getenv("SPU_NO_LS0_END") || getenv("SPU_EXITTRACE") || ++ getenv("SPU_STEPTRACE") || getenv("SPU_JOBDRAIN")) ? 1 : 0; ++ return s_hop_full; ++} ++ ++static inline void spu_hop(spu_context* ctx, void (*fn)(spu_context*)) ++{ ++ extern unsigned g_spu_stack_reset_count; /* spu_channels.c */ ++ extern void spu_check_stack_reset(spu_context*, void (*)(spu_context*)); ++ if (g_yz_lockstep_on != 0) yz_lockstep_tick(ctx); ++ if (__builtin_expect(s_hop_full != 0, 0) && (s_hop_full > 0 || spu_hop_full_read())) { ++ spu_task_launch_check(ctx, (void*)fn); ++ return; ++ } ++ /* What spu_task_launch_check does with every switch off. */ ++ const uint32_t pc = (uint32_t)ctx->pc & SPU_LS_MASK; ++ t_recent[t_recent_n++ & 31] = pc; ++ if (g_spu_stack_reset_count) ++ spu_check_stack_reset(ctx, fn); ++ if (ctx->steps++ && pc == 0 && !ctx->policy_mode && ctx->image_id > 0) { ++ spu_job_ls0_note(ctx); ++ spu_halt(ctx); ++ return; ++ } ++ if (g_pm_flow_ctx == (void*)ctx && g_pm_flow_n < 8192) ++ g_pm_flow_buf[g_pm_flow_n++] = ctx->pc; ++} ++ ++void spu_drain_hop(spu_context* ctx, void (*fn)(spu_context*)) ++{ ++ spu_hop(ctx, fn); ++} ++ + void spu_drain_call(spu_context* ctx, uint32_t return_pc) + { +- spu_depth_guard(ctx); ++ if (__builtin_expect(ctx->host_depth >= s_depth_max, 0)) ++ spu_depth_guard(ctx); + /* The frame an interrupt taken in THIS loop returns to. It stays armed + * after the handler's first host function returns -- the handler keeps + * running as trampolines of this loop -- until its iret fires or the +@@ -417,8 +460,7 @@ void spu_drain_call(spu_context* ctx, uint32_t return_pc) + void (*fn)(spu_context*) = g_spu_trampoline_fn; + g_spu_trampoline_fn = 0; + ctx->drain_ret_pc = return_pc & SPU_LS_MASK; /* re-set: a nested drain changed it */ +- yz_lockstep_tick(ctx); +- spu_task_launch_check(ctx, (void*)fn); ++ spu_hop(ctx, fn); + if (ctx->int_enable && (ctx->event_status & ctx->event_mask)) { + void (*vf)(spu_context*) = spu_take_interrupt(ctx, fn); + if (!ctx->int_enable) { /* taken (a take clears the enable; a deferral leaves it) */ diff --git a/tasks/sp00nznet__ps3recomp-533/tests/test.sh b/tasks/sp00nznet__ps3recomp-533/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-533/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-533/tests/verifier.py b/tasks/sp00nznet__ps3recomp-533/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-533/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-534/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-534/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e58bcfa58777d72bba591f37e690838b686d5be --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-534/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-534/instruction.md b/tasks/sp00nznet__ps3recomp-534/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f3500b0e0fb71eb55ff95d56636a293c069882fc --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-534/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** ppu: test the SPU reserved-line bitmap inline on guest stores + +## Description + +## Why + +Every guest store calls `spu_coh_is_reserved`. In God of War HD (NPUA80490) gameplay that call was 9.5% of the main PPU thread's samples. + +Testing the bitmap inline only moved the cost into `vm_write32` and `vm_write64`. Sampling by instruction showed where it actually went: + +- With the test inline (the armed flag as a pointer to the bitmap), the hottest instruction in `vm_write32` was the one right after loading that pointer: 68 of about 200 samples in the function. +- The next hottest was right after the load of the bitmap byte. + +The cause is `spu_coh_reserve`. On every GETLLAR it stored `s_coh_armed = 1` and or-ed the line's bit into the bitmap, the same values each time. The SPURS kernel reserves the same few lines over and over. So those cache lines kept moving to the SPU threads' cores, and the next PPU store missed on them. + +## Change + +- `spu_coh_reserve` writes the line's bit, and the armed state, only when they change. +- `runtime/spu/spu_coh_bitmap.h` publishes the bitmap as `g_spu_coh_bits`. It stays NULL until the first reservation, which replaces `s_coh_armed`. +- `spu_coh_line_reserved` tests the bitmap inline. It is used by: + - `VM_WRITE_COH` in `ppu_loader.cpp` and in `ppu_memory.h`; + - `vm_block_reserved`. +- `spu_coh_is_reserved` keeps its signature and calls the same test. +- `g_spu_coh_bits` has one merged definition per program (selectany / weak). The loader fixtures link `ppu_loader.cpp` without `spu_coherency.c`, so they still link and see no reserved lines. + +## Evidence + +All numbers are from God of War HD gameplay. + +- **Profile:** the pointer load fell to 6 samples. `vm_write32` plus `vm_write64` went from 23.4% of the main thread (with the call) to 18.3%. +- **Frame:** the main thread's running time per frame went from 17.2 to 16.3 ms (`PS3_FTRACE`). +- **Tests:** `PS3RECOMP_BUILD_TESTS=ON` passes 16/16. +- **Loader fixtures on Linux (g++):** `test_loaded_image_memory`, `test_loader_memory_domain`, `test_ppu_dispatch_depth`, `test_ppu_entry_arguments` and `test_ppu_tls_blocks` pass. These are the fixtures that need the weak definition. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-534/solution/patch.diff b/tasks/sp00nznet__ps3recomp-534/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2671375747baaab586eb3a756a6fb59a14d5fe26 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-534/solution/patch.diff @@ -0,0 +1,196 @@ +diff --git a/runtime/ppu/ppu_loader.cpp b/runtime/ppu/ppu_loader.cpp +index f54150d9..353ec85a 100644 +--- a/runtime/ppu/ppu_loader.cpp ++++ b/runtime/ppu/ppu_loader.cpp +@@ -34,6 +34,7 @@ + #include "ppu_tls.h" /* PPU_THREAD_LOCAL, without a second ppu_context */ + #define PPU_NO_INLINE_LOADS /* this file defines the out-of-line accessors */ + #include "ppu_recomp.h" ++#include "../spu/spu_coh_bitmap.h" /* spu_coh_line_reserved, for the stores */ + #include "ps3emu/ps3_ftrace.h" /* PS3_FTRACE timeline */ + #include "ps3emu/milestone.h" /* ps3_ms / ps3_msf -- boot milestone log */ /* ppu_context, func decls, ppu_recomp_register */ + #include "../memory/vm.h" /* vm_commit -- sys_mmapper_search_and_map maps for real */ +@@ -767,8 +768,9 @@ extern "C" void ppu_log_host_chain(const char* tag); /* fwd decl (defined below + * to serialize through the SPU lock-line lock, or it can land inside a PUTLLC's + * compare and be written straight back over; and it has to raise SPU_EVENT_LR, + * which is how an SPURS idle service parked in `rdch SPU_RdEventStat` finds out +- * work was posted. spu_coh_is_reserved reads a global that stays zero until an +- * SPU reserves its first line, so an ordinary store pays one branch. */ ++ * work was posted. The stores test the bitmap inline (spu_coh_line_reserved): ++ * a pointer that stays NULL until an SPU reserves its first line, so an ++ * ordinary store pays one branch. */ + extern "C" int spu_coh_is_reserved(uint32_t addr); + extern "C" void spu_lockline_lock(void); + extern "C" void spu_lockline_unlock(void); +@@ -1473,7 +1475,7 @@ extern "C" int* ps3_ppu_vcall_sp_slot(void) { return &g_vcall_sp; } + * them, until SPU code runs) it is the plain memcpy it replaced. */ + #define VM_WRITE_COH(a, src, n) \ + do { \ +- if (spu_coh_is_reserved((uint32_t)(a))) { \ ++ if (spu_coh_line_reserved((uint32_t)(a))) { \ + spu_lockline_lock(); \ + memcpy(vm_base + (uint32_t)(a), (src), (n)); \ + spu_coh_notify_write((uint32_t)(a)); \ +diff --git a/runtime/ppu/ppu_memory.h b/runtime/ppu/ppu_memory.h +index b3bc534d..97a9d17f 100644 +--- a/runtime/ppu/ppu_memory.h ++++ b/runtime/ppu/ppu_memory.h +@@ -13,6 +13,7 @@ + + #include "../../include/ps3emu/endian.h" + #include "ppu_context.h" ++#include "../spu/spu_coh_bitmap.h" + + #include + #include +@@ -129,8 +130,9 @@ void ppu_resv_break_store(uint64_t ea); + * SPURS idle service parked in `rdch SPU_RdEventStat` learns work was posted. + * Declared here rather than pulling spu_coherency.h into every HLE module. + * +- * spu_coh_is_reserved is a load of a global that stays zero until an SPU +- * reserves its first line, so the ordinary store pays one predictable branch. */ ++ * The stores test the bitmap inline (spu_coh_bitmap.h): a pointer that stays ++ * NULL until an SPU reserves its first line, so the ordinary store pays one ++ * predictable branch. */ + int spu_coh_is_reserved(uint32_t addr); + void spu_lockline_lock(void); + void spu_lockline_unlock(void); +@@ -141,7 +143,7 @@ void spu_coh_notify_write(uint32_t addr); + + #define VM_WRITE_COH(addr, src, n) \ + do { \ +- if (spu_coh_is_reserved((uint32_t)(addr))) { \ ++ if (spu_coh_line_reserved((uint32_t)(addr))) { \ + spu_lockline_lock(); \ + memcpy(vm_ptr8((uint32_t)(addr)), (src), (n)); \ + spu_coh_notify_write((uint32_t)(addr)); \ +@@ -236,7 +238,7 @@ static inline int vm_block_reserved(uint32_t guest_dst, size_t len) + uint32_t first = guest_dst & ~127u; + uint32_t last = (uint32_t)(guest_dst + (len - 1)) & ~127u; + for (uint32_t line = first; ; line += 128u) { +- if (spu_coh_is_reserved(line)) return 1; ++ if (spu_coh_line_reserved(line)) return 1; + if (line == last) break; + } + return 0; +diff --git a/runtime/spu/spu_coh_bitmap.h b/runtime/spu/spu_coh_bitmap.h +new file mode 100644 +index 00000000..79bffe73 +--- /dev/null ++++ b/runtime/spu/spu_coh_bitmap.h +@@ -0,0 +1,48 @@ ++/* ++ * ps3recomp - the SPU reserved-line bitmap, for inline store paths ++ * ++ * Every guest store asks whether an SPU has reserved its 128-byte line ++ * (spu_coherency.h). The PPU store paths test the bitmap here, inline, rather ++ * than through a call into spu_coherency.c. ++ * ++ * g_spu_coh_bits is NULL until an SPU reserves its first line, so a title that ++ * runs no SPU code pays one load and branch per store. It is one merged ++ * definition per program (selectany / weak): a target that links the store ++ * paths without spu_coherency.c, such as the PPU loader fixtures, sees NULL ++ * and never a reserved line. ++ */ ++ ++#ifndef SPU_COH_BITMAP_H ++#define SPU_COH_BITMAP_H ++ ++#include ++ ++#if defined(_MSC_VER) ++# define SPU_COH_SHARED __declspec(selectany) ++#else ++# define SPU_COH_SHARED __attribute__((weak)) ++#endif ++ ++#ifdef __cplusplus ++extern "C" { ++#endif ++ ++#define SPU_COH_LINE_SHIFT 7 /* 128-byte lines */ ++ ++/* One bit per line over the 32-bit guest address space; spu_coherency.c ++ * publishes it on the first reservation and only ever sets bits. */ ++SPU_COH_SHARED const unsigned char* g_spu_coh_bits = 0; ++ ++static inline int spu_coh_line_reserved(uint32_t addr) ++{ ++ const unsigned char* bits = g_spu_coh_bits; ++ if (!bits) return 0; ++ const uint32_t line = addr >> SPU_COH_LINE_SHIFT; ++ return (bits[line >> 3] >> (line & 7)) & 1; ++} ++ ++#ifdef __cplusplus ++} ++#endif ++ ++#endif /* SPU_COH_BITMAP_H */ +diff --git a/runtime/spu/spu_coherency.c b/runtime/spu/spu_coherency.c +index bc7017da..aee21cf7 100644 +--- a/runtime/spu/spu_coherency.c ++++ b/runtime/spu/spu_coherency.c +@@ -12,6 +12,7 @@ + + #include + #include "spu_coherency.h" ++#include "spu_coh_bitmap.h" + + #include + #include +@@ -69,18 +70,17 @@ void spu_lockline_unlock(void) { atomic_flag_clear_explicit(&g_lockline, memory_ + * line outside a hardcoded window would be silently non-coherent, which is the + * failure this whole file exists to remove. + * ===========================================================================*/ +-#define SPU_COH_LINE_SHIFT 7 /* 128-byte lines */ + #define SPU_COH_LINES (1u << (32 - SPU_COH_LINE_SHIFT)) /* 2^25 lines */ + #define SPU_COH_BITMAP_SZ (SPU_COH_LINES / 8) /* 4 MiB */ + + static unsigned char s_coh_bitmap[SPU_COH_BITMAP_SZ]; + +-/* Zero until the first GETLLAR anywhere. Keeps the PPU fast path off the +- * bitmap entirely for a title that runs no SPU code, and keeps every existing +- * test that stores through vm_write* paying one compare against a hot global. +- * Written once, under the lock; read unlocked, where a stale zero costs at most +- * one missed event on the very first reservation of the run. */ +-static int s_coh_armed; ++/* g_spu_coh_bits (spu_coh_bitmap.h) stays NULL until the first GETLLAR ++ * anywhere. That keeps the PPU fast path off the bitmap entirely for a title ++ * that runs no SPU code, and keeps every existing test that stores through ++ * vm_write* paying one compare against a hot global. Written under the lock; ++ * read unlocked, where a stale NULL costs at most one missed event on the very ++ * first reservation of the run. */ + + /* Every live virtual context may retain a reservation between scheduling + * quanta; physical SPU count is not a bound on this set. All access is under +@@ -95,9 +95,16 @@ unsigned long g_spu_lr_raise = 0; + + void spu_coh_reserve(spu_context* ctx, uint32_t ea) + { ++ /* Read before writing. The kernel reserves the same few lines over and ++ * over, and a store of the same value still takes the cache line away ++ * from every other core: each PPU store then missed on the pointer and on ++ * the bitmap byte. */ + uint32_t line = ea >> SPU_COH_LINE_SHIFT; +- s_coh_bitmap[line >> 3] |= (unsigned char)(1u << (line & 7)); +- s_coh_armed = 1; ++ const unsigned char bit = (unsigned char)(1u << (line & 7)); ++ if (!(s_coh_bitmap[line >> 3] & bit)) ++ s_coh_bitmap[line >> 3] |= bit; ++ if (!g_spu_coh_bits) ++ g_spu_coh_bits = s_coh_bitmap; + + if (!ctx) return; + for (spu_coh_entry* entry = s_coh_ctxs; entry; entry = entry->next) +@@ -170,9 +177,7 @@ void spu_coh_forget_range(uintptr_t lo, uintptr_t hi) + + int spu_coh_is_reserved(uint32_t addr) + { +- if (!s_coh_armed) return 0; +- uint32_t line = addr >> SPU_COH_LINE_SHIFT; +- return (s_coh_bitmap[line >> 3] >> (line & 7)) & 1u; ++ return spu_coh_line_reserved(addr); + } + + /* A DMA PUT is issued BY an SPU, and hardware does not take that SPU's own diff --git a/tasks/sp00nznet__ps3recomp-534/solution/solve.sh b/tasks/sp00nznet__ps3recomp-534/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-534/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-534/task.toml b/tasks/sp00nznet__ps3recomp-534/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6ef3121d047ba7835db973a910b9708868bb0ffc --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-534/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-534" +description = "ppu: test the SPU reserved-line bitmap inline on guest stores" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "a6d76c895f77eb30b90a806c830544e61821b77f" +reference = "https://github.com/sp00nznet/ps3recomp/pull/534" +source_access = "auto" +built_at = "2026-11-16T16:09:59.931510+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7edcf79cecf4ab42674719ba2df4131efa6f373d8d47260bb7c7ad3f980cc8fb" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-26T15:32:55Z" +diff_format = "unified" +context_files = [ + "runtime/ppu/ppu_loader.cpp", + "runtime/ppu/ppu_memory.h", + "runtime/spu/spu_coh_bitmap.h", + "runtime/spu/spu_coherency.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 95 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.120209+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-534/tests/capture.py b/tasks/sp00nznet__ps3recomp-534/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-534/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-534/tests/instruction.md b/tasks/sp00nznet__ps3recomp-534/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f3500b0e0fb71eb55ff95d56636a293c069882fc --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-534/tests/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** ppu: test the SPU reserved-line bitmap inline on guest stores + +## Description + +## Why + +Every guest store calls `spu_coh_is_reserved`. In God of War HD (NPUA80490) gameplay that call was 9.5% of the main PPU thread's samples. + +Testing the bitmap inline only moved the cost into `vm_write32` and `vm_write64`. Sampling by instruction showed where it actually went: + +- With the test inline (the armed flag as a pointer to the bitmap), the hottest instruction in `vm_write32` was the one right after loading that pointer: 68 of about 200 samples in the function. +- The next hottest was right after the load of the bitmap byte. + +The cause is `spu_coh_reserve`. On every GETLLAR it stored `s_coh_armed = 1` and or-ed the line's bit into the bitmap, the same values each time. The SPURS kernel reserves the same few lines over and over. So those cache lines kept moving to the SPU threads' cores, and the next PPU store missed on them. + +## Change + +- `spu_coh_reserve` writes the line's bit, and the armed state, only when they change. +- `runtime/spu/spu_coh_bitmap.h` publishes the bitmap as `g_spu_coh_bits`. It stays NULL until the first reservation, which replaces `s_coh_armed`. +- `spu_coh_line_reserved` tests the bitmap inline. It is used by: + - `VM_WRITE_COH` in `ppu_loader.cpp` and in `ppu_memory.h`; + - `vm_block_reserved`. +- `spu_coh_is_reserved` keeps its signature and calls the same test. +- `g_spu_coh_bits` has one merged definition per program (selectany / weak). The loader fixtures link `ppu_loader.cpp` without `spu_coherency.c`, so they still link and see no reserved lines. + +## Evidence + +All numbers are from God of War HD gameplay. + +- **Profile:** the pointer load fell to 6 samples. `vm_write32` plus `vm_write64` went from 23.4% of the main thread (with the call) to 18.3%. +- **Frame:** the main thread's running time per frame went from 17.2 to 16.3 ms (`PS3_FTRACE`). +- **Tests:** `PS3RECOMP_BUILD_TESTS=ON` passes 16/16. +- **Loader fixtures on Linux (g++):** `test_loaded_image_memory`, `test_loader_memory_domain`, `test_ppu_dispatch_depth`, `test_ppu_entry_arguments` and `test_ppu_tls_blocks` pass. These are the fixtures that need the weak definition. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-534/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-534/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2671375747baaab586eb3a756a6fb59a14d5fe26 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-534/tests/oracle.patch @@ -0,0 +1,196 @@ +diff --git a/runtime/ppu/ppu_loader.cpp b/runtime/ppu/ppu_loader.cpp +index f54150d9..353ec85a 100644 +--- a/runtime/ppu/ppu_loader.cpp ++++ b/runtime/ppu/ppu_loader.cpp +@@ -34,6 +34,7 @@ + #include "ppu_tls.h" /* PPU_THREAD_LOCAL, without a second ppu_context */ + #define PPU_NO_INLINE_LOADS /* this file defines the out-of-line accessors */ + #include "ppu_recomp.h" ++#include "../spu/spu_coh_bitmap.h" /* spu_coh_line_reserved, for the stores */ + #include "ps3emu/ps3_ftrace.h" /* PS3_FTRACE timeline */ + #include "ps3emu/milestone.h" /* ps3_ms / ps3_msf -- boot milestone log */ /* ppu_context, func decls, ppu_recomp_register */ + #include "../memory/vm.h" /* vm_commit -- sys_mmapper_search_and_map maps for real */ +@@ -767,8 +768,9 @@ extern "C" void ppu_log_host_chain(const char* tag); /* fwd decl (defined below + * to serialize through the SPU lock-line lock, or it can land inside a PUTLLC's + * compare and be written straight back over; and it has to raise SPU_EVENT_LR, + * which is how an SPURS idle service parked in `rdch SPU_RdEventStat` finds out +- * work was posted. spu_coh_is_reserved reads a global that stays zero until an +- * SPU reserves its first line, so an ordinary store pays one branch. */ ++ * work was posted. The stores test the bitmap inline (spu_coh_line_reserved): ++ * a pointer that stays NULL until an SPU reserves its first line, so an ++ * ordinary store pays one branch. */ + extern "C" int spu_coh_is_reserved(uint32_t addr); + extern "C" void spu_lockline_lock(void); + extern "C" void spu_lockline_unlock(void); +@@ -1473,7 +1475,7 @@ extern "C" int* ps3_ppu_vcall_sp_slot(void) { return &g_vcall_sp; } + * them, until SPU code runs) it is the plain memcpy it replaced. */ + #define VM_WRITE_COH(a, src, n) \ + do { \ +- if (spu_coh_is_reserved((uint32_t)(a))) { \ ++ if (spu_coh_line_reserved((uint32_t)(a))) { \ + spu_lockline_lock(); \ + memcpy(vm_base + (uint32_t)(a), (src), (n)); \ + spu_coh_notify_write((uint32_t)(a)); \ +diff --git a/runtime/ppu/ppu_memory.h b/runtime/ppu/ppu_memory.h +index b3bc534d..97a9d17f 100644 +--- a/runtime/ppu/ppu_memory.h ++++ b/runtime/ppu/ppu_memory.h +@@ -13,6 +13,7 @@ + + #include "../../include/ps3emu/endian.h" + #include "ppu_context.h" ++#include "../spu/spu_coh_bitmap.h" + + #include + #include +@@ -129,8 +130,9 @@ void ppu_resv_break_store(uint64_t ea); + * SPURS idle service parked in `rdch SPU_RdEventStat` learns work was posted. + * Declared here rather than pulling spu_coherency.h into every HLE module. + * +- * spu_coh_is_reserved is a load of a global that stays zero until an SPU +- * reserves its first line, so the ordinary store pays one predictable branch. */ ++ * The stores test the bitmap inline (spu_coh_bitmap.h): a pointer that stays ++ * NULL until an SPU reserves its first line, so the ordinary store pays one ++ * predictable branch. */ + int spu_coh_is_reserved(uint32_t addr); + void spu_lockline_lock(void); + void spu_lockline_unlock(void); +@@ -141,7 +143,7 @@ void spu_coh_notify_write(uint32_t addr); + + #define VM_WRITE_COH(addr, src, n) \ + do { \ +- if (spu_coh_is_reserved((uint32_t)(addr))) { \ ++ if (spu_coh_line_reserved((uint32_t)(addr))) { \ + spu_lockline_lock(); \ + memcpy(vm_ptr8((uint32_t)(addr)), (src), (n)); \ + spu_coh_notify_write((uint32_t)(addr)); \ +@@ -236,7 +238,7 @@ static inline int vm_block_reserved(uint32_t guest_dst, size_t len) + uint32_t first = guest_dst & ~127u; + uint32_t last = (uint32_t)(guest_dst + (len - 1)) & ~127u; + for (uint32_t line = first; ; line += 128u) { +- if (spu_coh_is_reserved(line)) return 1; ++ if (spu_coh_line_reserved(line)) return 1; + if (line == last) break; + } + return 0; +diff --git a/runtime/spu/spu_coh_bitmap.h b/runtime/spu/spu_coh_bitmap.h +new file mode 100644 +index 00000000..79bffe73 +--- /dev/null ++++ b/runtime/spu/spu_coh_bitmap.h +@@ -0,0 +1,48 @@ ++/* ++ * ps3recomp - the SPU reserved-line bitmap, for inline store paths ++ * ++ * Every guest store asks whether an SPU has reserved its 128-byte line ++ * (spu_coherency.h). The PPU store paths test the bitmap here, inline, rather ++ * than through a call into spu_coherency.c. ++ * ++ * g_spu_coh_bits is NULL until an SPU reserves its first line, so a title that ++ * runs no SPU code pays one load and branch per store. It is one merged ++ * definition per program (selectany / weak): a target that links the store ++ * paths without spu_coherency.c, such as the PPU loader fixtures, sees NULL ++ * and never a reserved line. ++ */ ++ ++#ifndef SPU_COH_BITMAP_H ++#define SPU_COH_BITMAP_H ++ ++#include ++ ++#if defined(_MSC_VER) ++# define SPU_COH_SHARED __declspec(selectany) ++#else ++# define SPU_COH_SHARED __attribute__((weak)) ++#endif ++ ++#ifdef __cplusplus ++extern "C" { ++#endif ++ ++#define SPU_COH_LINE_SHIFT 7 /* 128-byte lines */ ++ ++/* One bit per line over the 32-bit guest address space; spu_coherency.c ++ * publishes it on the first reservation and only ever sets bits. */ ++SPU_COH_SHARED const unsigned char* g_spu_coh_bits = 0; ++ ++static inline int spu_coh_line_reserved(uint32_t addr) ++{ ++ const unsigned char* bits = g_spu_coh_bits; ++ if (!bits) return 0; ++ const uint32_t line = addr >> SPU_COH_LINE_SHIFT; ++ return (bits[line >> 3] >> (line & 7)) & 1; ++} ++ ++#ifdef __cplusplus ++} ++#endif ++ ++#endif /* SPU_COH_BITMAP_H */ +diff --git a/runtime/spu/spu_coherency.c b/runtime/spu/spu_coherency.c +index bc7017da..aee21cf7 100644 +--- a/runtime/spu/spu_coherency.c ++++ b/runtime/spu/spu_coherency.c +@@ -12,6 +12,7 @@ + + #include + #include "spu_coherency.h" ++#include "spu_coh_bitmap.h" + + #include + #include +@@ -69,18 +70,17 @@ void spu_lockline_unlock(void) { atomic_flag_clear_explicit(&g_lockline, memory_ + * line outside a hardcoded window would be silently non-coherent, which is the + * failure this whole file exists to remove. + * ===========================================================================*/ +-#define SPU_COH_LINE_SHIFT 7 /* 128-byte lines */ + #define SPU_COH_LINES (1u << (32 - SPU_COH_LINE_SHIFT)) /* 2^25 lines */ + #define SPU_COH_BITMAP_SZ (SPU_COH_LINES / 8) /* 4 MiB */ + + static unsigned char s_coh_bitmap[SPU_COH_BITMAP_SZ]; + +-/* Zero until the first GETLLAR anywhere. Keeps the PPU fast path off the +- * bitmap entirely for a title that runs no SPU code, and keeps every existing +- * test that stores through vm_write* paying one compare against a hot global. +- * Written once, under the lock; read unlocked, where a stale zero costs at most +- * one missed event on the very first reservation of the run. */ +-static int s_coh_armed; ++/* g_spu_coh_bits (spu_coh_bitmap.h) stays NULL until the first GETLLAR ++ * anywhere. That keeps the PPU fast path off the bitmap entirely for a title ++ * that runs no SPU code, and keeps every existing test that stores through ++ * vm_write* paying one compare against a hot global. Written under the lock; ++ * read unlocked, where a stale NULL costs at most one missed event on the very ++ * first reservation of the run. */ + + /* Every live virtual context may retain a reservation between scheduling + * quanta; physical SPU count is not a bound on this set. All access is under +@@ -95,9 +95,16 @@ unsigned long g_spu_lr_raise = 0; + + void spu_coh_reserve(spu_context* ctx, uint32_t ea) + { ++ /* Read before writing. The kernel reserves the same few lines over and ++ * over, and a store of the same value still takes the cache line away ++ * from every other core: each PPU store then missed on the pointer and on ++ * the bitmap byte. */ + uint32_t line = ea >> SPU_COH_LINE_SHIFT; +- s_coh_bitmap[line >> 3] |= (unsigned char)(1u << (line & 7)); +- s_coh_armed = 1; ++ const unsigned char bit = (unsigned char)(1u << (line & 7)); ++ if (!(s_coh_bitmap[line >> 3] & bit)) ++ s_coh_bitmap[line >> 3] |= bit; ++ if (!g_spu_coh_bits) ++ g_spu_coh_bits = s_coh_bitmap; + + if (!ctx) return; + for (spu_coh_entry* entry = s_coh_ctxs; entry; entry = entry->next) +@@ -170,9 +177,7 @@ void spu_coh_forget_range(uintptr_t lo, uintptr_t hi) + + int spu_coh_is_reserved(uint32_t addr) + { +- if (!s_coh_armed) return 0; +- uint32_t line = addr >> SPU_COH_LINE_SHIFT; +- return (s_coh_bitmap[line >> 3] >> (line & 7)) & 1u; ++ return spu_coh_line_reserved(addr); + } + + /* A DMA PUT is issued BY an SPU, and hardware does not take that SPU's own diff --git a/tasks/sp00nznet__ps3recomp-534/tests/test.sh b/tasks/sp00nznet__ps3recomp-534/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-534/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-534/tests/verifier.py b/tasks/sp00nznet__ps3recomp-534/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-534/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-535/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-535/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e58bcfa58777d72bba591f37e690838b686d5be --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-535/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-535/instruction.md b/tasks/sp00nznet__ps3recomp-535/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..258682fedd04857ebd4fa4ca20884d1efd9dd91f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-535/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Add CITATION.cff + +## Description + +## Why + +GitHub shows a "Cite this repository" button for a repository with a `CITATION.cff` file in its root, and Zenodo and reference managers read the same file. Projects built on ps3recomp can then cite it with the right name, URL, licence and version. + +## Change + +One new file, `CITATION.cff` (Citation File Format 1.2.0): title `ps3recomp`, type software, author `sp00nznet`, repository URL, MIT licence, version 0.17.0 released 2026-10-21 (the `v0.17.0` tag), a one-line abstract from the README and a few keywords. No other file changes. + +You may want to add your name, an ORCID, or a different author list, or update `version` and `date-released` with each release. Those are your call; I kept the author as the GitHub handle only. + +## Tests + +- `cffconvert --validate` (cffconvert 2.0.0): "Citation metadata are valid according to schema version 1.2.0." Run. +- GitHub's "Cite this repository" rendering: not run (it only shows on the default branch). + +## Evidence + +None beyond the schema check; the file adds no code and changes no build. + +## Overlap + +No open PR or issue mentions `CITATION.cff` as of this draft. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-535/solution/patch.diff b/tasks/sp00nznet__ps3recomp-535/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..116d4942026643af9324e7f039915444f7268b8a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-535/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CITATION.cff b/CITATION.cff +new file mode 100644 +index 00000000..603b0a3e +--- /dev/null ++++ b/CITATION.cff +@@ -0,0 +1,19 @@ ++cff-version: 1.2.0 ++message: "If you use this software, please cite it as below." ++title: "ps3recomp" ++type: software ++authors: ++ - alias: sp00nznet ++repository-code: "https://github.com/sp00nznet/ps3recomp" ++url: "https://github.com/sp00nznet/ps3recomp" ++license: MIT ++version: "0.17.0" ++date-released: "2026-10-21" ++abstract: >- ++ Static recompilation runtime libraries for PlayStation 3 titles: turns PS3 ++ binaries into native executables, with no emulator required. ++keywords: ++ - static recompilation ++ - PS3 ++ - PlayStation 3 ++ - game preservation diff --git a/tasks/sp00nznet__ps3recomp-535/solution/solve.sh b/tasks/sp00nznet__ps3recomp-535/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-535/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-535/task.toml b/tasks/sp00nznet__ps3recomp-535/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c530422033c6f3c369b2f5a24c61d7a2aa94e74c --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-535/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-535" +description = "Add CITATION.cff" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "a6d76c895f77eb30b90a806c830544e61821b77f" +reference = "https://github.com/sp00nznet/ps3recomp/pull/535" +source_access = "auto" +built_at = "2026-11-16T16:09:59.825107+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5fbed3cff1a934ae5bf28507f44392d84954ed6a60fa3e3e62235f54a917b139" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-26T15:32:54Z" +diff_format = "unified" +context_files = [ + "CITATION.cff", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 19 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.120708+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-535/tests/capture.py b/tasks/sp00nznet__ps3recomp-535/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-535/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-535/tests/instruction.md b/tasks/sp00nznet__ps3recomp-535/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..258682fedd04857ebd4fa4ca20884d1efd9dd91f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-535/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Add CITATION.cff + +## Description + +## Why + +GitHub shows a "Cite this repository" button for a repository with a `CITATION.cff` file in its root, and Zenodo and reference managers read the same file. Projects built on ps3recomp can then cite it with the right name, URL, licence and version. + +## Change + +One new file, `CITATION.cff` (Citation File Format 1.2.0): title `ps3recomp`, type software, author `sp00nznet`, repository URL, MIT licence, version 0.17.0 released 2026-10-21 (the `v0.17.0` tag), a one-line abstract from the README and a few keywords. No other file changes. + +You may want to add your name, an ORCID, or a different author list, or update `version` and `date-released` with each release. Those are your call; I kept the author as the GitHub handle only. + +## Tests + +- `cffconvert --validate` (cffconvert 2.0.0): "Citation metadata are valid according to schema version 1.2.0." Run. +- GitHub's "Cite this repository" rendering: not run (it only shows on the default branch). + +## Evidence + +None beyond the schema check; the file adds no code and changes no build. + +## Overlap + +No open PR or issue mentions `CITATION.cff` as of this draft. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-535/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-535/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..116d4942026643af9324e7f039915444f7268b8a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-535/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CITATION.cff b/CITATION.cff +new file mode 100644 +index 00000000..603b0a3e +--- /dev/null ++++ b/CITATION.cff +@@ -0,0 +1,19 @@ ++cff-version: 1.2.0 ++message: "If you use this software, please cite it as below." ++title: "ps3recomp" ++type: software ++authors: ++ - alias: sp00nznet ++repository-code: "https://github.com/sp00nznet/ps3recomp" ++url: "https://github.com/sp00nznet/ps3recomp" ++license: MIT ++version: "0.17.0" ++date-released: "2026-10-21" ++abstract: >- ++ Static recompilation runtime libraries for PlayStation 3 titles: turns PS3 ++ binaries into native executables, with no emulator required. ++keywords: ++ - static recompilation ++ - PS3 ++ - PlayStation 3 ++ - game preservation diff --git a/tasks/sp00nznet__ps3recomp-535/tests/test.sh b/tasks/sp00nznet__ps3recomp-535/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-535/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-535/tests/verifier.py b/tasks/sp00nznet__ps3recomp-535/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-535/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-566/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-566/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e58bcfa58777d72bba591f37e690838b686d5be --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-566/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-566/instruction.md b/tasks/sp00nznet__ps3recomp-566/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b0f3e1e73ee3dc9f0948612505469eb90c374be6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-566/instruction.md @@ -0,0 +1,45 @@ +# Issue + +**Title:** cellGcmSys: GCM_FIFO_SEGMENT hands the command ring out in segments + +## Description + +## Why + +`cellGcmSetupContext` gives the title its whole command ring as one context: `end` is the end of the ring. So: + +- the buffer-full callback runs only when the ring wraps; +- `put` moves only when the title flushes. + +libgcm hands the ring out a segment at a time. RPCS3's `_cellGcmInitBody` sets `end = begin + 32 * 1024 - 4`, and its `cellGcmCallback` publishes `put` at every segment. On hardware the RSX therefore starts on a frame while the title is still writing it. + +God of War HD (NPUA80490) writes about 1.2 MB of commands per frame and flushes twice a frame, the second time at its flip. With the whole ring as one segment, the frame reached the walker in one go, and the title and the walker took turns. + +## Change + +`GCM_FIFO_SEGMENT=` (at least 4 KB, 4 KB aligned, and at most half the ring) hands the runtime's ring out in segments of that size. Unset, nothing changes. + +- **The context.** `end` is the end of the current segment, less 4 bytes for the closing JUMP. +- **The buffer-full callback on that ring** (`gcm_fifo_next_segment`) works like RPCS3's `cellGcmCallback`: + - writes a JUMP to the next segment; + - publishes `put` up to that JUMP; + - kicks the walker; + - waits only while the walker is still inside the next segment, that is, a whole lap behind (bounded, like the recycle wait); + - points the context at the next segment. +- **Flip markers.** `gcm_flip_into_fifo` and `_cellGcmSetFlipCommandWithWaitLabel` close a full segment the same way. Before, a flip near the end fell back to an immediate flip. Off a segmented ring the room check is unchanged. +- **Ring bounds.** The backlog is measured over the whole ring rather than the current segment. +- **Recycle.** The drain's own overrun recycle leaves the segmented ring alone. + +## Evidence + +All measurements are from God of War HD, first level, gameplay. + +- **Frame time.** With `GCM_FIFO_SEGMENT=0x8000`, together with a frame-clock fix in the port (flips completed when due), the median frame went from 22.1 ms to 20.1 ms. +- **Drain start.** Flip request to the walker reaching the flip went from 6.9 ms to 5.1 ms (ftrace). The walker now does about 3 ms of each frame while the title is still writing it. +- **Stability.** Five boots to gameplay, with no FIFO stall or resync. +- **Picture.** Unchanged frames: the same contact sheet, and no frame mixed with the next. +- **Tests:** `PS3RECOMP_BUILD_TESTS=ON`: 16/16 pass. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-566/solution/patch.diff b/tasks/sp00nznet__ps3recomp-566/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a8586a85ac9d7014af2eb66c67738d3f8b1aec6a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-566/solution/patch.diff @@ -0,0 +1,184 @@ +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index efad9b92..a26d77a1 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -556,6 +556,18 @@ s32 cellGcmInit(u32 cmdSize, u32 ioSize, u32 ioAddress) + return CELL_OK; + } + ++/* GCM_FIFO_SEGMENT=: hand the title its command ring a segment at a ++ * time, as libgcm does (RPCS3's _cellGcmInitBody uses 32 KB). The context's ++ * `end` is the end of the current segment, so the title's own reserve calls ++ * the buffer-full callback at every segment; the callback publishes `put` ++ * there and moves on (gcm_fifo_next_segment). The RSX then starts on a frame ++ * while the title is still writing it. With the whole ring as one segment, ++ * as before, `put` moves only when the title flushes: God of War HD flushes ++ * twice a frame, the second time at its flip, so its ~1.2 MB of commands ++ * reached the walker in one go and the title and the walker took turns. ++ * Unset (the default), nothing changes. */ ++static u32 s_seg_size = 0, s_ring_begin = 0, s_ring_end = 0; ++ + /* Reusable _cellGcmInitBody core (NID 0x15BAE46B). See cellGcmSys.h for why the + * guest vm is injected as callbacks. The CellGcmContextData layout here is the + * one proven in the shipping Simpsons port (begin@0/end@4/current@8/callback@C); +@@ -578,10 +590,23 @@ u32 cellGcmSetupContext(u32 ctx_out_addr, u32 cmdSize, u32 ioSize, u32 ioAddress + cellGcmInit(cmdSize, ioSize, ioAddress); + + u32 cmdbuf = ioAddress; /* FIFO lives at the IO region start */ ++ { ++ const char* e = getenv("GCM_FIFO_SEGMENT"); ++ const u32 seg = e ? (u32)strtoul(e, NULL, 0) : 0; ++ if (seg >= 0x1000 && (seg & 0xFFFu) == 0 && cmdSize >= 2 * seg) { ++ s_seg_size = seg; ++ s_ring_begin = cmdbuf; ++ s_ring_end = cmdbuf + cmdSize - cmdSize % seg; ++ printf("[cellGcmSys] command ring 0x%08X-0x%08X in %u KB segments%c", ++ s_ring_begin, s_ring_end, seg / 1024, 10); ++ } ++ } + u32 cdata = galloc ? galloc(16, 16) : 0; + if (cdata && gwrite32) { + gwrite32(cdata + 0x0, cmdbuf); /* begin */ +- gwrite32(cdata + 0x4, cmdbuf + cmdSize); /* end */ ++ /* end: the whole ring, or the first segment less the 4 bytes its ++ * closing JUMP needs. */ ++ gwrite32(cdata + 0x4, s_seg_size ? cmdbuf + s_seg_size - 4 : cmdbuf + cmdSize); + gwrite32(cdata + 0x8, cmdbuf); /* current */ + /* Command-buffer-full callback: a guest OPD {func, toc} routed to + * hle_gcm_callback -> cellGcm_fifo_recycle. Without a real callback the +@@ -925,8 +950,9 @@ static u32 gcm_fifo_backlog(u32 put, u32 get) + { + if (put >= get) return put - get; + if (!s_gcm_context_ea) return 0; +- u32 b = gcm_ea2io(vm_read32(s_gcm_context_ea + 0x0)); +- u32 e = gcm_ea2io(vm_read32(s_gcm_context_ea + 0x4)); ++ /* In segments the context holds only the current one; the ring is fixed. */ ++ u32 b = gcm_ea2io(s_seg_size ? s_ring_begin : vm_read32(s_gcm_context_ea + 0x0)); ++ u32 e = gcm_ea2io(s_seg_size ? s_ring_end : vm_read32(s_gcm_context_ea + 0x4)); + if (b == 0xFFFFFFFFu || e == 0xFFFFFFFFu || e <= b) return 0; + if (get < b || get > e || put < b || put > e) return 0; + return (e - get) + (put - b); +@@ -2427,7 +2453,9 @@ static void gcm_rsx_process_fifo_unlocked(void) + * + * ponytail: append the JUMP at `current` the way the SDK's own callback + * does, rather than tracking a second copy of the ring's geometry. */ +- if (s_gcm_ctx_out_ea) { ++ /* Not on a segmented ring: its `begin` is the current segment, and the ++ * segment callback (gcm_fifo_next_segment) keeps the title inside it. */ ++ if (s_gcm_ctx_out_ea && !(s_seg_size && vm_read32(s_gcm_ctx_out_ea) == s_gcm_context_ea)) { + u32 ctx = vm_read32(s_gcm_ctx_out_ea); + u32 begin = ctx ? vm_read32(ctx + 0x0) : 0; + u32 end = ctx ? vm_read32(ctx + 0x4) : 0; +@@ -2527,9 +2555,59 @@ static u32 gcm_ea2io(u32 ea) + return ((u32)io_page << 20) | (ea & 0xFFFFFu); + } + ++/* The buffer-full callback on a segmented ring (GCM_FIFO_SEGMENT), what ++ * RPCS3's cellGcmCallback does: close the segment with a JUMP to the next one, ++ * publish `put` up to that JUMP so the walker can start, wait while the next ++ * segment still holds commands it has not read (only when the ring is a whole ++ * lap behind), and point the context at the next segment. */ ++static void gcm_fifo_next_segment(u32 ctx) ++{ ++ const u32 cur = vm_read32(ctx + 0x8), end = vm_read32(ctx + 0x4); ++ u32 next = end + 4; ++ if (next < s_ring_begin || next + s_seg_size > s_ring_end) next = s_ring_begin; ++ const u32 io_cur = gcm_ea2io(cur), io_next = gcm_ea2io(next); ++ if (io_cur == 0xFFFFFFFFu || io_next == 0xFFFFFFFFu || cur > end) return; ++ vm_write32(cur, 0x20000000u | io_next); /* JUMP -> next segment */ ++ /* The JUMP has to be in memory before `put` lets the walker reach it. */ ++ atomic_thread_fence(memory_order_release); ++ vm_write32(GCM_CONTROL_GUEST_ADDR + 0, io_cur); /* put: up to the JUMP */ ++ if (s_gcm_kick_ev) SetEvent(s_gcm_kick_ev); /* start the walker now */ ++ /* The walker is a whole lap behind only if it is still inside the next ++ * segment. Bounded on no progress, like the recycle wait below. */ ++ int idle = 0; ++ u32 last_get = s_fifo_getoff; ++ while (s_fifo_getoff >= io_next && s_fifo_getoff < io_next + s_seg_size && idle < 2000) { ++ Sleep(1); ++ if (s_fifo_getoff != last_get) { last_get = s_fifo_getoff; idle = 0; } ++ else idle++; ++ } ++ if (idle >= 2000) { ++ static int warned = 0; ++ if (PS3_LOG_FIRST(warned, 4)) ++ printf("[cellGcmSys] fifo segment: walker stalled in the next segment (get=0x%08X)%c", ++ s_fifo_getoff, 10); ++ } ++ vm_write32(ctx + 0x0, next); ++ vm_write32(ctx + 0x8, next); ++ vm_write32(ctx + 0x4, next + s_seg_size - 4); ++} ++ ++/* Room for `bytes` more at the context's write head. On the segmented ring a ++ * full segment is closed and the next one opened, as the title's own reserve ++ * would; elsewhere this only checks, with the recycle slack. */ ++static int gcm_ctx_room(u32 ctx, u32 bytes) ++{ ++ if (s_seg_size && ctx == s_gcm_context_ea) { ++ if (vm_read32(ctx + 0x8) + bytes > vm_read32(ctx + 0x4)) gcm_fifo_next_segment(ctx); ++ return vm_read32(ctx + 0x8) + bytes <= vm_read32(ctx + 0x4); ++ } ++ return vm_read32(ctx + 0x8) + bytes + GCM_RECYCLE_SLACK <= vm_read32(ctx + 0x4); ++} ++ + void cellGcm_fifo_recycle(u32 ctx_ea) + { + if (!ctx_ea) return; ++ if (s_seg_size && ctx_ea == s_gcm_context_ea) { gcm_fifo_next_segment(ctx_ea); return; } + u32 begin = vm_read32(ctx_ea + 0x0); + u32 current = vm_read32(ctx_ea + 0x8); + if (current <= begin) return; /* nothing to recycle */ +@@ -2772,10 +2850,12 @@ static int gcm_flip_into_fifo(u32 ctx, u32 bufferId) + { + if (!ctx || bufferId >= CELL_GCM_MAX_DISPLAY_BUFFER_NUM || + !s_display_buffer_set[bufferId]) return 0; +- const u32 end = vm_read32(ctx + 4), cur = vm_read32(ctx + 8); + /* Never near the end: those bytes are the title's reserve before its +- * ring wraps, and the recycle above keys on them. */ +- if (cur + 8 + GCM_RECYCLE_SLACK > end || gcm_ea2io(cur) == 0xFFFFFFFFu) return 0; ++ * ring wraps, and the recycle above keys on them. On a segmented ring a ++ * full segment is closed first instead. */ ++ if (!gcm_ctx_room(ctx, 8)) return 0; ++ const u32 end = vm_read32(ctx + 4), cur = vm_read32(ctx + 8); ++ if (gcm_ea2io(cur) == 0xFFFFFFFFu) return 0; + vm_write32(cur, GCM_FLIP_MARKER | bufferId); + s_fifo_flips_queued++; + /* Wrap here, on the guest thread, once the ring is nearly used -- what the +@@ -2796,7 +2876,7 @@ static int gcm_flip_into_fifo(u32 ctx, u32 bufferId) + const u32 begin = vm_read32(ctx), io_begin = gcm_ea2io(begin); + const u32 cb_opd = vm_read32(ctx + 0xC); + const int runtime_ring = cb_opd && vm_read32(cb_opd) == GCM_FIFO_CALLBACK_SENTINEL_EA; +- if (runtime_ring && end - (cur + 4) < GCM_FLIP_WRAP_BYTES && io_begin != 0xFFFFFFFFu && ++ if (runtime_ring && !s_seg_size && end - (cur + 4) < GCM_FLIP_WRAP_BYTES && io_begin != 0xFFFFFFFFu && + s_fifo_getoff >= io_begin + GCM_RECYCLE_MARGIN) { + vm_write32(cur + 4, 0x20000000u | io_begin); /* JUMP -> begin */ + vm_write32(ctx + 8, begin); +@@ -3625,8 +3705,9 @@ s32 _cellGcmSetFlipCommandWithWaitLabel(void* ctx, u32 bufferId, + const u32 c = (u32)(uintptr_t)ctx; + if (c && labelIndex < CELL_GCM_MAX_LABEL_COUNT && + bufferId < CELL_GCM_MAX_DISPLAY_BUFFER_NUM && s_display_buffer_set[bufferId]) { +- const u32 end = vm_read32(c + 4), cur = vm_read32(c + 8); +- if (cur + 16 + 8 + GCM_RECYCLE_SLACK <= end && gcm_ea2io(cur) != 0xFFFFFFFFu) { ++ const int room = gcm_ctx_room(c, 16 + 8); ++ const u32 cur = vm_read32(c + 8); ++ if (room && gcm_ea2io(cur) != 0xFFFFFFFFu) { + vm_write32(cur + 0, 0x00040064u); /* SEMAPHORE_OFFSET */ + vm_write32(cur + 4, labelIndex * GCM_LABEL_STRIDE); + vm_write32(cur + 8, 0x00040068u); /* SEMAPHORE_ACQUIRE */ +diff --git a/libs/video/tests/test_gcm_flip_stream.c b/libs/video/tests/test_gcm_flip_stream.c +index 455e2c65..1ce449ca 100644 +--- a/libs/video/tests/test_gcm_flip_stream.c ++++ b/libs/video/tests/test_gcm_flip_stream.c +@@ -44,6 +44,11 @@ PPU_THREAD_LOCAL ppu_context* g_active_ctx; + u32 g_rsx_last_reference; + void (*g_spu_put_hook)(uint32_t ea, uint32_t size); + void rsx_raise_user_cmd(uint32_t arg) { (void)arg; } ++/* gcm_fifo_next_segment wakes the drain thread; this fixture has none, and ++ * runtime/platform/win32_compat.c is not linked. */ ++#ifndef _WIN32 ++BOOL SetEvent(HANDLE h) { (void)h; return 1; } ++#endif + void ppu_dump_bctrl_ring(uint32_t n, const char* why) { (void)n; (void)why; } + void ppu_dump_guest_stack(ppu_context* c, const char* why) { (void)c; (void)why; } + void rsx_state_init(rsx_state* state) { (void)state; } diff --git a/tasks/sp00nznet__ps3recomp-566/solution/solve.sh b/tasks/sp00nznet__ps3recomp-566/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-566/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-566/task.toml b/tasks/sp00nznet__ps3recomp-566/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2af73c2217341d228463f2378e824521c84cb446 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-566/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-566" +description = "cellGcmSys: GCM_FIFO_SEGMENT hands the command ring out in segments" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "a6d76c895f77eb30b90a806c830544e61821b77f" +reference = "https://github.com/sp00nznet/ps3recomp/pull/566" +source_access = "auto" +built_at = "2026-11-16T16:09:59.701872+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:cd572435169fb2a89feaf11bb4223ba97225049135b227aae54e1e8c4bb8bd9e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "libs/video/cellGcmSys.c", + "libs/video/tests/test_gcm_flip_stream.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 106 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.121275+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-566/tests/capture.py b/tasks/sp00nznet__ps3recomp-566/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-566/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-566/tests/instruction.md b/tasks/sp00nznet__ps3recomp-566/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b0f3e1e73ee3dc9f0948612505469eb90c374be6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-566/tests/instruction.md @@ -0,0 +1,45 @@ +# Issue + +**Title:** cellGcmSys: GCM_FIFO_SEGMENT hands the command ring out in segments + +## Description + +## Why + +`cellGcmSetupContext` gives the title its whole command ring as one context: `end` is the end of the ring. So: + +- the buffer-full callback runs only when the ring wraps; +- `put` moves only when the title flushes. + +libgcm hands the ring out a segment at a time. RPCS3's `_cellGcmInitBody` sets `end = begin + 32 * 1024 - 4`, and its `cellGcmCallback` publishes `put` at every segment. On hardware the RSX therefore starts on a frame while the title is still writing it. + +God of War HD (NPUA80490) writes about 1.2 MB of commands per frame and flushes twice a frame, the second time at its flip. With the whole ring as one segment, the frame reached the walker in one go, and the title and the walker took turns. + +## Change + +`GCM_FIFO_SEGMENT=` (at least 4 KB, 4 KB aligned, and at most half the ring) hands the runtime's ring out in segments of that size. Unset, nothing changes. + +- **The context.** `end` is the end of the current segment, less 4 bytes for the closing JUMP. +- **The buffer-full callback on that ring** (`gcm_fifo_next_segment`) works like RPCS3's `cellGcmCallback`: + - writes a JUMP to the next segment; + - publishes `put` up to that JUMP; + - kicks the walker; + - waits only while the walker is still inside the next segment, that is, a whole lap behind (bounded, like the recycle wait); + - points the context at the next segment. +- **Flip markers.** `gcm_flip_into_fifo` and `_cellGcmSetFlipCommandWithWaitLabel` close a full segment the same way. Before, a flip near the end fell back to an immediate flip. Off a segmented ring the room check is unchanged. +- **Ring bounds.** The backlog is measured over the whole ring rather than the current segment. +- **Recycle.** The drain's own overrun recycle leaves the segmented ring alone. + +## Evidence + +All measurements are from God of War HD, first level, gameplay. + +- **Frame time.** With `GCM_FIFO_SEGMENT=0x8000`, together with a frame-clock fix in the port (flips completed when due), the median frame went from 22.1 ms to 20.1 ms. +- **Drain start.** Flip request to the walker reaching the flip went from 6.9 ms to 5.1 ms (ftrace). The walker now does about 3 ms of each frame while the title is still writing it. +- **Stability.** Five boots to gameplay, with no FIFO stall or resync. +- **Picture.** Unchanged frames: the same contact sheet, and no frame mixed with the next. +- **Tests:** `PS3RECOMP_BUILD_TESTS=ON`: 16/16 pass. + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-566/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-566/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a8586a85ac9d7014af2eb66c67738d3f8b1aec6a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-566/tests/oracle.patch @@ -0,0 +1,184 @@ +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index efad9b92..a26d77a1 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -556,6 +556,18 @@ s32 cellGcmInit(u32 cmdSize, u32 ioSize, u32 ioAddress) + return CELL_OK; + } + ++/* GCM_FIFO_SEGMENT=: hand the title its command ring a segment at a ++ * time, as libgcm does (RPCS3's _cellGcmInitBody uses 32 KB). The context's ++ * `end` is the end of the current segment, so the title's own reserve calls ++ * the buffer-full callback at every segment; the callback publishes `put` ++ * there and moves on (gcm_fifo_next_segment). The RSX then starts on a frame ++ * while the title is still writing it. With the whole ring as one segment, ++ * as before, `put` moves only when the title flushes: God of War HD flushes ++ * twice a frame, the second time at its flip, so its ~1.2 MB of commands ++ * reached the walker in one go and the title and the walker took turns. ++ * Unset (the default), nothing changes. */ ++static u32 s_seg_size = 0, s_ring_begin = 0, s_ring_end = 0; ++ + /* Reusable _cellGcmInitBody core (NID 0x15BAE46B). See cellGcmSys.h for why the + * guest vm is injected as callbacks. The CellGcmContextData layout here is the + * one proven in the shipping Simpsons port (begin@0/end@4/current@8/callback@C); +@@ -578,10 +590,23 @@ u32 cellGcmSetupContext(u32 ctx_out_addr, u32 cmdSize, u32 ioSize, u32 ioAddress + cellGcmInit(cmdSize, ioSize, ioAddress); + + u32 cmdbuf = ioAddress; /* FIFO lives at the IO region start */ ++ { ++ const char* e = getenv("GCM_FIFO_SEGMENT"); ++ const u32 seg = e ? (u32)strtoul(e, NULL, 0) : 0; ++ if (seg >= 0x1000 && (seg & 0xFFFu) == 0 && cmdSize >= 2 * seg) { ++ s_seg_size = seg; ++ s_ring_begin = cmdbuf; ++ s_ring_end = cmdbuf + cmdSize - cmdSize % seg; ++ printf("[cellGcmSys] command ring 0x%08X-0x%08X in %u KB segments%c", ++ s_ring_begin, s_ring_end, seg / 1024, 10); ++ } ++ } + u32 cdata = galloc ? galloc(16, 16) : 0; + if (cdata && gwrite32) { + gwrite32(cdata + 0x0, cmdbuf); /* begin */ +- gwrite32(cdata + 0x4, cmdbuf + cmdSize); /* end */ ++ /* end: the whole ring, or the first segment less the 4 bytes its ++ * closing JUMP needs. */ ++ gwrite32(cdata + 0x4, s_seg_size ? cmdbuf + s_seg_size - 4 : cmdbuf + cmdSize); + gwrite32(cdata + 0x8, cmdbuf); /* current */ + /* Command-buffer-full callback: a guest OPD {func, toc} routed to + * hle_gcm_callback -> cellGcm_fifo_recycle. Without a real callback the +@@ -925,8 +950,9 @@ static u32 gcm_fifo_backlog(u32 put, u32 get) + { + if (put >= get) return put - get; + if (!s_gcm_context_ea) return 0; +- u32 b = gcm_ea2io(vm_read32(s_gcm_context_ea + 0x0)); +- u32 e = gcm_ea2io(vm_read32(s_gcm_context_ea + 0x4)); ++ /* In segments the context holds only the current one; the ring is fixed. */ ++ u32 b = gcm_ea2io(s_seg_size ? s_ring_begin : vm_read32(s_gcm_context_ea + 0x0)); ++ u32 e = gcm_ea2io(s_seg_size ? s_ring_end : vm_read32(s_gcm_context_ea + 0x4)); + if (b == 0xFFFFFFFFu || e == 0xFFFFFFFFu || e <= b) return 0; + if (get < b || get > e || put < b || put > e) return 0; + return (e - get) + (put - b); +@@ -2427,7 +2453,9 @@ static void gcm_rsx_process_fifo_unlocked(void) + * + * ponytail: append the JUMP at `current` the way the SDK's own callback + * does, rather than tracking a second copy of the ring's geometry. */ +- if (s_gcm_ctx_out_ea) { ++ /* Not on a segmented ring: its `begin` is the current segment, and the ++ * segment callback (gcm_fifo_next_segment) keeps the title inside it. */ ++ if (s_gcm_ctx_out_ea && !(s_seg_size && vm_read32(s_gcm_ctx_out_ea) == s_gcm_context_ea)) { + u32 ctx = vm_read32(s_gcm_ctx_out_ea); + u32 begin = ctx ? vm_read32(ctx + 0x0) : 0; + u32 end = ctx ? vm_read32(ctx + 0x4) : 0; +@@ -2527,9 +2555,59 @@ static u32 gcm_ea2io(u32 ea) + return ((u32)io_page << 20) | (ea & 0xFFFFFu); + } + ++/* The buffer-full callback on a segmented ring (GCM_FIFO_SEGMENT), what ++ * RPCS3's cellGcmCallback does: close the segment with a JUMP to the next one, ++ * publish `put` up to that JUMP so the walker can start, wait while the next ++ * segment still holds commands it has not read (only when the ring is a whole ++ * lap behind), and point the context at the next segment. */ ++static void gcm_fifo_next_segment(u32 ctx) ++{ ++ const u32 cur = vm_read32(ctx + 0x8), end = vm_read32(ctx + 0x4); ++ u32 next = end + 4; ++ if (next < s_ring_begin || next + s_seg_size > s_ring_end) next = s_ring_begin; ++ const u32 io_cur = gcm_ea2io(cur), io_next = gcm_ea2io(next); ++ if (io_cur == 0xFFFFFFFFu || io_next == 0xFFFFFFFFu || cur > end) return; ++ vm_write32(cur, 0x20000000u | io_next); /* JUMP -> next segment */ ++ /* The JUMP has to be in memory before `put` lets the walker reach it. */ ++ atomic_thread_fence(memory_order_release); ++ vm_write32(GCM_CONTROL_GUEST_ADDR + 0, io_cur); /* put: up to the JUMP */ ++ if (s_gcm_kick_ev) SetEvent(s_gcm_kick_ev); /* start the walker now */ ++ /* The walker is a whole lap behind only if it is still inside the next ++ * segment. Bounded on no progress, like the recycle wait below. */ ++ int idle = 0; ++ u32 last_get = s_fifo_getoff; ++ while (s_fifo_getoff >= io_next && s_fifo_getoff < io_next + s_seg_size && idle < 2000) { ++ Sleep(1); ++ if (s_fifo_getoff != last_get) { last_get = s_fifo_getoff; idle = 0; } ++ else idle++; ++ } ++ if (idle >= 2000) { ++ static int warned = 0; ++ if (PS3_LOG_FIRST(warned, 4)) ++ printf("[cellGcmSys] fifo segment: walker stalled in the next segment (get=0x%08X)%c", ++ s_fifo_getoff, 10); ++ } ++ vm_write32(ctx + 0x0, next); ++ vm_write32(ctx + 0x8, next); ++ vm_write32(ctx + 0x4, next + s_seg_size - 4); ++} ++ ++/* Room for `bytes` more at the context's write head. On the segmented ring a ++ * full segment is closed and the next one opened, as the title's own reserve ++ * would; elsewhere this only checks, with the recycle slack. */ ++static int gcm_ctx_room(u32 ctx, u32 bytes) ++{ ++ if (s_seg_size && ctx == s_gcm_context_ea) { ++ if (vm_read32(ctx + 0x8) + bytes > vm_read32(ctx + 0x4)) gcm_fifo_next_segment(ctx); ++ return vm_read32(ctx + 0x8) + bytes <= vm_read32(ctx + 0x4); ++ } ++ return vm_read32(ctx + 0x8) + bytes + GCM_RECYCLE_SLACK <= vm_read32(ctx + 0x4); ++} ++ + void cellGcm_fifo_recycle(u32 ctx_ea) + { + if (!ctx_ea) return; ++ if (s_seg_size && ctx_ea == s_gcm_context_ea) { gcm_fifo_next_segment(ctx_ea); return; } + u32 begin = vm_read32(ctx_ea + 0x0); + u32 current = vm_read32(ctx_ea + 0x8); + if (current <= begin) return; /* nothing to recycle */ +@@ -2772,10 +2850,12 @@ static int gcm_flip_into_fifo(u32 ctx, u32 bufferId) + { + if (!ctx || bufferId >= CELL_GCM_MAX_DISPLAY_BUFFER_NUM || + !s_display_buffer_set[bufferId]) return 0; +- const u32 end = vm_read32(ctx + 4), cur = vm_read32(ctx + 8); + /* Never near the end: those bytes are the title's reserve before its +- * ring wraps, and the recycle above keys on them. */ +- if (cur + 8 + GCM_RECYCLE_SLACK > end || gcm_ea2io(cur) == 0xFFFFFFFFu) return 0; ++ * ring wraps, and the recycle above keys on them. On a segmented ring a ++ * full segment is closed first instead. */ ++ if (!gcm_ctx_room(ctx, 8)) return 0; ++ const u32 end = vm_read32(ctx + 4), cur = vm_read32(ctx + 8); ++ if (gcm_ea2io(cur) == 0xFFFFFFFFu) return 0; + vm_write32(cur, GCM_FLIP_MARKER | bufferId); + s_fifo_flips_queued++; + /* Wrap here, on the guest thread, once the ring is nearly used -- what the +@@ -2796,7 +2876,7 @@ static int gcm_flip_into_fifo(u32 ctx, u32 bufferId) + const u32 begin = vm_read32(ctx), io_begin = gcm_ea2io(begin); + const u32 cb_opd = vm_read32(ctx + 0xC); + const int runtime_ring = cb_opd && vm_read32(cb_opd) == GCM_FIFO_CALLBACK_SENTINEL_EA; +- if (runtime_ring && end - (cur + 4) < GCM_FLIP_WRAP_BYTES && io_begin != 0xFFFFFFFFu && ++ if (runtime_ring && !s_seg_size && end - (cur + 4) < GCM_FLIP_WRAP_BYTES && io_begin != 0xFFFFFFFFu && + s_fifo_getoff >= io_begin + GCM_RECYCLE_MARGIN) { + vm_write32(cur + 4, 0x20000000u | io_begin); /* JUMP -> begin */ + vm_write32(ctx + 8, begin); +@@ -3625,8 +3705,9 @@ s32 _cellGcmSetFlipCommandWithWaitLabel(void* ctx, u32 bufferId, + const u32 c = (u32)(uintptr_t)ctx; + if (c && labelIndex < CELL_GCM_MAX_LABEL_COUNT && + bufferId < CELL_GCM_MAX_DISPLAY_BUFFER_NUM && s_display_buffer_set[bufferId]) { +- const u32 end = vm_read32(c + 4), cur = vm_read32(c + 8); +- if (cur + 16 + 8 + GCM_RECYCLE_SLACK <= end && gcm_ea2io(cur) != 0xFFFFFFFFu) { ++ const int room = gcm_ctx_room(c, 16 + 8); ++ const u32 cur = vm_read32(c + 8); ++ if (room && gcm_ea2io(cur) != 0xFFFFFFFFu) { + vm_write32(cur + 0, 0x00040064u); /* SEMAPHORE_OFFSET */ + vm_write32(cur + 4, labelIndex * GCM_LABEL_STRIDE); + vm_write32(cur + 8, 0x00040068u); /* SEMAPHORE_ACQUIRE */ +diff --git a/libs/video/tests/test_gcm_flip_stream.c b/libs/video/tests/test_gcm_flip_stream.c +index 455e2c65..1ce449ca 100644 +--- a/libs/video/tests/test_gcm_flip_stream.c ++++ b/libs/video/tests/test_gcm_flip_stream.c +@@ -44,6 +44,11 @@ PPU_THREAD_LOCAL ppu_context* g_active_ctx; + u32 g_rsx_last_reference; + void (*g_spu_put_hook)(uint32_t ea, uint32_t size); + void rsx_raise_user_cmd(uint32_t arg) { (void)arg; } ++/* gcm_fifo_next_segment wakes the drain thread; this fixture has none, and ++ * runtime/platform/win32_compat.c is not linked. */ ++#ifndef _WIN32 ++BOOL SetEvent(HANDLE h) { (void)h; return 1; } ++#endif + void ppu_dump_bctrl_ring(uint32_t n, const char* why) { (void)n; (void)why; } + void ppu_dump_guest_stack(ppu_context* c, const char* why) { (void)c; (void)why; } + void rsx_state_init(rsx_state* state) { (void)state; } diff --git a/tasks/sp00nznet__ps3recomp-566/tests/test.sh b/tasks/sp00nznet__ps3recomp-566/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-566/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-566/tests/verifier.py b/tasks/sp00nznet__ps3recomp-566/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-566/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-585/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-585/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-585/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-585/instruction.md b/tasks/sp00nznet__ps3recomp-585/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7715432288fa4d90dfab3f3dd0984f7e5ecbfc8b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-585/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** rsx engine: block-compressed (DXT) 3D textures go up as volumes + +## Description + +A texture unit whose `SET_TEXTURE_FORMAT` dimension is 3 (with a depth in `CONTROL3`) is a volume. The 3D path added in 1ba3657 takes uncompressed formats only, so a DXT volume still went up as a 2D texture made of its first slice-sized bytes. The fragment program, given the unit in the volume mask, declared it `Texture3D` all the same. + +A retail title draws its explosion smoke from 256x256x16 DXT5 volumes in main memory (`SET_TEXTURE_FORMAT` 0x0001883A: dimension 3, DXT45; depth 16), the animation running along the third coordinate. Compressed volumes whose sides are powers of two are stored in NVIDIA's VTC order: the slices go in groups of four, and within a group the four slices' blocks at one position follow each other. Read as one 2D image, the first 64 KB are four slices interleaved block by block, and one of the volumes holds a near-empty first group whose every fourth block is opaque black. The smoke drew as dark translucent squares with hard edges. + +## Change + +- `eng_texture_upload`: block-compressed formats take the 3D path too. + - A level whose width and height are powers of two is in VTC order. `eng_unvtc_3d_slice` lays a slice out of it into the staging rows (the depth % 4 slices left over form a smaller last group). It is written from the [NV_texture_compression_vtc](https://registry.khronos.org/OpenGL/extensions/NV/NV_texture_compression_vtc.txt) spec alone, cited in the source. For full groups it is the spec's `blockIndex`. For the last group the spec's formula stores the slices one after another, which contradicts its prose (4x4x2 and 4x4x3 blocks) when depth % 4 >= 2; the prose is followed. + - Any other level is slice after slice, as RPCS3 treats it. +- Metal `texture_upload_3d`: a block-compressed slice spans its block rows. `bytesPerImage` was row bytes times texel rows, four times the slice. That was harmless while each upload is one slice, but not what the call means. + +## Tests + +- `test_rsx_draw_engine`, a new group with a stub backend that has the 3D calls: + - an 8x8x6 DXT5 volume (a group of four and a group of two) goes up as six slices, every block where its slice put it; + - a 12x4x2 DXT5 volume (not a power of two) goes up slice after slice; + - a 16x16x8 DXT1 volume with three levels (8, 4 and 2 slices) goes up level by level, each out of its own VTC order. +- Each check fails without the change. A VTC order without the last group's own stride also fails, and so do levels not a whole level apart. +- `engine_up` became `engine_up_with(backend)` so a group can bring the engine up on its own backend. +- The group passes under ASan, with clang and with gcc. +- In the title, a per-draw capture traced the squares to the draws that sample those volumes. Their bytes, taken out of VTC order, are the smoke's slices. + +## Provenance + +The first version of `eng_unvtc_3d_slice()` was a port of RPCS3's `copy_unmodified_block_vtc`; the licence review held the PR for those eight lines. 53d9ecd rewrites them (the earlier version is still in this branch's history, so a squash merge would keep it out of master's) from the Khronos spec alone, without the earlier code in view, and drops the RPCS3 link. A standalone check compared the new function with a direct implementation of the spec's `blockIndex` for every block of eleven volumes (depth % 4 of 0 or 1) and with the prose layout for depths 1-7, 10 and 11, at 8 and 16 bytes per block, under ASan and UBSan. The three volume tests above pass unchanged. + +v0.18.0 merged in (acc93bb): the volume path keeps master's `!into` condition (no 3D path for an upload into an existing texture). On this branch (macOS arm64) ctest passes (22 of 22) and so do the `tools/test_*.py` scripts (120 of 120). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-585/solution/patch.diff b/tasks/sp00nznet__ps3recomp-585/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..abe65248188313c76ad7110e42d76f12710d961d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-585/solution/patch.diff @@ -0,0 +1,238 @@ +diff --git a/libs/video/rsx_draw_engine.c b/libs/video/rsx_draw_engine.c +index 8dff6011..b1995174 100644 +--- a/libs/video/rsx_draw_engine.c ++++ b/libs/video/rsx_draw_engine.c +@@ -1165,6 +1165,27 @@ static void eng_deswizzle_3d_slice(u8* dst, const u8* src, u32 w, u32 h, u32 d, + src + (size_t)rsx_swizzle_offset_3d(x, y, z, lw, lh, ld) * bpp, bpp); + } + ++/* Slice z of a block-compressed 3D level in NVIDIA's VTC layout ++ * (https://registry.khronos.org/OpenGL/extensions/NV/NV_texture_compression_vtc.txt), ++ * into dst in plain S3TC order. Slices go in groups of four, and each 4x4x4 ++ * block is four consecutive 4x4 blocks, one per layer; the d % 4 slices left ++ * over form a last group of 4x4x1, 4x4x2 or 4x4x3 blocks. So block i of slice ++ * z is at (4 * floor(z / 4) * blocks + i * n + z % 4) * block_bytes, n the ++ * layer count of z's group. For full groups that is the spec's blockIndex; for ++ * the last group the spec's formula stores the slices one after another, which ++ * contradicts its prose for d % 4 >= 2, and the prose is followed. `blocks` is ++ * the blocks in one slice. Only a volume whose width and height are powers of ++ * two is stored this way; any other is slice after slice. */ ++static void eng_unvtc_3d_slice(u8* dst, const u8* src, u32 blocks, u32 d, u32 z, u32 block_bytes) ++{ ++ const u32 group = z & ~3u; ++ const u32 n = group + 4 <= d ? 4 : d - group; ++ const u8* base = src + (size_t)group * blocks * block_bytes; ++ for (u32 i = 0; i < blocks; i++) ++ memcpy(dst + (size_t)i * block_bytes, ++ base + ((size_t)i * n + (z & 3)) * block_bytes, block_bytes); ++} ++ + /* One hash per cached texture per presented frame. Word-at-a-time FNV over + * the whole span is deliberately cheap: this is a mutation detector, not a + * content id (rsx_live_draw.c:2002-2026). */ +@@ -1248,9 +1269,12 @@ static u32 eng_texture_upload(u32 location, u32 offset, u32 fmt, u32 w, u32 h, + if (!nlv || !lv[0].tl.face_bytes) return 0; + /* A volume: every slice of every level decoded and uploaded on its own. + * inFAMOUS 2's occlusion volumes read an 8x8x8 cone LUT; uploaded as its +- * first slice and sampled in 2D it darkened whole boxes round every prop. */ ++ * first slice and sampled in 2D it darkened whole boxes round every prop. ++ * A DXT volume too: a retail title's explosion smoke is a 256x256x16 DXT5 ++ * animation, and its first 64 KB read as one 2D image (four slices' ++ * blocks interleaved) drew dark squares where the smoke was. */ + if (!into && depth > 1 && !cube && g.be->texture_create_3d && g.be->texture_upload_3d && +- !lv[0].tl.compressed && lv[0].tl.bytes_per_texel) { ++ (lv[0].tl.compressed || lv[0].tl.bytes_per_texel)) { + const u32 span = eng_texture_span_3d(fmt, w, h, depth, levels, pitch); + const u8* src = eng_guest_ptr(NULL, location, offset, span); + if (!src) return 0; +@@ -1261,13 +1285,19 @@ static u32 eng_texture_upload(u32 location, u32 offset, u32 fmt, u32 w, u32 h, + u32 d = depth; + for (u32 m = 0; m < nlv; m++) { + const rsx_tex_layout* tl = &lv[m].tl; ++ const int vtc = tl->compressed && !(lv[m].w & (lv[m].w - 1u)) && ++ !(lv[m].h & (lv[m].h - 1u)); + const u32 lin_bytes = tl->swizzled ? tl->row_bytes * tl->rows : 0u; + if (!eng_staging_reserve(tl->dst_row_bytes * tl->rows + lin_bytes)) { + g.be->texture_release(g.be->user, handle); + return 0; + } + for (u32 z = 0; z < d; z++) { +- if (tl->swizzled) { ++ if (vtc) { ++ /* Block rows go up as they are (rsx_texture_decode only copies them). */ ++ eng_unvtc_3d_slice(g.tex_staging, level_src, tl->face_bytes / tl->block_bytes, d, z, ++ tl->block_bytes); ++ } else if (tl->swizzled) { + u8* lin = g.tex_staging + tl->dst_row_bytes * tl->rows; + eng_deswizzle_3d_slice(lin, level_src, lv[m].w, lv[m].h, d, z, tl->bytes_per_texel); + rsx_tex_layout ltl = *tl; ltl.swizzled = 0; +diff --git a/libs/video/rsx_metal_backend.m b/libs/video/rsx_metal_backend.m +index ad8db0b5..8fe1839b 100644 +--- a/libs/video/rsx_metal_backend.m ++++ b/libs/video/rsx_metal_backend.m +@@ -3113,12 +3113,17 @@ static void eng_texture_upload_3d(void* user, u32 handle, u32 z, u32 mip, + (void)user; + id t = eng_obj(handle); + if (!t || !src || !row_bytes) return; ++ /* A block-compressed slice is rows of 4x4 blocks. */ ++ const MTLPixelFormat pf = [t pixelFormat]; ++ const int bc = pf == MTLPixelFormatBC1_RGBA || pf == MTLPixelFormatBC2_RGBA || ++ pf == MTLPixelFormatBC3_RGBA; ++ const u32 rows = bc ? (h + 3u) / 4u : h; + [t replaceRegion:MTLRegionMake3D(0, 0, z, w, h, 1) + mipmapLevel:mip + slice:0 + withBytes:src + bytesPerRow:row_bytes +- bytesPerImage:(NSUInteger)row_bytes * h]; ++ bytesPerImage:(NSUInteger)row_bytes * rows]; + } + + static u32 eng_color_target_create(void* user, rsx_be_format fmt, u32 w, u32 h, +diff --git a/libs/video/tests/test_rsx_draw_engine.c b/libs/video/tests/test_rsx_draw_engine.c +index 8099901a..6b1b4514 100644 +--- a/libs/video/tests/test_rsx_draw_engine.c ++++ b/libs/video/tests/test_rsx_draw_engine.c +@@ -796,6 +796,134 @@ static void test_texture_sparse_rehash(void) + + /* ---- 4. the pipeline key ------------------------------------------------- */ + ++/* A block-compressed volume (dimension 3, DXT) goes up slice by slice as a ++ * 3D texture. A retail title's explosion smoke is a 256x256x16 DXT5 volume; ++ * uploaded as the 2D image its first 64 KB make, it drew dark squares. */ ++#define VOL_MIPS 3 ++#define VOL_SLICES 8 ++static struct { ++ int n_create, n_upload; ++ u32 depth, row_bytes[VOL_MIPS]; ++ u8 slice[VOL_MIPS][VOL_SLICES][128]; /* the first bytes of each slice's upload */ ++} g_vol; ++ ++static u32 stub_texture_create_3d(void* u, rsx_be_format f, u32 w, u32 h, u32 depth, ++ u32 mips, u32 remap, u32 rsx_fmt) ++{ ++ g_vol.n_create++; ++ g_vol.depth = depth; ++ return stub_texture_create(u, f, w, h, mips, 1, remap, rsx_fmt); ++} ++ ++static void stub_texture_upload_3d(void* u, u32 t, u32 z, u32 mip, u32 w, u32 h, ++ const void* src, u32 row_bytes) ++{ ++ (void)u; (void)t; (void)w; ++ g_vol.n_upload++; ++ if (mip >= VOL_MIPS || z >= VOL_SLICES || !src) return; ++ g_vol.row_bytes[mip] = row_bytes; ++ const u32 bytes = row_bytes * ((h + 3u) / 4u); /* one slice of block rows */ ++ memcpy(g_vol.slice[mip][z], src, bytes < 128u ? bytes : 128u); ++} ++ ++/* Block i of slice z of level m, as the volume's guest bytes mark it. */ ++static int volume_block_is(u32 m, u32 z, u32 i, u32 block_bytes) ++{ ++ const u8* b = g_vol.slice[m][z] + i * block_bytes; ++ return b[0] == (u8)(0xA0u + m * 0x10u + z) && b[1] == (u8)i; ++} ++ ++/* Lay level m (w x h blocks, d slices) out at `at` in VTC order (power-of-two ++ * sides) or slice after slice, each block marked with its level, slice and ++ * index. Returns the level's size. */ ++static u32 volume_level(u32 at, u32 m, u32 blocks, u32 d, u32 block_bytes, int vtc) ++{ ++ const u32 full = d & ~3u; ++ for (u32 z = 0; z < d; z++) ++ for (u32 i = 0; i < blocks; i++) { ++ u32 n = z * blocks + i; ++ if (vtc) { ++ const u32 group = z < full ? z & ~3u : full, stride = z < full ? 4u : d - full; ++ n = group * blocks + i * stride + (z - group); ++ } ++ vm_base[at + n * block_bytes] = (u8)(0xA0u + m * 0x10u + z); ++ vm_base[at + n * block_bytes + 1u] = (u8)i; ++ } ++ return blocks * d * block_bytes; ++} ++ ++static void bind_volume(u32 fmt, u32 w, u32 h, u32 depth, u32 mips) ++{ ++ m(M_TEX_UNIT + 0x00, TEX_OFFSET); ++ m(M_TEX_UNIT + 0x04, 2u | (3u << 4) | (fmt << 8) | (mips << 16)); /* main, 3D */ ++ m(M_TEX_UNIT + 0x0C, 0x80000000u); ++ m(M_TEX_UNIT + 0x10, 0xAAE4u); ++ m(M_TEX_UNIT + 0x18, (w << 16) | h); ++ m(0x1840 /* control3 */, depth << 20); ++} ++ ++static void test_compressed_volume(void) ++{ ++ printf("-- compressed volume\n"); ++ rsx_draw_backend be = g_stub_backend; ++ be.texture_create_3d = stub_texture_create_3d; ++ be.texture_upload_3d = stub_texture_upload_3d; ++ ++ /* 8x8x6 DXT5: four blocks a slice. Power-of-two sides, so VTC order: ++ * slices 0-3 interleaved block by block, then 4-5 the same way. */ ++ engine_up_with(&be); ++ memset(&g_vol, 0, sizeof g_vol); ++ memset(vm_base + TEX_OFFSET, 0, 0x1000); ++ volume_level(TEX_OFFSET, 0, 4, 6, 16, 1); ++ bind_volume(0x88, 8, 8, 6, 1); ++ draw_triangle(); ++ int ok = g_vol.n_create == 1 && g_vol.depth == 6 && g_vol.n_upload == 6 && g_vol.row_bytes[0] == 32; ++ for (u32 z = 0; z < 6 && ok; z++) ++ for (u32 i = 0; i < 4; i++) ok &= volume_block_is(0, z, i, 16); ++ CHECK(ok, "a power-of-two DXT5 volume goes up as 6 slices out of VTC order " ++ "(%d created, depth %u, %d uploads, row %u)", ++ g_vol.n_create, g_vol.depth, g_vol.n_upload, g_vol.row_bytes[0]); ++ engine_down(); ++ ++ /* 12x4x2: not a power of two, so slice after slice as they lie. */ ++ engine_up_with(&be); ++ memset(&g_vol, 0, sizeof g_vol); ++ memset(vm_base + TEX_OFFSET, 0, 0x1000); ++ volume_level(TEX_OFFSET, 0, 3, 2, 16, 0); ++ bind_volume(0x88, 12, 4, 2, 1); ++ draw_triangle(); ++ ok = g_vol.n_create == 1 && g_vol.n_upload == 2 && g_vol.row_bytes[0] == 48; ++ for (u32 z = 0; z < 2 && ok; z++) ++ for (u32 i = 0; i < 3; i++) ok &= volume_block_is(0, z, i, 16); ++ CHECK(ok, "a non-power-of-two DXT5 volume goes up slice after slice " ++ "(%d created, %d uploads, row %u)", ++ g_vol.n_create, g_vol.n_upload, g_vol.row_bytes[0]); ++ engine_down(); ++ ++ /* 16x16x8 DXT1 with three levels: 16 blocks x 8 slices (two groups of ++ * four), 4 blocks x 4 slices (one group), 1 block x 2 slices (a group of ++ * two), each level in VTC order after the one before. */ ++ engine_up_with(&be); ++ memset(&g_vol, 0, sizeof g_vol); ++ memset(vm_base + TEX_OFFSET, 0, 0x1000); ++ u32 at = TEX_OFFSET; ++ at += volume_level(at, 0, 16, 8, 8, 1); ++ at += volume_level(at, 1, 4, 4, 8, 1); ++ volume_level(at, 2, 1, 2, 8, 1); ++ bind_volume(0x86, 16, 16, 8, 3); ++ draw_triangle(); ++ static const u32 blocks[VOL_MIPS] = {16, 4, 1}, slices[VOL_MIPS] = {8, 4, 2}, rows[VOL_MIPS] = {32, 16, 8}; ++ ok = g_vol.n_create == 1 && g_vol.n_upload == 8 + 4 + 2; ++ for (u32 lv = 0; lv < VOL_MIPS && ok; lv++) { ++ ok &= g_vol.row_bytes[lv] == rows[lv]; ++ for (u32 z = 0; z < slices[lv]; z++) ++ for (u32 i = 0; i < blocks[lv]; i++) ok &= volume_block_is(lv, z, i, 8); ++ } ++ CHECK(ok, "a DXT1 volume's every level goes up out of its own VTC order " ++ "(%d created, %d uploads)", g_vol.n_create, g_vol.n_upload); ++ engine_down(); ++} ++ + static void test_pipeline_key(void) + { + printf("-- pipeline key\n"); +@@ -2456,6 +2584,7 @@ int main(void) + test_texture_cache(); + test_texture_lookup_memo(); + test_texture_sparse_rehash(); ++ test_compressed_volume(); + test_pipeline_key(); + test_restart_expansion(); + test_indexed_runs(); diff --git a/tasks/sp00nznet__ps3recomp-585/solution/solve.sh b/tasks/sp00nznet__ps3recomp-585/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-585/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-585/task.toml b/tasks/sp00nznet__ps3recomp-585/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2d28205d56105fcee58a13aa1cac31c1862255a9 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-585/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-585" +description = "rsx engine: block-compressed (DXT) 3D textures go up as volumes" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/585" +source_access = "auto" +built_at = "2026-11-16T16:09:59.699921+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:321f76a0cbae8b6bc1736f3ea430d7e1e538007aba113b430a1118f544ba6c1d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "libs/video/rsx_draw_engine.c", + "libs/video/rsx_metal_backend.m", + "libs/video/tests/test_rsx_draw_engine.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 172 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.121808+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-585/tests/capture.py b/tasks/sp00nznet__ps3recomp-585/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-585/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-585/tests/instruction.md b/tasks/sp00nznet__ps3recomp-585/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7715432288fa4d90dfab3f3dd0984f7e5ecbfc8b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-585/tests/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** rsx engine: block-compressed (DXT) 3D textures go up as volumes + +## Description + +A texture unit whose `SET_TEXTURE_FORMAT` dimension is 3 (with a depth in `CONTROL3`) is a volume. The 3D path added in 1ba3657 takes uncompressed formats only, so a DXT volume still went up as a 2D texture made of its first slice-sized bytes. The fragment program, given the unit in the volume mask, declared it `Texture3D` all the same. + +A retail title draws its explosion smoke from 256x256x16 DXT5 volumes in main memory (`SET_TEXTURE_FORMAT` 0x0001883A: dimension 3, DXT45; depth 16), the animation running along the third coordinate. Compressed volumes whose sides are powers of two are stored in NVIDIA's VTC order: the slices go in groups of four, and within a group the four slices' blocks at one position follow each other. Read as one 2D image, the first 64 KB are four slices interleaved block by block, and one of the volumes holds a near-empty first group whose every fourth block is opaque black. The smoke drew as dark translucent squares with hard edges. + +## Change + +- `eng_texture_upload`: block-compressed formats take the 3D path too. + - A level whose width and height are powers of two is in VTC order. `eng_unvtc_3d_slice` lays a slice out of it into the staging rows (the depth % 4 slices left over form a smaller last group). It is written from the [NV_texture_compression_vtc](https://registry.khronos.org/OpenGL/extensions/NV/NV_texture_compression_vtc.txt) spec alone, cited in the source. For full groups it is the spec's `blockIndex`. For the last group the spec's formula stores the slices one after another, which contradicts its prose (4x4x2 and 4x4x3 blocks) when depth % 4 >= 2; the prose is followed. + - Any other level is slice after slice, as RPCS3 treats it. +- Metal `texture_upload_3d`: a block-compressed slice spans its block rows. `bytesPerImage` was row bytes times texel rows, four times the slice. That was harmless while each upload is one slice, but not what the call means. + +## Tests + +- `test_rsx_draw_engine`, a new group with a stub backend that has the 3D calls: + - an 8x8x6 DXT5 volume (a group of four and a group of two) goes up as six slices, every block where its slice put it; + - a 12x4x2 DXT5 volume (not a power of two) goes up slice after slice; + - a 16x16x8 DXT1 volume with three levels (8, 4 and 2 slices) goes up level by level, each out of its own VTC order. +- Each check fails without the change. A VTC order without the last group's own stride also fails, and so do levels not a whole level apart. +- `engine_up` became `engine_up_with(backend)` so a group can bring the engine up on its own backend. +- The group passes under ASan, with clang and with gcc. +- In the title, a per-draw capture traced the squares to the draws that sample those volumes. Their bytes, taken out of VTC order, are the smoke's slices. + +## Provenance + +The first version of `eng_unvtc_3d_slice()` was a port of RPCS3's `copy_unmodified_block_vtc`; the licence review held the PR for those eight lines. 53d9ecd rewrites them (the earlier version is still in this branch's history, so a squash merge would keep it out of master's) from the Khronos spec alone, without the earlier code in view, and drops the RPCS3 link. A standalone check compared the new function with a direct implementation of the spec's `blockIndex` for every block of eleven volumes (depth % 4 of 0 or 1) and with the prose layout for depths 1-7, 10 and 11, at 8 and 16 bytes per block, under ASan and UBSan. The three volume tests above pass unchanged. + +v0.18.0 merged in (acc93bb): the volume path keeps master's `!into` condition (no 3D path for an upload into an existing texture). On this branch (macOS arm64) ctest passes (22 of 22) and so do the `tools/test_*.py` scripts (120 of 120). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-585/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-585/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..abe65248188313c76ad7110e42d76f12710d961d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-585/tests/oracle.patch @@ -0,0 +1,238 @@ +diff --git a/libs/video/rsx_draw_engine.c b/libs/video/rsx_draw_engine.c +index 8dff6011..b1995174 100644 +--- a/libs/video/rsx_draw_engine.c ++++ b/libs/video/rsx_draw_engine.c +@@ -1165,6 +1165,27 @@ static void eng_deswizzle_3d_slice(u8* dst, const u8* src, u32 w, u32 h, u32 d, + src + (size_t)rsx_swizzle_offset_3d(x, y, z, lw, lh, ld) * bpp, bpp); + } + ++/* Slice z of a block-compressed 3D level in NVIDIA's VTC layout ++ * (https://registry.khronos.org/OpenGL/extensions/NV/NV_texture_compression_vtc.txt), ++ * into dst in plain S3TC order. Slices go in groups of four, and each 4x4x4 ++ * block is four consecutive 4x4 blocks, one per layer; the d % 4 slices left ++ * over form a last group of 4x4x1, 4x4x2 or 4x4x3 blocks. So block i of slice ++ * z is at (4 * floor(z / 4) * blocks + i * n + z % 4) * block_bytes, n the ++ * layer count of z's group. For full groups that is the spec's blockIndex; for ++ * the last group the spec's formula stores the slices one after another, which ++ * contradicts its prose for d % 4 >= 2, and the prose is followed. `blocks` is ++ * the blocks in one slice. Only a volume whose width and height are powers of ++ * two is stored this way; any other is slice after slice. */ ++static void eng_unvtc_3d_slice(u8* dst, const u8* src, u32 blocks, u32 d, u32 z, u32 block_bytes) ++{ ++ const u32 group = z & ~3u; ++ const u32 n = group + 4 <= d ? 4 : d - group; ++ const u8* base = src + (size_t)group * blocks * block_bytes; ++ for (u32 i = 0; i < blocks; i++) ++ memcpy(dst + (size_t)i * block_bytes, ++ base + ((size_t)i * n + (z & 3)) * block_bytes, block_bytes); ++} ++ + /* One hash per cached texture per presented frame. Word-at-a-time FNV over + * the whole span is deliberately cheap: this is a mutation detector, not a + * content id (rsx_live_draw.c:2002-2026). */ +@@ -1248,9 +1269,12 @@ static u32 eng_texture_upload(u32 location, u32 offset, u32 fmt, u32 w, u32 h, + if (!nlv || !lv[0].tl.face_bytes) return 0; + /* A volume: every slice of every level decoded and uploaded on its own. + * inFAMOUS 2's occlusion volumes read an 8x8x8 cone LUT; uploaded as its +- * first slice and sampled in 2D it darkened whole boxes round every prop. */ ++ * first slice and sampled in 2D it darkened whole boxes round every prop. ++ * A DXT volume too: a retail title's explosion smoke is a 256x256x16 DXT5 ++ * animation, and its first 64 KB read as one 2D image (four slices' ++ * blocks interleaved) drew dark squares where the smoke was. */ + if (!into && depth > 1 && !cube && g.be->texture_create_3d && g.be->texture_upload_3d && +- !lv[0].tl.compressed && lv[0].tl.bytes_per_texel) { ++ (lv[0].tl.compressed || lv[0].tl.bytes_per_texel)) { + const u32 span = eng_texture_span_3d(fmt, w, h, depth, levels, pitch); + const u8* src = eng_guest_ptr(NULL, location, offset, span); + if (!src) return 0; +@@ -1261,13 +1285,19 @@ static u32 eng_texture_upload(u32 location, u32 offset, u32 fmt, u32 w, u32 h, + u32 d = depth; + for (u32 m = 0; m < nlv; m++) { + const rsx_tex_layout* tl = &lv[m].tl; ++ const int vtc = tl->compressed && !(lv[m].w & (lv[m].w - 1u)) && ++ !(lv[m].h & (lv[m].h - 1u)); + const u32 lin_bytes = tl->swizzled ? tl->row_bytes * tl->rows : 0u; + if (!eng_staging_reserve(tl->dst_row_bytes * tl->rows + lin_bytes)) { + g.be->texture_release(g.be->user, handle); + return 0; + } + for (u32 z = 0; z < d; z++) { +- if (tl->swizzled) { ++ if (vtc) { ++ /* Block rows go up as they are (rsx_texture_decode only copies them). */ ++ eng_unvtc_3d_slice(g.tex_staging, level_src, tl->face_bytes / tl->block_bytes, d, z, ++ tl->block_bytes); ++ } else if (tl->swizzled) { + u8* lin = g.tex_staging + tl->dst_row_bytes * tl->rows; + eng_deswizzle_3d_slice(lin, level_src, lv[m].w, lv[m].h, d, z, tl->bytes_per_texel); + rsx_tex_layout ltl = *tl; ltl.swizzled = 0; +diff --git a/libs/video/rsx_metal_backend.m b/libs/video/rsx_metal_backend.m +index ad8db0b5..8fe1839b 100644 +--- a/libs/video/rsx_metal_backend.m ++++ b/libs/video/rsx_metal_backend.m +@@ -3113,12 +3113,17 @@ static void eng_texture_upload_3d(void* user, u32 handle, u32 z, u32 mip, + (void)user; + id t = eng_obj(handle); + if (!t || !src || !row_bytes) return; ++ /* A block-compressed slice is rows of 4x4 blocks. */ ++ const MTLPixelFormat pf = [t pixelFormat]; ++ const int bc = pf == MTLPixelFormatBC1_RGBA || pf == MTLPixelFormatBC2_RGBA || ++ pf == MTLPixelFormatBC3_RGBA; ++ const u32 rows = bc ? (h + 3u) / 4u : h; + [t replaceRegion:MTLRegionMake3D(0, 0, z, w, h, 1) + mipmapLevel:mip + slice:0 + withBytes:src + bytesPerRow:row_bytes +- bytesPerImage:(NSUInteger)row_bytes * h]; ++ bytesPerImage:(NSUInteger)row_bytes * rows]; + } + + static u32 eng_color_target_create(void* user, rsx_be_format fmt, u32 w, u32 h, +diff --git a/libs/video/tests/test_rsx_draw_engine.c b/libs/video/tests/test_rsx_draw_engine.c +index 8099901a..6b1b4514 100644 +--- a/libs/video/tests/test_rsx_draw_engine.c ++++ b/libs/video/tests/test_rsx_draw_engine.c +@@ -796,6 +796,134 @@ static void test_texture_sparse_rehash(void) + + /* ---- 4. the pipeline key ------------------------------------------------- */ + ++/* A block-compressed volume (dimension 3, DXT) goes up slice by slice as a ++ * 3D texture. A retail title's explosion smoke is a 256x256x16 DXT5 volume; ++ * uploaded as the 2D image its first 64 KB make, it drew dark squares. */ ++#define VOL_MIPS 3 ++#define VOL_SLICES 8 ++static struct { ++ int n_create, n_upload; ++ u32 depth, row_bytes[VOL_MIPS]; ++ u8 slice[VOL_MIPS][VOL_SLICES][128]; /* the first bytes of each slice's upload */ ++} g_vol; ++ ++static u32 stub_texture_create_3d(void* u, rsx_be_format f, u32 w, u32 h, u32 depth, ++ u32 mips, u32 remap, u32 rsx_fmt) ++{ ++ g_vol.n_create++; ++ g_vol.depth = depth; ++ return stub_texture_create(u, f, w, h, mips, 1, remap, rsx_fmt); ++} ++ ++static void stub_texture_upload_3d(void* u, u32 t, u32 z, u32 mip, u32 w, u32 h, ++ const void* src, u32 row_bytes) ++{ ++ (void)u; (void)t; (void)w; ++ g_vol.n_upload++; ++ if (mip >= VOL_MIPS || z >= VOL_SLICES || !src) return; ++ g_vol.row_bytes[mip] = row_bytes; ++ const u32 bytes = row_bytes * ((h + 3u) / 4u); /* one slice of block rows */ ++ memcpy(g_vol.slice[mip][z], src, bytes < 128u ? bytes : 128u); ++} ++ ++/* Block i of slice z of level m, as the volume's guest bytes mark it. */ ++static int volume_block_is(u32 m, u32 z, u32 i, u32 block_bytes) ++{ ++ const u8* b = g_vol.slice[m][z] + i * block_bytes; ++ return b[0] == (u8)(0xA0u + m * 0x10u + z) && b[1] == (u8)i; ++} ++ ++/* Lay level m (w x h blocks, d slices) out at `at` in VTC order (power-of-two ++ * sides) or slice after slice, each block marked with its level, slice and ++ * index. Returns the level's size. */ ++static u32 volume_level(u32 at, u32 m, u32 blocks, u32 d, u32 block_bytes, int vtc) ++{ ++ const u32 full = d & ~3u; ++ for (u32 z = 0; z < d; z++) ++ for (u32 i = 0; i < blocks; i++) { ++ u32 n = z * blocks + i; ++ if (vtc) { ++ const u32 group = z < full ? z & ~3u : full, stride = z < full ? 4u : d - full; ++ n = group * blocks + i * stride + (z - group); ++ } ++ vm_base[at + n * block_bytes] = (u8)(0xA0u + m * 0x10u + z); ++ vm_base[at + n * block_bytes + 1u] = (u8)i; ++ } ++ return blocks * d * block_bytes; ++} ++ ++static void bind_volume(u32 fmt, u32 w, u32 h, u32 depth, u32 mips) ++{ ++ m(M_TEX_UNIT + 0x00, TEX_OFFSET); ++ m(M_TEX_UNIT + 0x04, 2u | (3u << 4) | (fmt << 8) | (mips << 16)); /* main, 3D */ ++ m(M_TEX_UNIT + 0x0C, 0x80000000u); ++ m(M_TEX_UNIT + 0x10, 0xAAE4u); ++ m(M_TEX_UNIT + 0x18, (w << 16) | h); ++ m(0x1840 /* control3 */, depth << 20); ++} ++ ++static void test_compressed_volume(void) ++{ ++ printf("-- compressed volume\n"); ++ rsx_draw_backend be = g_stub_backend; ++ be.texture_create_3d = stub_texture_create_3d; ++ be.texture_upload_3d = stub_texture_upload_3d; ++ ++ /* 8x8x6 DXT5: four blocks a slice. Power-of-two sides, so VTC order: ++ * slices 0-3 interleaved block by block, then 4-5 the same way. */ ++ engine_up_with(&be); ++ memset(&g_vol, 0, sizeof g_vol); ++ memset(vm_base + TEX_OFFSET, 0, 0x1000); ++ volume_level(TEX_OFFSET, 0, 4, 6, 16, 1); ++ bind_volume(0x88, 8, 8, 6, 1); ++ draw_triangle(); ++ int ok = g_vol.n_create == 1 && g_vol.depth == 6 && g_vol.n_upload == 6 && g_vol.row_bytes[0] == 32; ++ for (u32 z = 0; z < 6 && ok; z++) ++ for (u32 i = 0; i < 4; i++) ok &= volume_block_is(0, z, i, 16); ++ CHECK(ok, "a power-of-two DXT5 volume goes up as 6 slices out of VTC order " ++ "(%d created, depth %u, %d uploads, row %u)", ++ g_vol.n_create, g_vol.depth, g_vol.n_upload, g_vol.row_bytes[0]); ++ engine_down(); ++ ++ /* 12x4x2: not a power of two, so slice after slice as they lie. */ ++ engine_up_with(&be); ++ memset(&g_vol, 0, sizeof g_vol); ++ memset(vm_base + TEX_OFFSET, 0, 0x1000); ++ volume_level(TEX_OFFSET, 0, 3, 2, 16, 0); ++ bind_volume(0x88, 12, 4, 2, 1); ++ draw_triangle(); ++ ok = g_vol.n_create == 1 && g_vol.n_upload == 2 && g_vol.row_bytes[0] == 48; ++ for (u32 z = 0; z < 2 && ok; z++) ++ for (u32 i = 0; i < 3; i++) ok &= volume_block_is(0, z, i, 16); ++ CHECK(ok, "a non-power-of-two DXT5 volume goes up slice after slice " ++ "(%d created, %d uploads, row %u)", ++ g_vol.n_create, g_vol.n_upload, g_vol.row_bytes[0]); ++ engine_down(); ++ ++ /* 16x16x8 DXT1 with three levels: 16 blocks x 8 slices (two groups of ++ * four), 4 blocks x 4 slices (one group), 1 block x 2 slices (a group of ++ * two), each level in VTC order after the one before. */ ++ engine_up_with(&be); ++ memset(&g_vol, 0, sizeof g_vol); ++ memset(vm_base + TEX_OFFSET, 0, 0x1000); ++ u32 at = TEX_OFFSET; ++ at += volume_level(at, 0, 16, 8, 8, 1); ++ at += volume_level(at, 1, 4, 4, 8, 1); ++ volume_level(at, 2, 1, 2, 8, 1); ++ bind_volume(0x86, 16, 16, 8, 3); ++ draw_triangle(); ++ static const u32 blocks[VOL_MIPS] = {16, 4, 1}, slices[VOL_MIPS] = {8, 4, 2}, rows[VOL_MIPS] = {32, 16, 8}; ++ ok = g_vol.n_create == 1 && g_vol.n_upload == 8 + 4 + 2; ++ for (u32 lv = 0; lv < VOL_MIPS && ok; lv++) { ++ ok &= g_vol.row_bytes[lv] == rows[lv]; ++ for (u32 z = 0; z < slices[lv]; z++) ++ for (u32 i = 0; i < blocks[lv]; i++) ok &= volume_block_is(lv, z, i, 8); ++ } ++ CHECK(ok, "a DXT1 volume's every level goes up out of its own VTC order " ++ "(%d created, %d uploads)", g_vol.n_create, g_vol.n_upload); ++ engine_down(); ++} ++ + static void test_pipeline_key(void) + { + printf("-- pipeline key\n"); +@@ -2456,6 +2584,7 @@ int main(void) + test_texture_cache(); + test_texture_lookup_memo(); + test_texture_sparse_rehash(); ++ test_compressed_volume(); + test_pipeline_key(); + test_restart_expansion(); + test_indexed_runs(); diff --git a/tasks/sp00nznet__ps3recomp-585/tests/test.sh b/tasks/sp00nznet__ps3recomp-585/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-585/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-585/tests/verifier.py b/tasks/sp00nznet__ps3recomp-585/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-585/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-596/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-596/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e58bcfa58777d72bba591f37e690838b686d5be --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-596/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a6d76c895f77eb30b90a806c830544e61821b77f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a6d76c895f77eb30b90a806c830544e61821b77f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a6d76c895f77eb30b90a806c830544e61821b77f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-596/instruction.md b/tasks/sp00nznet__ps3recomp-596/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3e2125291d021d16ae9e025cad7d0648b85f5ceb --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-596/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** ppu_thread: backfill the main thread's stack addr/size after register_main + +## Description + +`ppu_thread_register_main()` memset()s the whole thread-table slot and nothing ever fills the stack fields back in, so `sys_ppu_thread_get_stack_information` (49) finds tid 1 with stack_addr/stack_size == 0 and reports a {0,0} stack. + +Observed with RPCS3's `dump_stack` test ELF, which queries its own stack and writes what it gets to a file: on this runtime the {0,0} report made the guest call `cellFsWrite(fd, NULL, 0)` and produce an empty file, while lv2/RPCS3 report the real region (base 0xD0010000, 1 MB) and the file comes out full-size. + +Fix: new `ppu_thread_set_main_stack()`, called from `ppu_run()` once the boot harness has chosen the main stack. Two files, twenty-three lines; no table layout or ABI change — it fills fields that were always zero for tid 1, and the registered-but-zero state is not observable any other way. + +Verified against RPCS3 with the same ELF: both runs now write a 1,048,576-byte stack mirror, and all 26 code/data return addresses in it (TOC, every dump_stack function) are identical across the two. The remaining differences are environmental by construction — argv[0] path, stack address range, and RPCS3's HLE trampolines pushing extra frames onto the guest stack — so a byte-identical mirror is not reachable for this test on any two hosts. The fs_probe regression still exits 0 with byte-identical sys_fs output. + +Environment: Windows 11, Visual Studio 18 Community (cl 19.50), x64. clang/GCC builds are unaffected by construction (plain C99 calling the table helpers already in this file). + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-596/solution/patch.diff b/tasks/sp00nznet__ps3recomp-596/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3ffce9e6722b1677d960a3bc2004d7cdf8aaf6b0 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-596/solution/patch.diff @@ -0,0 +1,45 @@ +diff --git a/runtime/ppu/ppu_loader.cpp b/runtime/ppu/ppu_loader.cpp +index f54150d9..05ddcaf5 100644 +--- a/runtime/ppu/ppu_loader.cpp ++++ b/runtime/ppu/ppu_loader.cpp +@@ -3821,6 +3821,11 @@ extern "C" int ppu_run(uint32_t entry_opd, uint32_t stack_top) + * and concurrently-emitted fences vanished (the boot-loading stall). */ + { extern uint64_t ppu_thread_register_main(void); + ctx.thread_id = ppu_thread_register_main(); } ++ /* register_main() leaves stack_addr/stack_size zeroed; sys_ppu_thread_ ++ * get_stack_information(49) would report a {0,0} stack for the main ++ * thread. Backfill the real region now that the harness chose it. */ ++ { extern void ppu_thread_set_main_stack(uint32_t, uint32_t); ++ ppu_thread_set_main_stack(stack_top - VM_PPU_STACK_SIZE, VM_PPU_STACK_SIZE); } + /* For samplers on other threads (a port's periodic stack dump): the main + * thread's context lives on this frame, not in the thread table. */ + g_ppu_main_ctx = &ctx; +diff --git a/runtime/syscalls/sys_ppu_thread.c b/runtime/syscalls/sys_ppu_thread.c +index c64b0b8d..b4f78cdc 100644 +--- a/runtime/syscalls/sys_ppu_thread.c ++++ b/runtime/syscalls/sys_ppu_thread.c +@@ -264,6 +264,24 @@ uint64_t ppu_thread_register_main(void) + return 1; + } + ++/* Fill in the main thread's stack fields after the boot harness has chosen ++ * where the stack lives. register_main() memset()s the whole struct, so ++ * without this sys_ppu_thread_get_stack_information(49) finds tid 1 in the ++ * table with stack_addr/stack_size == 0 and reports a {0,0} stack -- a guest ++ * that dumps its own stack (RPCS3's dump_stack test) then calls ++ * cellFsWrite(fd, NULL, 0) and produces an empty file while the real kernel ++ * reports the actual region. RPCS3's main stack: base 0xD0010000, 1 MB. */ ++void ppu_thread_set_main_stack(uint32_t stack_base, uint32_t stack_size) ++{ ++ table_lock(); ++ ppu_thread_info* t = &g_ppu_threads[0]; ++ if (t->state != PPU_THREAD_STATE_FREE) { ++ t->stack_addr = stack_base; ++ t->stack_size = stack_size; ++ } ++ table_unlock(); ++} ++ + /* --------------------------------------------------------------------------- + * sys_ppu_thread_create + * diff --git a/tasks/sp00nznet__ps3recomp-596/solution/solve.sh b/tasks/sp00nznet__ps3recomp-596/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-596/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-596/task.toml b/tasks/sp00nznet__ps3recomp-596/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8c57b5dfcc3681498223a2cf8e8457481d9b915d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-596/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-596" +description = "ppu_thread: backfill the main thread's stack addr/size after register_main" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "a6d76c895f77eb30b90a806c830544e61821b77f" +reference = "https://github.com/sp00nznet/ps3recomp/pull/596" +source_access = "auto" +built_at = "2026-11-16T16:09:59.698144+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:583a13fb1d702fc60770732108bf5314c35a044da6d4b65284d22a40034d65c2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "runtime/ppu/ppu_loader.cpp", + "runtime/syscalls/sys_ppu_thread.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 23 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.122333+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e2d4ecd99865fba2b0acaedf729ae5691dbf66db8344addc4011979442884be1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-596/tests/capture.py b/tasks/sp00nznet__ps3recomp-596/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-596/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-596/tests/instruction.md b/tasks/sp00nznet__ps3recomp-596/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3e2125291d021d16ae9e025cad7d0648b85f5ceb --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-596/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** ppu_thread: backfill the main thread's stack addr/size after register_main + +## Description + +`ppu_thread_register_main()` memset()s the whole thread-table slot and nothing ever fills the stack fields back in, so `sys_ppu_thread_get_stack_information` (49) finds tid 1 with stack_addr/stack_size == 0 and reports a {0,0} stack. + +Observed with RPCS3's `dump_stack` test ELF, which queries its own stack and writes what it gets to a file: on this runtime the {0,0} report made the guest call `cellFsWrite(fd, NULL, 0)` and produce an empty file, while lv2/RPCS3 report the real region (base 0xD0010000, 1 MB) and the file comes out full-size. + +Fix: new `ppu_thread_set_main_stack()`, called from `ppu_run()` once the boot harness has chosen the main stack. Two files, twenty-three lines; no table layout or ABI change — it fills fields that were always zero for tid 1, and the registered-but-zero state is not observable any other way. + +Verified against RPCS3 with the same ELF: both runs now write a 1,048,576-byte stack mirror, and all 26 code/data return addresses in it (TOC, every dump_stack function) are identical across the two. The remaining differences are environmental by construction — argv[0] path, stack address range, and RPCS3's HLE trampolines pushing extra frames onto the guest stack — so a byte-identical mirror is not reachable for this test on any two hosts. The fs_probe regression still exits 0 with byte-identical sys_fs output. + +Environment: Windows 11, Visual Studio 18 Community (cl 19.50), x64. clang/GCC builds are unaffected by construction (plain C99 calling the table helpers already in this file). + +## Task + +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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-596/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-596/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3ffce9e6722b1677d960a3bc2004d7cdf8aaf6b0 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-596/tests/oracle.patch @@ -0,0 +1,45 @@ +diff --git a/runtime/ppu/ppu_loader.cpp b/runtime/ppu/ppu_loader.cpp +index f54150d9..05ddcaf5 100644 +--- a/runtime/ppu/ppu_loader.cpp ++++ b/runtime/ppu/ppu_loader.cpp +@@ -3821,6 +3821,11 @@ extern "C" int ppu_run(uint32_t entry_opd, uint32_t stack_top) + * and concurrently-emitted fences vanished (the boot-loading stall). */ + { extern uint64_t ppu_thread_register_main(void); + ctx.thread_id = ppu_thread_register_main(); } ++ /* register_main() leaves stack_addr/stack_size zeroed; sys_ppu_thread_ ++ * get_stack_information(49) would report a {0,0} stack for the main ++ * thread. Backfill the real region now that the harness chose it. */ ++ { extern void ppu_thread_set_main_stack(uint32_t, uint32_t); ++ ppu_thread_set_main_stack(stack_top - VM_PPU_STACK_SIZE, VM_PPU_STACK_SIZE); } + /* For samplers on other threads (a port's periodic stack dump): the main + * thread's context lives on this frame, not in the thread table. */ + g_ppu_main_ctx = &ctx; +diff --git a/runtime/syscalls/sys_ppu_thread.c b/runtime/syscalls/sys_ppu_thread.c +index c64b0b8d..b4f78cdc 100644 +--- a/runtime/syscalls/sys_ppu_thread.c ++++ b/runtime/syscalls/sys_ppu_thread.c +@@ -264,6 +264,24 @@ uint64_t ppu_thread_register_main(void) + return 1; + } + ++/* Fill in the main thread's stack fields after the boot harness has chosen ++ * where the stack lives. register_main() memset()s the whole struct, so ++ * without this sys_ppu_thread_get_stack_information(49) finds tid 1 in the ++ * table with stack_addr/stack_size == 0 and reports a {0,0} stack -- a guest ++ * that dumps its own stack (RPCS3's dump_stack test) then calls ++ * cellFsWrite(fd, NULL, 0) and produces an empty file while the real kernel ++ * reports the actual region. RPCS3's main stack: base 0xD0010000, 1 MB. */ ++void ppu_thread_set_main_stack(uint32_t stack_base, uint32_t stack_size) ++{ ++ table_lock(); ++ ppu_thread_info* t = &g_ppu_threads[0]; ++ if (t->state != PPU_THREAD_STATE_FREE) { ++ t->stack_addr = stack_base; ++ t->stack_size = stack_size; ++ } ++ table_unlock(); ++} ++ + /* --------------------------------------------------------------------------- + * sys_ppu_thread_create + * diff --git a/tasks/sp00nznet__ps3recomp-596/tests/test.sh b/tasks/sp00nznet__ps3recomp-596/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c6cfc71bd176c79953c06925c479540ee73a8b6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-596/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a6d76c895f77eb30b90a806c830544e61821b77f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-596/tests/verifier.py b/tasks/sp00nznet__ps3recomp-596/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-596/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-597/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-597/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-597/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-597/instruction.md b/tasks/sp00nznet__ps3recomp-597/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..de57b528e72183b89f73d5e22ef7a8f79601dc3c --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-597/instruction.md @@ -0,0 +1,53 @@ +# Issue + +**Title:** rsx_vertex_fetch: expand missing attribute components (w = 1.0f) + +## Description + +## Why + +When an application binds a vertex attribute array with fewer than 4 components (such as standard 3-component position streams `(x, y, z)`), missing components must expand according to standard graphics hardware conventions: +- Missing `y, z` expand to `0.0f` +- Missing `w` expands to `1.0f` + +In titles that clear or leave uninitialized the constant attribute registers (`vertex_data4f` = 0), a 3-component position array left `w = 0.0f`. Following perspective transformation in vertex programs, clip-space `w` evaluated to `0.0f`. As a result, the GPU hardware clipper culled all triangles, resulting in complete geometry starvation (0 visible primitives despite hundreds of valid draw calls). + +--- + +## Change + +In `libs/video/rsx_vertex_fetch.c` (`rsx_fetch_attrib`): +- Explicitly enforce component expansion rules when attribute component count `n < 4`: + - `if (n < 4) out[3] = 1.0f;` + - `if (n < 3) out[2] = 0.0f;` + - `if (n < 2) out[1] = 0.0f;` + +--- + +## Evidence + +### Before vs. With this change + +| Behavior | Before | With this change | +|---|---|---| +| Attribute expansion for `n < 4` | Uninitialized / `0.0f` from constant storage | Missing `y, z = 0.0f`, missing `w = 1.0f` | +| Clip-space `w` | `w = 0.0f` -> 100% triangles culled by hardware clipper | `w = 1.0f` -> 685 draw calls pass clipper and rasterize onto target | +| Visual Output | Completely empty / black frame | Scene geometry successfully rasterized | + +### Visual Verification + +![Scene Geometry Rasterized](https://raw.githubusercontent.com/DriifterSelf/ps3recomp/evidence-assets/scene_geometry.png) + +*685 draw calls rasterizing scene geometry into offscreen render targets following proper component expansion.* + +--- + +## AI Assistance & Clean-Room Compliance + +In accordance with upstream guidelines ([`CONTRIBUTORS.md#a-note-on-ai-assisted-contributions`](CONTRIBUTORS.md#a-note-on-ai-assisted-contributions)): +- This PR was authored with AI assistance (Antigravity), directed and verified against hardware specifications and runtime telemetry. +- Clean-room implementation: strictly adheres to standard graphics pipeline specifications; no code copied or adapted from RPCS3 or other GPL emulators. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-597/solution/patch.diff b/tasks/sp00nznet__ps3recomp-597/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0c6db1206bae7e1ef6697c861279792662302544 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-597/solution/patch.diff @@ -0,0 +1,19 @@ +diff --git a/libs/video/rsx_vertex_fetch.c b/libs/video/rsx_vertex_fetch.c +index bd31518d..7d08c22b 100644 +--- a/libs/video/rsx_vertex_fetch.c ++++ b/libs/video/rsx_vertex_fetch.c +@@ -124,4 +124,14 @@ void rsx_fetch_attrib(const rsx_state* st, int idx, u32 vi, float out[4]) + for (u32 k = 0; k < n; k++) out[k] = rsx_rd_bef(p + k * 4); + break; + } ++ ++ /* When an attribute array is enabled with fewer than 4 components, ++ * missing components expand according to standard graphics hardware rules: ++ * missing y,z = 0.0, missing w = 1.0. A game may clear the constant ++ * register vertex_data4f to all zeros; leaving w=0 on a 3-component position ++ * array drops translation in the vertex shader and produces clip-space w=0, ++ * which causes the hardware clipper to discard every vertex. */ ++ if (n < 4) out[3] = 1.0f; ++ if (n < 3) out[2] = 0.0f; ++ if (n < 2) out[1] = 0.0f; + } diff --git a/tasks/sp00nznet__ps3recomp-597/solution/solve.sh b/tasks/sp00nznet__ps3recomp-597/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-597/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-597/task.toml b/tasks/sp00nznet__ps3recomp-597/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..88058c47bdb48a6d6a92ddc91f0451c0f1cf8883 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-597/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-597" +description = "rsx_vertex_fetch: expand missing attribute components (w = 1.0f)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/597" +source_access = "auto" +built_at = "2026-11-16T16:09:59.696634+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:204e37ff747900a6a4819dc283de1c1c998b3886ff44815643db57048ff96cda" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "libs/video/rsx_vertex_fetch.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 10 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.122851+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-597/tests/capture.py b/tasks/sp00nznet__ps3recomp-597/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-597/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-597/tests/instruction.md b/tasks/sp00nznet__ps3recomp-597/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..de57b528e72183b89f73d5e22ef7a8f79601dc3c --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-597/tests/instruction.md @@ -0,0 +1,53 @@ +# Issue + +**Title:** rsx_vertex_fetch: expand missing attribute components (w = 1.0f) + +## Description + +## Why + +When an application binds a vertex attribute array with fewer than 4 components (such as standard 3-component position streams `(x, y, z)`), missing components must expand according to standard graphics hardware conventions: +- Missing `y, z` expand to `0.0f` +- Missing `w` expands to `1.0f` + +In titles that clear or leave uninitialized the constant attribute registers (`vertex_data4f` = 0), a 3-component position array left `w = 0.0f`. Following perspective transformation in vertex programs, clip-space `w` evaluated to `0.0f`. As a result, the GPU hardware clipper culled all triangles, resulting in complete geometry starvation (0 visible primitives despite hundreds of valid draw calls). + +--- + +## Change + +In `libs/video/rsx_vertex_fetch.c` (`rsx_fetch_attrib`): +- Explicitly enforce component expansion rules when attribute component count `n < 4`: + - `if (n < 4) out[3] = 1.0f;` + - `if (n < 3) out[2] = 0.0f;` + - `if (n < 2) out[1] = 0.0f;` + +--- + +## Evidence + +### Before vs. With this change + +| Behavior | Before | With this change | +|---|---|---| +| Attribute expansion for `n < 4` | Uninitialized / `0.0f` from constant storage | Missing `y, z = 0.0f`, missing `w = 1.0f` | +| Clip-space `w` | `w = 0.0f` -> 100% triangles culled by hardware clipper | `w = 1.0f` -> 685 draw calls pass clipper and rasterize onto target | +| Visual Output | Completely empty / black frame | Scene geometry successfully rasterized | + +### Visual Verification + +![Scene Geometry Rasterized](https://raw.githubusercontent.com/DriifterSelf/ps3recomp/evidence-assets/scene_geometry.png) + +*685 draw calls rasterizing scene geometry into offscreen render targets following proper component expansion.* + +--- + +## AI Assistance & Clean-Room Compliance + +In accordance with upstream guidelines ([`CONTRIBUTORS.md#a-note-on-ai-assisted-contributions`](CONTRIBUTORS.md#a-note-on-ai-assisted-contributions)): +- This PR was authored with AI assistance (Antigravity), directed and verified against hardware specifications and runtime telemetry. +- Clean-room implementation: strictly adheres to standard graphics pipeline specifications; no code copied or adapted from RPCS3 or other GPL emulators. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-597/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-597/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0c6db1206bae7e1ef6697c861279792662302544 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-597/tests/oracle.patch @@ -0,0 +1,19 @@ +diff --git a/libs/video/rsx_vertex_fetch.c b/libs/video/rsx_vertex_fetch.c +index bd31518d..7d08c22b 100644 +--- a/libs/video/rsx_vertex_fetch.c ++++ b/libs/video/rsx_vertex_fetch.c +@@ -124,4 +124,14 @@ void rsx_fetch_attrib(const rsx_state* st, int idx, u32 vi, float out[4]) + for (u32 k = 0; k < n; k++) out[k] = rsx_rd_bef(p + k * 4); + break; + } ++ ++ /* When an attribute array is enabled with fewer than 4 components, ++ * missing components expand according to standard graphics hardware rules: ++ * missing y,z = 0.0, missing w = 1.0. A game may clear the constant ++ * register vertex_data4f to all zeros; leaving w=0 on a 3-component position ++ * array drops translation in the vertex shader and produces clip-space w=0, ++ * which causes the hardware clipper to discard every vertex. */ ++ if (n < 4) out[3] = 1.0f; ++ if (n < 3) out[2] = 0.0f; ++ if (n < 2) out[1] = 0.0f; + } diff --git a/tasks/sp00nznet__ps3recomp-597/tests/test.sh b/tasks/sp00nznet__ps3recomp-597/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-597/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-597/tests/verifier.py b/tasks/sp00nznet__ps3recomp-597/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-597/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-600/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-600/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-600/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-600/instruction.md b/tasks/sp00nznet__ps3recomp-600/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d5fc04118b96213bd4a832a085bbe75301668439 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-600/instruction.md @@ -0,0 +1,108 @@ +# Issue + +**Title:** rsx_d3d12: expand descriptor ranges to 16 units, MAX_OFF_RTS to 64, track row pitch, and add D3D12_NO_DBG + +## Description + +## Why + +When executing titles featuring complex deferred rendering pipelines, multi-layer paint shaders, and multi-stage offscreen render-to-texture (RTT) passes (e.g. racing simulations with 6-face dynamic reflection cubemaps, 4-level bloom downsample pyramids, and tonemapping buffers), the D3D12 backend encountered descriptor starvation and heap exhaustion: + +1. **Offscreen Render Target Exhaustion:** Titles allocating 25+ offscreen render surfaces per frame crashed or dropped passes due to the previous limit of `MAX_OFF_RTS = 16`. +2. **RSX Descriptor Range Starvation:** Complex RSX fragment programs bind and sample up to 16 texture units (`rsx_tex[16]`, `rsx_samp[16]`). The hardcoded 4-descriptor root signature table (`t0-t3`) left units `t4-t15` unbound and starved. +3. **Linear Texture Pitch Mismatch:** Linear textures require exact row pitch tracking from `SET_TEXTURE_CONTROL3` (bits 0..19). +4. **FPS Metric Reset:** The FPS counter reset `frame_count = 0` on every 1-second tick rather than taking a delta, distorting frame timing metrics. + +--- + +## Change + +### 1. Descriptor Heap Layout & Arithmetic (`DRAW_SRV_BASE` / `DRAW_SRV_STRIDE`) +- **`DRAW_SRV_BASE = 256`**: + - Offsets the dynamic per-draw SRV windows safely past the static allocations: + - Slots `0..4`: Primary backbuffers and UI atlas textures. + - Slots `5..68`: Offscreen render target SRVs (`RT_SRV_BASE..RT_SRV_BASE + MAX_OFF_RTS`). + - Slots `69..255`: Guard headroom clear of legacy `vp_tex` slots. +- **`DRAW_SRV_STRIDE = 16`**: + - Each recorded draw call gets a contiguous 16-descriptor window mapping units `t0..t15`. +- **Per-Draw Window Count & Total Heap Size**: + - For `MAX_DRAWS = 2048`, the ring provides 2,048 distinct per-draw windows. + - Total shader-visible descriptor heap size: + $$\text{SRV\_HEAP\_SIZE} = \text{DRAW\_SRV\_BASE} + (\text{MAX\_DRAWS} \times \text{DRAW\_SRV\_STRIDE}) = 256 + (2048 \times 16) = 33,024\text{ descriptors}$$ + - **Hardware compatibility:** D3D12 guarantees a minimum of 1,000,000 descriptors in a shader-visible heap for all Tier 1 hardware. At 32 bytes per descriptor, 33,024 descriptors require only $\approx 1.05\text{ MB}$ of VRAM, well within all hardware limits. + +### 2. Multi-Target Capacity (`MAX_OFF_RTS = 64`) +- Scaled `MAX_OFF_RTS` from 16 to 64 to comfortably accommodate 25+ active offscreen targets per frame (6 cubemap faces, 4-stage bloom downsample chains, and intermediate tone mapping buffers). + +### 3. Root Signature & Draw Record Expansion +- Expanded root signature SRV descriptor table and static samplers from 4 to 16 (`t0-t15`, `s0-s15`). +- Expanded `D3D12DrawRecord` to store 16 texture units (`tex[16]`, `tex_rt[16]`) and connected all 16 units throughout `render_frame`, `d3d12_draw_arrays`, and `d3d12_draw_indexed`. + +### 4. Diagnostics & Controls +- Added `D3D12_NO_DBG` knob to disable the D3D12 debug layer even in debug builds, documented for `tools/gen_diagnostics_index.py`. +- Corrected FPS metric calculation to record the delta against `s_last_fps_frame`. +- Tracked linear texture row pitch from `SET_TEXTURE_CONTROL3` (bits 0..19). + +--- + +## Factual Citations & Hardware References + +1. **NVIDIA CineFX 3.0 / G70 Hardware Architecture (16 Sampler Units):** + - *Reference:* [Khronos OpenGL ARB_fragment_program Specification (`MAX_TEXTURE_IMAGE_UNITS = 16`)](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_fragment_program.txt) + - *Hardware Mapping:* The RSX Reality Synthesizer implements 16 independent texture mapping units, addressed in GCM command packets via methods `NV4097_SET_TEXTURE_OFFSET_M` (`0x1A00 + 0x20 * M`) and `NV4097_SET_TEXTURE_FORMAT_M` (`0x1840 + 0x20 * M`) where $M \in [0, 15]$. +2. **Microsoft Direct3D 12 Hardware Tiers Specification (Tier 1 Resource Binding):** + - *Reference:* [Microsoft Learn – D3D12 Hardware Tiers](https://learn.microsoft.com/en-us/windows/win32/direct3d12/hardware-support) + - *Specification limit:* All Direct3D 12 Tier 1 hardware supports a minimum of 1,000,000 descriptors in a shader-visible descriptor heap. Our allocation of 33,024 descriptors utilizes only $3.3\%$ of the minimum Tier 1 hardware ceiling. + +--- + +## Evidence + +### Before vs. With this change + +| Component | Before | With this change | +|---|---|---| +| Offscreen Render Targets | `MAX_OFF_RTS = 16` -> Heap exhaustion on pass 17 | `MAX_OFF_RTS = 64` -> All 25 targets map cleanly | +| Bound Texture Samplers | 4 descriptors (`t0-t3`) -> units 4..15 unbound | 16 descriptors (`t0-t15`) -> all 16 units bound | +| Descriptor Heap Size | 8,224 descriptors | 33,024 descriptors (2,048 windows x 16 units) | +| Linear Texture Row Pitch | Unparsed / default pitch | Tracked from `SET_TEXTURE_CONTROL3` bits 0..19 | +| FPS Counter | Distorted (zeroed every tick) | Accurate frame delta over 1000ms | + +### Telemetry: Multi-Target Allocation Manifest (25 Offscreen Targets) + +``` +frame_count=2712 draws=940 backbuffer=1280x720 +offrt[0] off=0x0F180000 1280x720 dxgi=28 (Main HDR Scene) +offrt[1] off=0x0C0C0000 512x512 dxgi=28 (Cubemap Face 0) +offrt[2] off=0x0C1C0000 512x512 dxgi=28 (Cubemap Face 1) +offrt[3] off=0x0C2C0000 512x512 dxgi=28 (Cubemap Face 2) +offrt[4] off=0x0C4C0000 512x512 dxgi=28 (Cubemap Face 4) +offrt[5] off=0x0C5C0000 512x512 dxgi=28 (Cubemap Face 5) +offrt[6] off=0x0E0C0000 1280x360 dxgi=28 (Bloom Level 1 Downsample) +offrt[7] off=0x0DDC0000 640x360 dxgi=28 (Bloom Level 2 Downsample) +offrt[8] off=0x0DC20000 640x180 dxgi=28 (Bloom Level 3 Downsample) +offrt[9] off=0x0D360000 320x180 dxgi=28 (Bloom Level 4 Downsample) +... +op937 DRAW rt=0x0D7A0000 vp=0,0,1280x720 fp=0x03778001 vs=2 n=3 cmask=F blend=0 t0=0x0F180000 t1=0x0E300000 t2=0x0D360000 t3=0x0BDA0000 +op939 DRAW rt=0x00000000 vp=0,0,1280x720 fp=0x03777701 vs=2 n=3 cmask=F blend=0 t0=0x0D7A0000 t1=0x0E300000 t2=0x0D300000 t3=0x0BDA0000 +``` + +### Visual Verification + +![HUD & Telemetry Dial](https://raw.githubusercontent.com/DriifterSelf/ps3recomp/evidence-assets/hud_dial.png) +*HUD dials and telemetry elements rendering across offscreen composite targets.* + +![Gameplay Composite](https://raw.githubusercontent.com/DriifterSelf/ps3recomp/evidence-assets/gameplay_composite.png) +*Multi-stage offscreen RTT composite pass executing without descriptor exhaustion.* + +--- + +## AI Assistance & Clean-Room Compliance + +In accordance with upstream guidelines ([`CONTRIBUTORS.md#a-note-on-ai-assisted-contributions`](CONTRIBUTORS.md#a-note-on-ai-assisted-contributions)): +- Authored with AI assistance (Antigravity), directed and verified against Direct3D 12 specifications and runtime telemetry. +- Clean-room implementation: all descriptor arithmetic and resource management written specifically for `ps3recomp`; no code copied or adapted from RPCS3 or other GPL emulators. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-600/solution/patch.diff b/tasks/sp00nznet__ps3recomp-600/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e8420fe7cb0df37aef4ee26a873607b680666b08 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-600/solution/patch.diff @@ -0,0 +1,404 @@ +diff --git a/libs/video/rsx_d3d12_backend.c b/libs/video/rsx_d3d12_backend.c +index bc05a308..4f81ae8f 100644 +--- a/libs/video/rsx_d3d12_backend.c ++++ b/libs/video/rsx_d3d12_backend.c +@@ -106,14 +106,16 @@ typedef struct { + u32 mips; /* SET_TEXTURE_FORMAT bits 16..31: mipmap level count. + * Cube faces sit one whole mip pyramid apart, so this + * is what sets the face stride. */ ++ u32 pitch; /* SET_TEXTURE_CONTROL3 bits 0..19: row pitch for linear textures */ + int cube; /* SET_TEXTURE_FORMAT bit 2: a cube texture. Sampled + * with a 3-component direction, not a 2D uv -- treating + * one as 2D is what makes an environment-mapped chrome + * surface come out with black patches and banding. */ + int set; + u32 addr, filter, ctrl0, border; /* TEXTURE_ADDRESS/FILTER/CONTROL0/BORDER_COLOR */ +- } tex[4]; +- int tex_rt[4]; /* pre-pass: OffRT index sampled by unit, -1 = none */ ++ } tex[16]; ++ int tex_rt[16]; /* pre-pass: OffRT index sampled by unit, -1 = none */ ++ int tex_ds[16]; /* pre-pass: OffDS read through unit u (its colour copy is tex_rt), -1 = none */ + int tex_slot; /* legacy single-slot path (atlas); -1 = none */ + int vs_idx; /* VPVSEntry slot for this draw's vertex program (-1 = primary) */ + int blend; /* guest blend enable at draw time */ +@@ -135,7 +137,6 @@ typedef struct { + u32 rt_fmt; /* RSX surface colour format (SET_SURFACE_FORMAT [4:0]) */ + u32 zeta_off; /* depth surface (SET_SURFACE_ZETA_OFFSET) when the surface has one */ + int no_color; /* colour target NONE with a depth surface: a depth-only pass */ +- int tex_ds[4]; /* pre-pass: OffDS read through unit u (its colour copy is tex_rt), -1 = none */ + /* Guest viewport rect at draw time (target pixels). Sub-viewport layouts + * (wave's debug tiles) position quads with this, not with constants -- + * forcing full-target viewports drew every tile window-sized. */ +@@ -166,7 +167,7 @@ typedef struct { + D3D12_RESOURCE_STATES st; /* tracked resource state */ + int used; /* referenced this frame */ + } OffRT; +-#define MAX_OFF_RTS 16 /* demosaic double-buffers its 6-surface pass chain */ ++#define MAX_OFF_RTS 64 /* titles with bloom pyramids and cubemap RTT passes allocate 20+ surfaces */ + + /* Depth surface, one per guest zeta offset. The pass chain keeps several + * (God of War HD: the scene's 2x-AA depth at 0x17F0000 and the resolved depth +@@ -182,13 +183,13 @@ typedef struct { + u64 last_frame; /* frame_count of the last pass that bound it */ + } OffDS; + #define MAX_OFF_DS 6 +-#define DS_SRV_BASE 21 /* SRV heap slots 21..32 hold depth + stencil SRVs (2 per OffDS) */ +-#define RT_SRV_BASE 5 /* SRV heap slots 5..20 hold offscreen-RT SRVs */ +-/* Per-draw SRV windows: each VP draw gets 4 consecutive descriptors (t0-t3) +- * so multi-unit fragment programs see all their textures (demosaic's +- * interpolation passes sample 3 units). */ +-#define DRAW_SRV_BASE 40 +-#define SRV_HEAP_SIZE (DRAW_SRV_BASE + MAX_DRAWS * 4) ++#define RT_SRV_BASE 5 /* SRV heap slots 5..68 hold offscreen-RT SRVs */ ++#define DS_SRV_BASE 70 /* SRV heap slots 70..81 hold depth + stencil SRVs (2 per OffDS) */ ++/* Per-draw SRV windows: each VP draw gets 16 consecutive descriptors (t0-t15) ++ * so multi-unit fragment programs see all their textures. */ ++#define DRAW_SRV_BASE 256 ++#define DRAW_SRV_STRIDE 16 ++#define SRV_HEAP_SIZE (DRAW_SRV_BASE + MAX_DRAWS * DRAW_SRV_STRIDE) + + /* Per-frame VP texture slot: a guest texture uploaded for this frame's VP + * draws (re-uploaded every frame -- gcm/cube's plasma animates in guest +@@ -198,6 +199,7 @@ typedef struct { + ID3D12Resource* res; + ID3D12Resource* up; + u32 off, w, h, fmt; /* current contents (resource reused when dims match) */ ++ u32 pitch; + u32 csum; /* sparse checksum of the source bytes last uploaded */ + int cube; /* resource is a 6-face cube, sampled as TextureCube */ + u32 key; /* the ORIGINAL bound offset -- the cache lookup key. +@@ -208,12 +210,8 @@ typedef struct { + u32 last_frame; /* frame_count when last referenced: the slot least + * recently used is the one given to a new texture */ + } VPTexSlot; +-/* Distinct textures uploadable per frame. Four was enough for a UI/atlas-style +- * frame but not for a scene: this title binds ~20 distinct textures per frame, +- * so every draw past the fourth got slot -1 from vp_upload_tex_slot ("out of +- * slots") and drew UNTEXTURED. That reads as a correctly-lit but solid black +- * object, which is indistinguishable from a missing texture upload. */ +-#define VP_TEX_SLOTS 192 ++/* Distinct textures uploadable per frame. */ ++#define VP_TEX_SLOTS 256 + /* Guest texture uploads are staged in one persistently mapped upload buffer, + * a part per frame in flight, reset when that frame's command allocator is + * (the GPU has finished its copies by then). A committed upload buffer per +@@ -367,9 +365,9 @@ typedef struct { + VPFPEntry vp_fp[VP_FP_CACHE]; /* guest-FP PSO cache */ + int vp_fp_n; + u32 srv_inc; /* CBV_SRV_UAV descriptor size */ +- /* VP path: latest texture bound per unit (t0-t3). */ +- struct { u32 off, raw, w, h, fmt, ctrl1, mips; int cube; int set; +- u32 addr, filter, ctrl0, border; } cur_texs[4]; ++ /* VP path: latest texture bound per unit (t0-t15). */ ++ struct { u32 off, raw, w, h, fmt, ctrl1, mips, pitch; int cube; int set; ++ u32 addr, filter, ctrl0, border; } cur_texs[16]; + /* Guest sampler states, one shader-visible descriptor each (samp_key[i] + * describes descriptor i; 0 and 1 are the defaults for units with none). */ + ID3D12DescriptorHeap* samp_heap; +@@ -722,7 +720,7 @@ static int init_d3d12(u32 width, u32 height) + #ifdef NDEBUG + getenv("D3D12_DBG") + #else +- 1 ++ !getenv("D3D12_NO_DBG") /* D3D12_NO_DBG=1 disables the debug layer in debug builds */ + #endif + ) { + ID3D12Debug* debug_controller = NULL; +@@ -1323,11 +1321,11 @@ static int init_d3d12(u32 width, u32 height) + * t0 and are unaffected. Matching 4 static samplers s0-s3. */ + D3D12_DESCRIPTOR_RANGE srv_range = {0}; + srv_range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; +- srv_range.NumDescriptors = 4; ++ srv_range.NumDescriptors = 16; + srv_range.BaseShaderRegister = 0; + srv_range.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + +- D3D12_ROOT_PARAMETER rp[7] = {0}; ++ D3D12_ROOT_PARAMETER rp[19] = {0}; + rp[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; /* b0 = vp_c bank */ + rp[0].Descriptor.ShaderRegister = 0; + rp[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; +@@ -1339,15 +1337,10 @@ static int init_d3d12(u32 width, u32 height) + rp[2].Descriptor.ShaderRegister = 1; + rp[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + +- /* s0-s3: one sampler table per unit, filled per draw from the guest's +- * TEXTURE_ADDRESS/FILTER/CONTROL0 (vp_sampler). These were four static +- * samplers -- s0 point/clamp for the dbgfont atlas, s1-s3 linear/wrap -- +- * so every unit-0 texture was point-sampled and clamped whatever the +- * title asked for: God of War HD's soldiers wrap their texture atlas +- * (v up to ~2) and drew transparent-black from its clamped bottom row. +- * Units without guest state keep those two defaults. */ +- D3D12_DESCRIPTOR_RANGE samp_range[4] = {0}; +- for (int _s = 0; _s < 4; _s++) { ++ /* s0-s15: one sampler table per unit, filled per draw from the guest's ++ * TEXTURE_ADDRESS/FILTER/CONTROL0 (vp_sampler). */ ++ D3D12_DESCRIPTOR_RANGE samp_range[16] = {0}; ++ for (int _s = 0; _s < 16; _s++) { + samp_range[_s].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER; + samp_range[_s].NumDescriptors = 1; + samp_range[_s].BaseShaderRegister = (UINT)_s; +@@ -1358,7 +1351,7 @@ static int init_d3d12(u32 width, u32 height) + } + + D3D12_ROOT_SIGNATURE_DESC rd = {0}; +- rd.NumParameters = 7; rd.pParameters = rp; ++ rd.NumParameters = 19; rd.pParameters = rp; + rd.NumStaticSamplers = 0; rd.pStaticSamplers = NULL; + rd.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; + +@@ -2847,7 +2840,7 @@ static u32 tex_csum(const u8* base, u32 nbytes) + return h; + } + +-static int vp_upload_tex_slot(u32 off, u32 w, u32 h, u32 fmt, int cube, u32 mips) ++static int vp_upload_tex_slot(u32 off, u32 w, u32 h, u32 fmt, int cube, u32 mips, u32 pitch_arg) + { + /* TEX_BUDGET=: cap texture uploads per frame. Off by default -- it was + * tried against the TDR and does not help, because PERF shows the upload +@@ -2871,7 +2864,7 @@ static int vp_upload_tex_slot(u32 off, u32 w, u32 h, u32 fmt, int cube, u32 mips + * layout.c owns them so the Metal backend can read a guest texture without + * re-deriving any of it. Only the DXGI mapping below is ours. */ + rsx_tex_layout tl; +- rsx_texture_layout(fmt, w, h, &tl); ++ rsx_texture_layout_pitched(fmt, w, h, pitch_arg, &tl); + int argb = (tl.fmt == RSX_TEXFMT_R8G8B8A8); + int dxt = tl.compressed; + /* Compressed rows are counted in blocks, so keep bpp at 1 for the byte +@@ -2906,7 +2899,7 @@ static int vp_upload_tex_slot(u32 off, u32 w, u32 h, u32 fmt, int cube, u32 mips + for (int i = 0; i < VP_TEX_SLOTS; i++) { + VPTexSlot* c = &s_d3d.vp_tex[i]; + if (c->res && c->key == key_off && c->w == w && c->h == h && c->fmt == fmt +- && c->cube == cube) { ++ && c->cube == cube && c->pitch == pitch_arg) { + c->last_frame = s_d3d.frame_count; + if (c->used) return i; /* already bound this frame */ + { static int nocache = -1; /* TEX_NOCACHE=1: always re-upload */ +@@ -3031,6 +3024,7 @@ static int vp_upload_tex_slot(u32 off, u32 w, u32 h, u32 fmt, int cube, u32 mips + if (slot < 0) return -1; + VPTexSlot* t = &s_d3d.vp_tex[slot]; + t->last_frame = s_d3d.frame_count; ++ t->pitch = pitch_arg; + /* The upload buffer's rows hold the DECODED image, so they are sized from + * dst_row_bytes -- w * bpp is the source row, which is narrower for any + * format rsx_texture_decode unpacks. */ +@@ -3041,7 +3035,7 @@ static int vp_upload_tex_slot(u32 off, u32 w, u32 h, u32 fmt, int cube, u32 mips + * the same dimensions would otherwise be reused with 1 array slice while the + * cube path copies 6 subresources and writes a 6x upload buffer -- which + * crashes. */ +- if (t->res && (t->w != w || t->h != h || t->fmt != fmt || t->cube != cube)) { ++ if (t->res && (t->w != w || t->h != h || t->fmt != fmt || t->cube != cube || t->pitch != pitch_arg)) { + t->res->lpVtbl->Release(t->res); t->res = NULL; + if (t->up) { t->up->lpVtbl->Release(t->up); t->up = NULL; } + } +@@ -4704,11 +4698,11 @@ static void render_frame(void) + off_rt_get(dr->rt_mrt[_m], dr->rt_w, dr->rt_h, dr->rt_fmt); + if (dr->is_vp && dr->zeta_off && (dr->rt_off || dr->no_color)) + off_ds_get(dr->zeta_off, dr->rt_w, dr->rt_h); +- for (int _u = 0; _u < 4; _u++) dr->tex_ds[_u] = -1; /* set below for draws */ ++ for (int _u = 0; _u < 16; _u++) dr->tex_ds[_u] = -1; /* set below for draws */ + } + for (u32 _d = 0; _d < s_d3d.draw_count && _d < MAX_DRAWS; _d++) { + const D3D12DrawRecord* dr = &s_d3d.draws[_d]; +- for (int _u = 0; _u < 4 && dr->is_vp && !dr->is_clear; _u++) { ++ for (int _u = 0; _u < 16 && dr->is_vp && !dr->is_clear; _u++) { + const int ds = dr->tex[_u].set ? off_ds_find(dr->tex[_u].raw) : -1; + if (ds < 0) continue; + s_d3d.off_ds[ds].last_frame = s_d3d.frame_count; +@@ -4747,7 +4741,7 @@ static void render_frame(void) + { static int ed = -1; + if (ed < 0) { const char* e = getenv("EMPTYTEX"); ed = e ? atoi(e) : 0; } + extern uint8_t* vm_base; +- if (ed && vm_base) for (int _u = 0; _u < 4; _u++) { ++ if (ed && vm_base) for (int _u = 0; _u < 16; _u++) { + if (!dr->tex[_u].set || !dr->tex[_u].off) continue; + u32 nz = 0, sz = dr->tex[_u].w * dr->tex[_u].h * 4u; + for (u32 i2 = 0; i2 < sz && i2 < 0x20000u; i2 += 997) +@@ -4790,7 +4784,7 @@ static void render_frame(void) + } } + { static int sd = -1; + if (sd < 0) { const char* e = getenv("SCREENTEX"); sd = e ? atoi(e) : 0; } +- if (sd) for (int _u = 0; _u < 4; _u++) ++ if (sd) for (int _u = 0; _u < 16; _u++) + if (dr->tex[_u].set && dr->tex[_u].w == s_d3d.width && + dr->tex[_u].h == s_d3d.height) { + static u32 seen[16]; static int ns = 0; int known = 0; +@@ -4802,12 +4796,12 @@ static void render_frame(void) + dr->tex[_u].fmt, dr->fp_addr, dr->vertex_count, + dr->vp_x, dr->vp_y, dr->vp_w, dr->vp_h, 10); } + } } +- /* Fill this draw's t0-t3 SRV window (DRAW_SRV_BASE + d*4): each unit ++ /* Fill this draw's t0-t15 SRV window (DRAW_SRV_BASE + d*DRAW_SRV_STRIDE): each unit + * resolves to an offscreen RT (sampled directly), an uploaded guest + * texture, or a null SRV. */ + double _sv0 = perf_on() ? perf_now() : 0.0; +- for (int _u = 0; _u < 4; _u++) { +- u32 wslot = DRAW_SRV_BASE + _d * 4 + (u32)_u; ++ for (int _u = 0; _u < DRAW_SRV_STRIDE; _u++) { ++ u32 wslot = DRAW_SRV_BASE + _d * DRAW_SRV_STRIDE + (u32)_u; + dr->tex_rt[_u] = -1; + /* A depth surface read as a texture: its colour copy (made in the + * RT pre-pass), refreshed from the depth buffer just before this +@@ -4876,7 +4870,7 @@ static void render_frame(void) + int _cube = dr->tex[_u].cube && (dr_cube_mask(dr) & (1u << _u)); + int ts = vp_upload_tex_slot(dr->tex[_u].off, dr->tex[_u].w, + dr->tex[_u].h, dr->tex[_u].fmt, +- _cube, dr->tex[_u].mips); ++ _cube, dr->tex[_u].mips, dr->tex[_u].pitch); + if (perf_on()) { s_perf_tex += perf_now() - _tt; s_perf_ntex++; + s_perf_texbytes += (u64)dr->tex[_u].w * dr->tex[_u].h * 4u; } + /* Both forms of the offset are in hand here; the filters +@@ -5100,7 +5094,8 @@ static void render_frame(void) + D3D12_GPU_DESCRIPTOR_HANDLE gh; + s_d3d.srv_heap->lpVtbl->GetGPUDescriptorHandleForHeapStart(s_d3d.srv_heap, &gh); + s_d3d.cmd_list->lpVtbl->SetGraphicsRootDescriptorTable(s_d3d.cmd_list, 1, gh); +- int samp_bound[4] = { -1, -1, -1, -1 }; ++ int samp_bound[16]; ++ for (int _s = 0; _s < 16; _s++) samp_bound[_s] = -1; + D3D12_VERTEX_BUFFER_VIEW vbv; + vbv.BufferLocation = s_d3d.vp_vb->lpVtbl->GetGPUVirtualAddress(s_d3d.vp_vb) + + (u64)s_d3d.vp_parity * MAX_VERTICES * 256; +@@ -5121,7 +5116,7 @@ static void render_frame(void) + for (u32 d = 0; d < s_d3d.draw_count && d < MAX_DRAWS; d++) { + const D3D12DrawRecord* dr = &s_d3d.draws[d]; + if (!dr->is_vp) continue; +- for (int _u = 0; _u < 4; _u++) { ++ for (int _u = 0; _u < 16; _u++) { + const int ds = dr->tex_ds[_u]; + if (ds < 0 || ds == cur_z || s_d3d.off_ds[ds].conv_gen == s_d3d.off_ds[ds].gen) + continue; +@@ -5129,7 +5124,7 @@ static void render_frame(void) + s_d3d.cmd_list->lpVtbl->SetGraphicsRootSignature(s_d3d.cmd_list, s_d3d.vp_root_sig); + { ID3D12DescriptorHeap* hp2[] = { s_d3d.srv_heap, s_d3d.samp_heap }; + s_d3d.cmd_list->lpVtbl->SetDescriptorHeaps(s_d3d.cmd_list, s_d3d.samp_heap ? 2 : 1, hp2); } +- for (int _s = 0; _s < 4; _s++) samp_bound[_s] = -1; ++ for (int _s = 0; _s < 16; _s++) samp_bound[_s] = -1; + force_rebind = 1; + } + /* The reduced-viewport passes (this title's reflection, drawn +@@ -5334,19 +5329,19 @@ static void render_frame(void) + /* Per-draw textures: bind this draw's t0-t3 SRV window. + * Any sampled offscreen RT transitions to PSR first (never + * one of the currently-bound colour targets). */ +- for (int _u = 0; _u < 4; _u++) { ++ for (int _u = 0; _u < 16; _u++) { + int rt = dr->tex_rt[_u]; + if (rt >= 0 && rt != cur_rt && + rt != cur_m[0] && rt != cur_m[1] && rt != cur_m[2]) + off_rt_transition(rt, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + } + D3D12_GPU_DESCRIPTOR_HANDLE gh = gh_base; +- gh.ptr += (u64)(DRAW_SRV_BASE + d * 4) * s_d3d.srv_inc; ++ gh.ptr += (u64)(DRAW_SRV_BASE + d * DRAW_SRV_STRIDE) * s_d3d.srv_inc; + s_d3d.cmd_list->lpVtbl->SetGraphicsRootDescriptorTable(s_d3d.cmd_list, 1, gh); + if (s_d3d.samp_heap) { + D3D12_GPU_DESCRIPTOR_HANDLE sb; + s_d3d.samp_heap->lpVtbl->GetGPUDescriptorHandleForHeapStart(s_d3d.samp_heap, &sb); +- for (int _u = 0; _u < 4; _u++) { ++ for (int _u = 0; _u < 16; _u++) { + const int si = vp_sampler(dr, _u); + if (si == samp_bound[_u]) continue; + samp_bound[_u] = si; +@@ -5948,9 +5943,10 @@ static void d3d12_present(void* ud, u32 buffer_id) + /* FPS tracking */ + ULONGLONG now = GetTickCount64(); + if (now - s_d3d.last_fps_time >= 1000) { +- s_d3d.fps = (u32)s_d3d.frame_count; /* rough estimate */ ++ static u64 s_last_fps_frame = 0; ++ s_d3d.fps = (u32)(s_d3d.frame_count - s_last_fps_frame); ++ s_last_fps_frame = s_d3d.frame_count; + s_d3d.last_fps_time = now; +- s_d3d.frame_count = 0; + } + } + +@@ -7076,7 +7072,7 @@ static void d3d12_draw_arrays(void* ud, u32 primitive, u32 first, u32 count) + dr->alpha_ctl = ((s_d3d.current_rsx_state->alpha_test_enable ? 1u : 0u) << 16) + | ((s_d3d.current_rsx_state->alpha_func & 0xFFu) << 8) + | (s_d3d.current_rsx_state->alpha_ref & 0xFFu); +- for (int _u = 0; _u < 4; _u++) { ++ for (int _u = 0; _u < 16; _u++) { + dr->tex[_u].off = s_d3d.cur_texs[_u].off; + dr->tex[_u].raw = s_d3d.cur_texs[_u].raw; + dr->tex[_u].w = s_d3d.cur_texs[_u].w; +@@ -7084,7 +7080,12 @@ static void d3d12_draw_arrays(void* ud, u32 primitive, u32 first, u32 count) + dr->tex[_u].fmt = s_d3d.cur_texs[_u].fmt; + dr->tex[_u].ctrl1 = s_d3d.cur_texs[_u].ctrl1; + dr->tex[_u].cube = s_d3d.cur_texs[_u].cube; +- dr->tex[_u].mips = s_d3d.cur_texs[_u].mips; dr->tex[_u].addr = s_d3d.cur_texs[_u].addr; dr->tex[_u].filter = s_d3d.cur_texs[_u].filter; dr->tex[_u].ctrl0 = s_d3d.cur_texs[_u].ctrl0; dr->tex[_u].border = s_d3d.cur_texs[_u].border; ++ dr->tex[_u].mips = s_d3d.cur_texs[_u].mips; ++ dr->tex[_u].pitch = s_d3d.cur_texs[_u].pitch; ++ dr->tex[_u].addr = s_d3d.cur_texs[_u].addr; ++ dr->tex[_u].filter = s_d3d.cur_texs[_u].filter; ++ dr->tex[_u].ctrl0 = s_d3d.cur_texs[_u].ctrl0; ++ dr->tex[_u].border = s_d3d.cur_texs[_u].border; + dr->tex[_u].set = s_d3d.cur_texs[_u].set; + dr->tex_rt[_u] = -1; + } +@@ -7197,15 +7198,20 @@ static void d3d12_draw_arrays(void* ud, u32 primitive, u32 first, u32 count) + dr->alpha_ctl = ((s_d3d.current_rsx_state->alpha_test_enable ? 1u : 0u) << 16) + | ((s_d3d.current_rsx_state->alpha_func & 0xFFu) << 8) + | (s_d3d.current_rsx_state->alpha_ref & 0xFFu); +- for (int _u = 0; _u < 4; _u++) { ++ for (int _u = 0; _u < 16; _u++) { + dr->tex[_u].off = s_d3d.cur_texs[_u].off; + dr->tex[_u].raw = s_d3d.cur_texs[_u].raw; + dr->tex[_u].w = s_d3d.cur_texs[_u].w; + dr->tex[_u].h = s_d3d.cur_texs[_u].h; + dr->tex[_u].fmt = s_d3d.cur_texs[_u].fmt; +- dr->tex[_u].ctrl1 = s_d3d.cur_texs[_u].ctrl1; +- dr->tex[_u].cube = s_d3d.cur_texs[_u].cube; +- dr->tex[_u].mips = s_d3d.cur_texs[_u].mips; dr->tex[_u].addr = s_d3d.cur_texs[_u].addr; dr->tex[_u].filter = s_d3d.cur_texs[_u].filter; dr->tex[_u].ctrl0 = s_d3d.cur_texs[_u].ctrl0; dr->tex[_u].border = s_d3d.cur_texs[_u].border; ++ dr->tex[_u].ctrl1 = s_d3d.cur_texs[_u].ctrl1; ++ dr->tex[_u].cube = s_d3d.cur_texs[_u].cube; ++ dr->tex[_u].mips = s_d3d.cur_texs[_u].mips; ++ dr->tex[_u].pitch = s_d3d.cur_texs[_u].pitch; ++ dr->tex[_u].addr = s_d3d.cur_texs[_u].addr; ++ dr->tex[_u].filter = s_d3d.cur_texs[_u].filter; ++ dr->tex[_u].ctrl0 = s_d3d.cur_texs[_u].ctrl0; ++ dr->tex[_u].border = s_d3d.cur_texs[_u].border; + dr->tex[_u].set = s_d3d.cur_texs[_u].set; + dr->tex_rt[_u] = -1; + } +@@ -7364,15 +7370,20 @@ static void d3d12_draw_indexed(void* ud, u32 primitive, u32 first, u32 count) + dr->alpha_ctl = ((s_d3d.current_rsx_state->alpha_test_enable ? 1u : 0u) << 16) + | ((s_d3d.current_rsx_state->alpha_func & 0xFFu) << 8) + | (s_d3d.current_rsx_state->alpha_ref & 0xFFu); +- for (int _u = 0; _u < 4; _u++) { ++ for (int _u = 0; _u < 16; _u++) { + dr->tex[_u].off = s_d3d.cur_texs[_u].off; + dr->tex[_u].raw = s_d3d.cur_texs[_u].raw; + dr->tex[_u].w = s_d3d.cur_texs[_u].w; + dr->tex[_u].h = s_d3d.cur_texs[_u].h; + dr->tex[_u].fmt = s_d3d.cur_texs[_u].fmt; +- dr->tex[_u].ctrl1 = s_d3d.cur_texs[_u].ctrl1; +- dr->tex[_u].cube = s_d3d.cur_texs[_u].cube; +- dr->tex[_u].mips = s_d3d.cur_texs[_u].mips; dr->tex[_u].addr = s_d3d.cur_texs[_u].addr; dr->tex[_u].filter = s_d3d.cur_texs[_u].filter; dr->tex[_u].ctrl0 = s_d3d.cur_texs[_u].ctrl0; dr->tex[_u].border = s_d3d.cur_texs[_u].border; ++ dr->tex[_u].ctrl1 = s_d3d.cur_texs[_u].ctrl1; ++ dr->tex[_u].cube = s_d3d.cur_texs[_u].cube; ++ dr->tex[_u].mips = s_d3d.cur_texs[_u].mips; ++ dr->tex[_u].pitch = s_d3d.cur_texs[_u].pitch; ++ dr->tex[_u].addr = s_d3d.cur_texs[_u].addr; ++ dr->tex[_u].filter = s_d3d.cur_texs[_u].filter; ++ dr->tex[_u].ctrl0 = s_d3d.cur_texs[_u].ctrl0; ++ dr->tex[_u].border = s_d3d.cur_texs[_u].border; + dr->tex[_u].set = s_d3d.cur_texs[_u].set; + dr->tex_rt[_u] = -1; + } +@@ -7469,7 +7480,7 @@ static void d3d12_bind_texture(void* ud, u32 unit, const rsx_texture_state* tex) + /* VP path: record the latest bound texture (any supported format) so draws + * can carry it per-draw. Location bits (format[1:0]): 1 = LOCAL, 2 = MAIN. */ + extern u32 cellGcmResolveLocated(int local, u32 offset); +- if (unit < 4 && ++ if (unit < 16 && + (base_fmt == 0x81 /* B8 */ || base_fmt == 0x85 /* A8R8G8B8 */ || + base_fmt == 0x8B /* G8B8: LBP's font atlas */ || + (base_fmt >= 0x86 && base_fmt <= 0x88) /* DXT1/23/45 */ || +@@ -7521,6 +7532,7 @@ static void d3d12_bind_texture(void* ud, u32 unit, const rsx_texture_state* tex) + s_d3d.cur_texs[unit].ctrl1 = tex->control1; + s_d3d.cur_texs[unit].cube = (tex->format & 4) ? 1 : 0; + s_d3d.cur_texs[unit].mips = (tex->format >> 16) & 0xFFFFu; ++ s_d3d.cur_texs[unit].pitch = tex->control3 & 0xFFFFFu; + s_d3d.cur_texs[unit].addr = tex->address; + s_d3d.cur_texs[unit].filter = tex->filter; + s_d3d.cur_texs[unit].ctrl0 = tex->control0; diff --git a/tasks/sp00nznet__ps3recomp-600/solution/solve.sh b/tasks/sp00nznet__ps3recomp-600/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-600/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-600/task.toml b/tasks/sp00nznet__ps3recomp-600/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a6727ac54a0ea97e5b38bb548441403a7c0d54e8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-600/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-600" +description = "rsx_d3d12: expand descriptor ranges to 16 units, MAX_OFF_RTS to 64, track row pitch, and add D3D12_NO_DBG" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/600" +source_access = "auto" +built_at = "2026-11-16T16:09:59.694316+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ffd8b3e73a65ef9f6c236f63992a3dc01cd143dfa78a70ab2cf18cf3f6a4ea93" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "libs/video/rsx_d3d12_backend.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 140 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.123343+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-600/tests/capture.py b/tasks/sp00nznet__ps3recomp-600/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-600/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-600/tests/instruction.md b/tasks/sp00nznet__ps3recomp-600/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d5fc04118b96213bd4a832a085bbe75301668439 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-600/tests/instruction.md @@ -0,0 +1,108 @@ +# Issue + +**Title:** rsx_d3d12: expand descriptor ranges to 16 units, MAX_OFF_RTS to 64, track row pitch, and add D3D12_NO_DBG + +## Description + +## Why + +When executing titles featuring complex deferred rendering pipelines, multi-layer paint shaders, and multi-stage offscreen render-to-texture (RTT) passes (e.g. racing simulations with 6-face dynamic reflection cubemaps, 4-level bloom downsample pyramids, and tonemapping buffers), the D3D12 backend encountered descriptor starvation and heap exhaustion: + +1. **Offscreen Render Target Exhaustion:** Titles allocating 25+ offscreen render surfaces per frame crashed or dropped passes due to the previous limit of `MAX_OFF_RTS = 16`. +2. **RSX Descriptor Range Starvation:** Complex RSX fragment programs bind and sample up to 16 texture units (`rsx_tex[16]`, `rsx_samp[16]`). The hardcoded 4-descriptor root signature table (`t0-t3`) left units `t4-t15` unbound and starved. +3. **Linear Texture Pitch Mismatch:** Linear textures require exact row pitch tracking from `SET_TEXTURE_CONTROL3` (bits 0..19). +4. **FPS Metric Reset:** The FPS counter reset `frame_count = 0` on every 1-second tick rather than taking a delta, distorting frame timing metrics. + +--- + +## Change + +### 1. Descriptor Heap Layout & Arithmetic (`DRAW_SRV_BASE` / `DRAW_SRV_STRIDE`) +- **`DRAW_SRV_BASE = 256`**: + - Offsets the dynamic per-draw SRV windows safely past the static allocations: + - Slots `0..4`: Primary backbuffers and UI atlas textures. + - Slots `5..68`: Offscreen render target SRVs (`RT_SRV_BASE..RT_SRV_BASE + MAX_OFF_RTS`). + - Slots `69..255`: Guard headroom clear of legacy `vp_tex` slots. +- **`DRAW_SRV_STRIDE = 16`**: + - Each recorded draw call gets a contiguous 16-descriptor window mapping units `t0..t15`. +- **Per-Draw Window Count & Total Heap Size**: + - For `MAX_DRAWS = 2048`, the ring provides 2,048 distinct per-draw windows. + - Total shader-visible descriptor heap size: + $$\text{SRV\_HEAP\_SIZE} = \text{DRAW\_SRV\_BASE} + (\text{MAX\_DRAWS} \times \text{DRAW\_SRV\_STRIDE}) = 256 + (2048 \times 16) = 33,024\text{ descriptors}$$ + - **Hardware compatibility:** D3D12 guarantees a minimum of 1,000,000 descriptors in a shader-visible heap for all Tier 1 hardware. At 32 bytes per descriptor, 33,024 descriptors require only $\approx 1.05\text{ MB}$ of VRAM, well within all hardware limits. + +### 2. Multi-Target Capacity (`MAX_OFF_RTS = 64`) +- Scaled `MAX_OFF_RTS` from 16 to 64 to comfortably accommodate 25+ active offscreen targets per frame (6 cubemap faces, 4-stage bloom downsample chains, and intermediate tone mapping buffers). + +### 3. Root Signature & Draw Record Expansion +- Expanded root signature SRV descriptor table and static samplers from 4 to 16 (`t0-t15`, `s0-s15`). +- Expanded `D3D12DrawRecord` to store 16 texture units (`tex[16]`, `tex_rt[16]`) and connected all 16 units throughout `render_frame`, `d3d12_draw_arrays`, and `d3d12_draw_indexed`. + +### 4. Diagnostics & Controls +- Added `D3D12_NO_DBG` knob to disable the D3D12 debug layer even in debug builds, documented for `tools/gen_diagnostics_index.py`. +- Corrected FPS metric calculation to record the delta against `s_last_fps_frame`. +- Tracked linear texture row pitch from `SET_TEXTURE_CONTROL3` (bits 0..19). + +--- + +## Factual Citations & Hardware References + +1. **NVIDIA CineFX 3.0 / G70 Hardware Architecture (16 Sampler Units):** + - *Reference:* [Khronos OpenGL ARB_fragment_program Specification (`MAX_TEXTURE_IMAGE_UNITS = 16`)](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_fragment_program.txt) + - *Hardware Mapping:* The RSX Reality Synthesizer implements 16 independent texture mapping units, addressed in GCM command packets via methods `NV4097_SET_TEXTURE_OFFSET_M` (`0x1A00 + 0x20 * M`) and `NV4097_SET_TEXTURE_FORMAT_M` (`0x1840 + 0x20 * M`) where $M \in [0, 15]$. +2. **Microsoft Direct3D 12 Hardware Tiers Specification (Tier 1 Resource Binding):** + - *Reference:* [Microsoft Learn – D3D12 Hardware Tiers](https://learn.microsoft.com/en-us/windows/win32/direct3d12/hardware-support) + - *Specification limit:* All Direct3D 12 Tier 1 hardware supports a minimum of 1,000,000 descriptors in a shader-visible descriptor heap. Our allocation of 33,024 descriptors utilizes only $3.3\%$ of the minimum Tier 1 hardware ceiling. + +--- + +## Evidence + +### Before vs. With this change + +| Component | Before | With this change | +|---|---|---| +| Offscreen Render Targets | `MAX_OFF_RTS = 16` -> Heap exhaustion on pass 17 | `MAX_OFF_RTS = 64` -> All 25 targets map cleanly | +| Bound Texture Samplers | 4 descriptors (`t0-t3`) -> units 4..15 unbound | 16 descriptors (`t0-t15`) -> all 16 units bound | +| Descriptor Heap Size | 8,224 descriptors | 33,024 descriptors (2,048 windows x 16 units) | +| Linear Texture Row Pitch | Unparsed / default pitch | Tracked from `SET_TEXTURE_CONTROL3` bits 0..19 | +| FPS Counter | Distorted (zeroed every tick) | Accurate frame delta over 1000ms | + +### Telemetry: Multi-Target Allocation Manifest (25 Offscreen Targets) + +``` +frame_count=2712 draws=940 backbuffer=1280x720 +offrt[0] off=0x0F180000 1280x720 dxgi=28 (Main HDR Scene) +offrt[1] off=0x0C0C0000 512x512 dxgi=28 (Cubemap Face 0) +offrt[2] off=0x0C1C0000 512x512 dxgi=28 (Cubemap Face 1) +offrt[3] off=0x0C2C0000 512x512 dxgi=28 (Cubemap Face 2) +offrt[4] off=0x0C4C0000 512x512 dxgi=28 (Cubemap Face 4) +offrt[5] off=0x0C5C0000 512x512 dxgi=28 (Cubemap Face 5) +offrt[6] off=0x0E0C0000 1280x360 dxgi=28 (Bloom Level 1 Downsample) +offrt[7] off=0x0DDC0000 640x360 dxgi=28 (Bloom Level 2 Downsample) +offrt[8] off=0x0DC20000 640x180 dxgi=28 (Bloom Level 3 Downsample) +offrt[9] off=0x0D360000 320x180 dxgi=28 (Bloom Level 4 Downsample) +... +op937 DRAW rt=0x0D7A0000 vp=0,0,1280x720 fp=0x03778001 vs=2 n=3 cmask=F blend=0 t0=0x0F180000 t1=0x0E300000 t2=0x0D360000 t3=0x0BDA0000 +op939 DRAW rt=0x00000000 vp=0,0,1280x720 fp=0x03777701 vs=2 n=3 cmask=F blend=0 t0=0x0D7A0000 t1=0x0E300000 t2=0x0D300000 t3=0x0BDA0000 +``` + +### Visual Verification + +![HUD & Telemetry Dial](https://raw.githubusercontent.com/DriifterSelf/ps3recomp/evidence-assets/hud_dial.png) +*HUD dials and telemetry elements rendering across offscreen composite targets.* + +![Gameplay Composite](https://raw.githubusercontent.com/DriifterSelf/ps3recomp/evidence-assets/gameplay_composite.png) +*Multi-stage offscreen RTT composite pass executing without descriptor exhaustion.* + +--- + +## AI Assistance & Clean-Room Compliance + +In accordance with upstream guidelines ([`CONTRIBUTORS.md#a-note-on-ai-assisted-contributions`](CONTRIBUTORS.md#a-note-on-ai-assisted-contributions)): +- Authored with AI assistance (Antigravity), directed and verified against Direct3D 12 specifications and runtime telemetry. +- Clean-room implementation: all descriptor arithmetic and resource management written specifically for `ps3recomp`; no code copied or adapted from RPCS3 or other GPL emulators. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-600/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-600/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e8420fe7cb0df37aef4ee26a873607b680666b08 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-600/tests/oracle.patch @@ -0,0 +1,404 @@ +diff --git a/libs/video/rsx_d3d12_backend.c b/libs/video/rsx_d3d12_backend.c +index bc05a308..4f81ae8f 100644 +--- a/libs/video/rsx_d3d12_backend.c ++++ b/libs/video/rsx_d3d12_backend.c +@@ -106,14 +106,16 @@ typedef struct { + u32 mips; /* SET_TEXTURE_FORMAT bits 16..31: mipmap level count. + * Cube faces sit one whole mip pyramid apart, so this + * is what sets the face stride. */ ++ u32 pitch; /* SET_TEXTURE_CONTROL3 bits 0..19: row pitch for linear textures */ + int cube; /* SET_TEXTURE_FORMAT bit 2: a cube texture. Sampled + * with a 3-component direction, not a 2D uv -- treating + * one as 2D is what makes an environment-mapped chrome + * surface come out with black patches and banding. */ + int set; + u32 addr, filter, ctrl0, border; /* TEXTURE_ADDRESS/FILTER/CONTROL0/BORDER_COLOR */ +- } tex[4]; +- int tex_rt[4]; /* pre-pass: OffRT index sampled by unit, -1 = none */ ++ } tex[16]; ++ int tex_rt[16]; /* pre-pass: OffRT index sampled by unit, -1 = none */ ++ int tex_ds[16]; /* pre-pass: OffDS read through unit u (its colour copy is tex_rt), -1 = none */ + int tex_slot; /* legacy single-slot path (atlas); -1 = none */ + int vs_idx; /* VPVSEntry slot for this draw's vertex program (-1 = primary) */ + int blend; /* guest blend enable at draw time */ +@@ -135,7 +137,6 @@ typedef struct { + u32 rt_fmt; /* RSX surface colour format (SET_SURFACE_FORMAT [4:0]) */ + u32 zeta_off; /* depth surface (SET_SURFACE_ZETA_OFFSET) when the surface has one */ + int no_color; /* colour target NONE with a depth surface: a depth-only pass */ +- int tex_ds[4]; /* pre-pass: OffDS read through unit u (its colour copy is tex_rt), -1 = none */ + /* Guest viewport rect at draw time (target pixels). Sub-viewport layouts + * (wave's debug tiles) position quads with this, not with constants -- + * forcing full-target viewports drew every tile window-sized. */ +@@ -166,7 +167,7 @@ typedef struct { + D3D12_RESOURCE_STATES st; /* tracked resource state */ + int used; /* referenced this frame */ + } OffRT; +-#define MAX_OFF_RTS 16 /* demosaic double-buffers its 6-surface pass chain */ ++#define MAX_OFF_RTS 64 /* titles with bloom pyramids and cubemap RTT passes allocate 20+ surfaces */ + + /* Depth surface, one per guest zeta offset. The pass chain keeps several + * (God of War HD: the scene's 2x-AA depth at 0x17F0000 and the resolved depth +@@ -182,13 +183,13 @@ typedef struct { + u64 last_frame; /* frame_count of the last pass that bound it */ + } OffDS; + #define MAX_OFF_DS 6 +-#define DS_SRV_BASE 21 /* SRV heap slots 21..32 hold depth + stencil SRVs (2 per OffDS) */ +-#define RT_SRV_BASE 5 /* SRV heap slots 5..20 hold offscreen-RT SRVs */ +-/* Per-draw SRV windows: each VP draw gets 4 consecutive descriptors (t0-t3) +- * so multi-unit fragment programs see all their textures (demosaic's +- * interpolation passes sample 3 units). */ +-#define DRAW_SRV_BASE 40 +-#define SRV_HEAP_SIZE (DRAW_SRV_BASE + MAX_DRAWS * 4) ++#define RT_SRV_BASE 5 /* SRV heap slots 5..68 hold offscreen-RT SRVs */ ++#define DS_SRV_BASE 70 /* SRV heap slots 70..81 hold depth + stencil SRVs (2 per OffDS) */ ++/* Per-draw SRV windows: each VP draw gets 16 consecutive descriptors (t0-t15) ++ * so multi-unit fragment programs see all their textures. */ ++#define DRAW_SRV_BASE 256 ++#define DRAW_SRV_STRIDE 16 ++#define SRV_HEAP_SIZE (DRAW_SRV_BASE + MAX_DRAWS * DRAW_SRV_STRIDE) + + /* Per-frame VP texture slot: a guest texture uploaded for this frame's VP + * draws (re-uploaded every frame -- gcm/cube's plasma animates in guest +@@ -198,6 +199,7 @@ typedef struct { + ID3D12Resource* res; + ID3D12Resource* up; + u32 off, w, h, fmt; /* current contents (resource reused when dims match) */ ++ u32 pitch; + u32 csum; /* sparse checksum of the source bytes last uploaded */ + int cube; /* resource is a 6-face cube, sampled as TextureCube */ + u32 key; /* the ORIGINAL bound offset -- the cache lookup key. +@@ -208,12 +210,8 @@ typedef struct { + u32 last_frame; /* frame_count when last referenced: the slot least + * recently used is the one given to a new texture */ + } VPTexSlot; +-/* Distinct textures uploadable per frame. Four was enough for a UI/atlas-style +- * frame but not for a scene: this title binds ~20 distinct textures per frame, +- * so every draw past the fourth got slot -1 from vp_upload_tex_slot ("out of +- * slots") and drew UNTEXTURED. That reads as a correctly-lit but solid black +- * object, which is indistinguishable from a missing texture upload. */ +-#define VP_TEX_SLOTS 192 ++/* Distinct textures uploadable per frame. */ ++#define VP_TEX_SLOTS 256 + /* Guest texture uploads are staged in one persistently mapped upload buffer, + * a part per frame in flight, reset when that frame's command allocator is + * (the GPU has finished its copies by then). A committed upload buffer per +@@ -367,9 +365,9 @@ typedef struct { + VPFPEntry vp_fp[VP_FP_CACHE]; /* guest-FP PSO cache */ + int vp_fp_n; + u32 srv_inc; /* CBV_SRV_UAV descriptor size */ +- /* VP path: latest texture bound per unit (t0-t3). */ +- struct { u32 off, raw, w, h, fmt, ctrl1, mips; int cube; int set; +- u32 addr, filter, ctrl0, border; } cur_texs[4]; ++ /* VP path: latest texture bound per unit (t0-t15). */ ++ struct { u32 off, raw, w, h, fmt, ctrl1, mips, pitch; int cube; int set; ++ u32 addr, filter, ctrl0, border; } cur_texs[16]; + /* Guest sampler states, one shader-visible descriptor each (samp_key[i] + * describes descriptor i; 0 and 1 are the defaults for units with none). */ + ID3D12DescriptorHeap* samp_heap; +@@ -722,7 +720,7 @@ static int init_d3d12(u32 width, u32 height) + #ifdef NDEBUG + getenv("D3D12_DBG") + #else +- 1 ++ !getenv("D3D12_NO_DBG") /* D3D12_NO_DBG=1 disables the debug layer in debug builds */ + #endif + ) { + ID3D12Debug* debug_controller = NULL; +@@ -1323,11 +1321,11 @@ static int init_d3d12(u32 width, u32 height) + * t0 and are unaffected. Matching 4 static samplers s0-s3. */ + D3D12_DESCRIPTOR_RANGE srv_range = {0}; + srv_range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; +- srv_range.NumDescriptors = 4; ++ srv_range.NumDescriptors = 16; + srv_range.BaseShaderRegister = 0; + srv_range.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + +- D3D12_ROOT_PARAMETER rp[7] = {0}; ++ D3D12_ROOT_PARAMETER rp[19] = {0}; + rp[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; /* b0 = vp_c bank */ + rp[0].Descriptor.ShaderRegister = 0; + rp[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX; +@@ -1339,15 +1337,10 @@ static int init_d3d12(u32 width, u32 height) + rp[2].Descriptor.ShaderRegister = 1; + rp[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + +- /* s0-s3: one sampler table per unit, filled per draw from the guest's +- * TEXTURE_ADDRESS/FILTER/CONTROL0 (vp_sampler). These were four static +- * samplers -- s0 point/clamp for the dbgfont atlas, s1-s3 linear/wrap -- +- * so every unit-0 texture was point-sampled and clamped whatever the +- * title asked for: God of War HD's soldiers wrap their texture atlas +- * (v up to ~2) and drew transparent-black from its clamped bottom row. +- * Units without guest state keep those two defaults. */ +- D3D12_DESCRIPTOR_RANGE samp_range[4] = {0}; +- for (int _s = 0; _s < 4; _s++) { ++ /* s0-s15: one sampler table per unit, filled per draw from the guest's ++ * TEXTURE_ADDRESS/FILTER/CONTROL0 (vp_sampler). */ ++ D3D12_DESCRIPTOR_RANGE samp_range[16] = {0}; ++ for (int _s = 0; _s < 16; _s++) { + samp_range[_s].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER; + samp_range[_s].NumDescriptors = 1; + samp_range[_s].BaseShaderRegister = (UINT)_s; +@@ -1358,7 +1351,7 @@ static int init_d3d12(u32 width, u32 height) + } + + D3D12_ROOT_SIGNATURE_DESC rd = {0}; +- rd.NumParameters = 7; rd.pParameters = rp; ++ rd.NumParameters = 19; rd.pParameters = rp; + rd.NumStaticSamplers = 0; rd.pStaticSamplers = NULL; + rd.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; + +@@ -2847,7 +2840,7 @@ static u32 tex_csum(const u8* base, u32 nbytes) + return h; + } + +-static int vp_upload_tex_slot(u32 off, u32 w, u32 h, u32 fmt, int cube, u32 mips) ++static int vp_upload_tex_slot(u32 off, u32 w, u32 h, u32 fmt, int cube, u32 mips, u32 pitch_arg) + { + /* TEX_BUDGET=: cap texture uploads per frame. Off by default -- it was + * tried against the TDR and does not help, because PERF shows the upload +@@ -2871,7 +2864,7 @@ static int vp_upload_tex_slot(u32 off, u32 w, u32 h, u32 fmt, int cube, u32 mips + * layout.c owns them so the Metal backend can read a guest texture without + * re-deriving any of it. Only the DXGI mapping below is ours. */ + rsx_tex_layout tl; +- rsx_texture_layout(fmt, w, h, &tl); ++ rsx_texture_layout_pitched(fmt, w, h, pitch_arg, &tl); + int argb = (tl.fmt == RSX_TEXFMT_R8G8B8A8); + int dxt = tl.compressed; + /* Compressed rows are counted in blocks, so keep bpp at 1 for the byte +@@ -2906,7 +2899,7 @@ static int vp_upload_tex_slot(u32 off, u32 w, u32 h, u32 fmt, int cube, u32 mips + for (int i = 0; i < VP_TEX_SLOTS; i++) { + VPTexSlot* c = &s_d3d.vp_tex[i]; + if (c->res && c->key == key_off && c->w == w && c->h == h && c->fmt == fmt +- && c->cube == cube) { ++ && c->cube == cube && c->pitch == pitch_arg) { + c->last_frame = s_d3d.frame_count; + if (c->used) return i; /* already bound this frame */ + { static int nocache = -1; /* TEX_NOCACHE=1: always re-upload */ +@@ -3031,6 +3024,7 @@ static int vp_upload_tex_slot(u32 off, u32 w, u32 h, u32 fmt, int cube, u32 mips + if (slot < 0) return -1; + VPTexSlot* t = &s_d3d.vp_tex[slot]; + t->last_frame = s_d3d.frame_count; ++ t->pitch = pitch_arg; + /* The upload buffer's rows hold the DECODED image, so they are sized from + * dst_row_bytes -- w * bpp is the source row, which is narrower for any + * format rsx_texture_decode unpacks. */ +@@ -3041,7 +3035,7 @@ static int vp_upload_tex_slot(u32 off, u32 w, u32 h, u32 fmt, int cube, u32 mips + * the same dimensions would otherwise be reused with 1 array slice while the + * cube path copies 6 subresources and writes a 6x upload buffer -- which + * crashes. */ +- if (t->res && (t->w != w || t->h != h || t->fmt != fmt || t->cube != cube)) { ++ if (t->res && (t->w != w || t->h != h || t->fmt != fmt || t->cube != cube || t->pitch != pitch_arg)) { + t->res->lpVtbl->Release(t->res); t->res = NULL; + if (t->up) { t->up->lpVtbl->Release(t->up); t->up = NULL; } + } +@@ -4704,11 +4698,11 @@ static void render_frame(void) + off_rt_get(dr->rt_mrt[_m], dr->rt_w, dr->rt_h, dr->rt_fmt); + if (dr->is_vp && dr->zeta_off && (dr->rt_off || dr->no_color)) + off_ds_get(dr->zeta_off, dr->rt_w, dr->rt_h); +- for (int _u = 0; _u < 4; _u++) dr->tex_ds[_u] = -1; /* set below for draws */ ++ for (int _u = 0; _u < 16; _u++) dr->tex_ds[_u] = -1; /* set below for draws */ + } + for (u32 _d = 0; _d < s_d3d.draw_count && _d < MAX_DRAWS; _d++) { + const D3D12DrawRecord* dr = &s_d3d.draws[_d]; +- for (int _u = 0; _u < 4 && dr->is_vp && !dr->is_clear; _u++) { ++ for (int _u = 0; _u < 16 && dr->is_vp && !dr->is_clear; _u++) { + const int ds = dr->tex[_u].set ? off_ds_find(dr->tex[_u].raw) : -1; + if (ds < 0) continue; + s_d3d.off_ds[ds].last_frame = s_d3d.frame_count; +@@ -4747,7 +4741,7 @@ static void render_frame(void) + { static int ed = -1; + if (ed < 0) { const char* e = getenv("EMPTYTEX"); ed = e ? atoi(e) : 0; } + extern uint8_t* vm_base; +- if (ed && vm_base) for (int _u = 0; _u < 4; _u++) { ++ if (ed && vm_base) for (int _u = 0; _u < 16; _u++) { + if (!dr->tex[_u].set || !dr->tex[_u].off) continue; + u32 nz = 0, sz = dr->tex[_u].w * dr->tex[_u].h * 4u; + for (u32 i2 = 0; i2 < sz && i2 < 0x20000u; i2 += 997) +@@ -4790,7 +4784,7 @@ static void render_frame(void) + } } + { static int sd = -1; + if (sd < 0) { const char* e = getenv("SCREENTEX"); sd = e ? atoi(e) : 0; } +- if (sd) for (int _u = 0; _u < 4; _u++) ++ if (sd) for (int _u = 0; _u < 16; _u++) + if (dr->tex[_u].set && dr->tex[_u].w == s_d3d.width && + dr->tex[_u].h == s_d3d.height) { + static u32 seen[16]; static int ns = 0; int known = 0; +@@ -4802,12 +4796,12 @@ static void render_frame(void) + dr->tex[_u].fmt, dr->fp_addr, dr->vertex_count, + dr->vp_x, dr->vp_y, dr->vp_w, dr->vp_h, 10); } + } } +- /* Fill this draw's t0-t3 SRV window (DRAW_SRV_BASE + d*4): each unit ++ /* Fill this draw's t0-t15 SRV window (DRAW_SRV_BASE + d*DRAW_SRV_STRIDE): each unit + * resolves to an offscreen RT (sampled directly), an uploaded guest + * texture, or a null SRV. */ + double _sv0 = perf_on() ? perf_now() : 0.0; +- for (int _u = 0; _u < 4; _u++) { +- u32 wslot = DRAW_SRV_BASE + _d * 4 + (u32)_u; ++ for (int _u = 0; _u < DRAW_SRV_STRIDE; _u++) { ++ u32 wslot = DRAW_SRV_BASE + _d * DRAW_SRV_STRIDE + (u32)_u; + dr->tex_rt[_u] = -1; + /* A depth surface read as a texture: its colour copy (made in the + * RT pre-pass), refreshed from the depth buffer just before this +@@ -4876,7 +4870,7 @@ static void render_frame(void) + int _cube = dr->tex[_u].cube && (dr_cube_mask(dr) & (1u << _u)); + int ts = vp_upload_tex_slot(dr->tex[_u].off, dr->tex[_u].w, + dr->tex[_u].h, dr->tex[_u].fmt, +- _cube, dr->tex[_u].mips); ++ _cube, dr->tex[_u].mips, dr->tex[_u].pitch); + if (perf_on()) { s_perf_tex += perf_now() - _tt; s_perf_ntex++; + s_perf_texbytes += (u64)dr->tex[_u].w * dr->tex[_u].h * 4u; } + /* Both forms of the offset are in hand here; the filters +@@ -5100,7 +5094,8 @@ static void render_frame(void) + D3D12_GPU_DESCRIPTOR_HANDLE gh; + s_d3d.srv_heap->lpVtbl->GetGPUDescriptorHandleForHeapStart(s_d3d.srv_heap, &gh); + s_d3d.cmd_list->lpVtbl->SetGraphicsRootDescriptorTable(s_d3d.cmd_list, 1, gh); +- int samp_bound[4] = { -1, -1, -1, -1 }; ++ int samp_bound[16]; ++ for (int _s = 0; _s < 16; _s++) samp_bound[_s] = -1; + D3D12_VERTEX_BUFFER_VIEW vbv; + vbv.BufferLocation = s_d3d.vp_vb->lpVtbl->GetGPUVirtualAddress(s_d3d.vp_vb) + + (u64)s_d3d.vp_parity * MAX_VERTICES * 256; +@@ -5121,7 +5116,7 @@ static void render_frame(void) + for (u32 d = 0; d < s_d3d.draw_count && d < MAX_DRAWS; d++) { + const D3D12DrawRecord* dr = &s_d3d.draws[d]; + if (!dr->is_vp) continue; +- for (int _u = 0; _u < 4; _u++) { ++ for (int _u = 0; _u < 16; _u++) { + const int ds = dr->tex_ds[_u]; + if (ds < 0 || ds == cur_z || s_d3d.off_ds[ds].conv_gen == s_d3d.off_ds[ds].gen) + continue; +@@ -5129,7 +5124,7 @@ static void render_frame(void) + s_d3d.cmd_list->lpVtbl->SetGraphicsRootSignature(s_d3d.cmd_list, s_d3d.vp_root_sig); + { ID3D12DescriptorHeap* hp2[] = { s_d3d.srv_heap, s_d3d.samp_heap }; + s_d3d.cmd_list->lpVtbl->SetDescriptorHeaps(s_d3d.cmd_list, s_d3d.samp_heap ? 2 : 1, hp2); } +- for (int _s = 0; _s < 4; _s++) samp_bound[_s] = -1; ++ for (int _s = 0; _s < 16; _s++) samp_bound[_s] = -1; + force_rebind = 1; + } + /* The reduced-viewport passes (this title's reflection, drawn +@@ -5334,19 +5329,19 @@ static void render_frame(void) + /* Per-draw textures: bind this draw's t0-t3 SRV window. + * Any sampled offscreen RT transitions to PSR first (never + * one of the currently-bound colour targets). */ +- for (int _u = 0; _u < 4; _u++) { ++ for (int _u = 0; _u < 16; _u++) { + int rt = dr->tex_rt[_u]; + if (rt >= 0 && rt != cur_rt && + rt != cur_m[0] && rt != cur_m[1] && rt != cur_m[2]) + off_rt_transition(rt, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + } + D3D12_GPU_DESCRIPTOR_HANDLE gh = gh_base; +- gh.ptr += (u64)(DRAW_SRV_BASE + d * 4) * s_d3d.srv_inc; ++ gh.ptr += (u64)(DRAW_SRV_BASE + d * DRAW_SRV_STRIDE) * s_d3d.srv_inc; + s_d3d.cmd_list->lpVtbl->SetGraphicsRootDescriptorTable(s_d3d.cmd_list, 1, gh); + if (s_d3d.samp_heap) { + D3D12_GPU_DESCRIPTOR_HANDLE sb; + s_d3d.samp_heap->lpVtbl->GetGPUDescriptorHandleForHeapStart(s_d3d.samp_heap, &sb); +- for (int _u = 0; _u < 4; _u++) { ++ for (int _u = 0; _u < 16; _u++) { + const int si = vp_sampler(dr, _u); + if (si == samp_bound[_u]) continue; + samp_bound[_u] = si; +@@ -5948,9 +5943,10 @@ static void d3d12_present(void* ud, u32 buffer_id) + /* FPS tracking */ + ULONGLONG now = GetTickCount64(); + if (now - s_d3d.last_fps_time >= 1000) { +- s_d3d.fps = (u32)s_d3d.frame_count; /* rough estimate */ ++ static u64 s_last_fps_frame = 0; ++ s_d3d.fps = (u32)(s_d3d.frame_count - s_last_fps_frame); ++ s_last_fps_frame = s_d3d.frame_count; + s_d3d.last_fps_time = now; +- s_d3d.frame_count = 0; + } + } + +@@ -7076,7 +7072,7 @@ static void d3d12_draw_arrays(void* ud, u32 primitive, u32 first, u32 count) + dr->alpha_ctl = ((s_d3d.current_rsx_state->alpha_test_enable ? 1u : 0u) << 16) + | ((s_d3d.current_rsx_state->alpha_func & 0xFFu) << 8) + | (s_d3d.current_rsx_state->alpha_ref & 0xFFu); +- for (int _u = 0; _u < 4; _u++) { ++ for (int _u = 0; _u < 16; _u++) { + dr->tex[_u].off = s_d3d.cur_texs[_u].off; + dr->tex[_u].raw = s_d3d.cur_texs[_u].raw; + dr->tex[_u].w = s_d3d.cur_texs[_u].w; +@@ -7084,7 +7080,12 @@ static void d3d12_draw_arrays(void* ud, u32 primitive, u32 first, u32 count) + dr->tex[_u].fmt = s_d3d.cur_texs[_u].fmt; + dr->tex[_u].ctrl1 = s_d3d.cur_texs[_u].ctrl1; + dr->tex[_u].cube = s_d3d.cur_texs[_u].cube; +- dr->tex[_u].mips = s_d3d.cur_texs[_u].mips; dr->tex[_u].addr = s_d3d.cur_texs[_u].addr; dr->tex[_u].filter = s_d3d.cur_texs[_u].filter; dr->tex[_u].ctrl0 = s_d3d.cur_texs[_u].ctrl0; dr->tex[_u].border = s_d3d.cur_texs[_u].border; ++ dr->tex[_u].mips = s_d3d.cur_texs[_u].mips; ++ dr->tex[_u].pitch = s_d3d.cur_texs[_u].pitch; ++ dr->tex[_u].addr = s_d3d.cur_texs[_u].addr; ++ dr->tex[_u].filter = s_d3d.cur_texs[_u].filter; ++ dr->tex[_u].ctrl0 = s_d3d.cur_texs[_u].ctrl0; ++ dr->tex[_u].border = s_d3d.cur_texs[_u].border; + dr->tex[_u].set = s_d3d.cur_texs[_u].set; + dr->tex_rt[_u] = -1; + } +@@ -7197,15 +7198,20 @@ static void d3d12_draw_arrays(void* ud, u32 primitive, u32 first, u32 count) + dr->alpha_ctl = ((s_d3d.current_rsx_state->alpha_test_enable ? 1u : 0u) << 16) + | ((s_d3d.current_rsx_state->alpha_func & 0xFFu) << 8) + | (s_d3d.current_rsx_state->alpha_ref & 0xFFu); +- for (int _u = 0; _u < 4; _u++) { ++ for (int _u = 0; _u < 16; _u++) { + dr->tex[_u].off = s_d3d.cur_texs[_u].off; + dr->tex[_u].raw = s_d3d.cur_texs[_u].raw; + dr->tex[_u].w = s_d3d.cur_texs[_u].w; + dr->tex[_u].h = s_d3d.cur_texs[_u].h; + dr->tex[_u].fmt = s_d3d.cur_texs[_u].fmt; +- dr->tex[_u].ctrl1 = s_d3d.cur_texs[_u].ctrl1; +- dr->tex[_u].cube = s_d3d.cur_texs[_u].cube; +- dr->tex[_u].mips = s_d3d.cur_texs[_u].mips; dr->tex[_u].addr = s_d3d.cur_texs[_u].addr; dr->tex[_u].filter = s_d3d.cur_texs[_u].filter; dr->tex[_u].ctrl0 = s_d3d.cur_texs[_u].ctrl0; dr->tex[_u].border = s_d3d.cur_texs[_u].border; ++ dr->tex[_u].ctrl1 = s_d3d.cur_texs[_u].ctrl1; ++ dr->tex[_u].cube = s_d3d.cur_texs[_u].cube; ++ dr->tex[_u].mips = s_d3d.cur_texs[_u].mips; ++ dr->tex[_u].pitch = s_d3d.cur_texs[_u].pitch; ++ dr->tex[_u].addr = s_d3d.cur_texs[_u].addr; ++ dr->tex[_u].filter = s_d3d.cur_texs[_u].filter; ++ dr->tex[_u].ctrl0 = s_d3d.cur_texs[_u].ctrl0; ++ dr->tex[_u].border = s_d3d.cur_texs[_u].border; + dr->tex[_u].set = s_d3d.cur_texs[_u].set; + dr->tex_rt[_u] = -1; + } +@@ -7364,15 +7370,20 @@ static void d3d12_draw_indexed(void* ud, u32 primitive, u32 first, u32 count) + dr->alpha_ctl = ((s_d3d.current_rsx_state->alpha_test_enable ? 1u : 0u) << 16) + | ((s_d3d.current_rsx_state->alpha_func & 0xFFu) << 8) + | (s_d3d.current_rsx_state->alpha_ref & 0xFFu); +- for (int _u = 0; _u < 4; _u++) { ++ for (int _u = 0; _u < 16; _u++) { + dr->tex[_u].off = s_d3d.cur_texs[_u].off; + dr->tex[_u].raw = s_d3d.cur_texs[_u].raw; + dr->tex[_u].w = s_d3d.cur_texs[_u].w; + dr->tex[_u].h = s_d3d.cur_texs[_u].h; + dr->tex[_u].fmt = s_d3d.cur_texs[_u].fmt; +- dr->tex[_u].ctrl1 = s_d3d.cur_texs[_u].ctrl1; +- dr->tex[_u].cube = s_d3d.cur_texs[_u].cube; +- dr->tex[_u].mips = s_d3d.cur_texs[_u].mips; dr->tex[_u].addr = s_d3d.cur_texs[_u].addr; dr->tex[_u].filter = s_d3d.cur_texs[_u].filter; dr->tex[_u].ctrl0 = s_d3d.cur_texs[_u].ctrl0; dr->tex[_u].border = s_d3d.cur_texs[_u].border; ++ dr->tex[_u].ctrl1 = s_d3d.cur_texs[_u].ctrl1; ++ dr->tex[_u].cube = s_d3d.cur_texs[_u].cube; ++ dr->tex[_u].mips = s_d3d.cur_texs[_u].mips; ++ dr->tex[_u].pitch = s_d3d.cur_texs[_u].pitch; ++ dr->tex[_u].addr = s_d3d.cur_texs[_u].addr; ++ dr->tex[_u].filter = s_d3d.cur_texs[_u].filter; ++ dr->tex[_u].ctrl0 = s_d3d.cur_texs[_u].ctrl0; ++ dr->tex[_u].border = s_d3d.cur_texs[_u].border; + dr->tex[_u].set = s_d3d.cur_texs[_u].set; + dr->tex_rt[_u] = -1; + } +@@ -7469,7 +7480,7 @@ static void d3d12_bind_texture(void* ud, u32 unit, const rsx_texture_state* tex) + /* VP path: record the latest bound texture (any supported format) so draws + * can carry it per-draw. Location bits (format[1:0]): 1 = LOCAL, 2 = MAIN. */ + extern u32 cellGcmResolveLocated(int local, u32 offset); +- if (unit < 4 && ++ if (unit < 16 && + (base_fmt == 0x81 /* B8 */ || base_fmt == 0x85 /* A8R8G8B8 */ || + base_fmt == 0x8B /* G8B8: LBP's font atlas */ || + (base_fmt >= 0x86 && base_fmt <= 0x88) /* DXT1/23/45 */ || +@@ -7521,6 +7532,7 @@ static void d3d12_bind_texture(void* ud, u32 unit, const rsx_texture_state* tex) + s_d3d.cur_texs[unit].ctrl1 = tex->control1; + s_d3d.cur_texs[unit].cube = (tex->format & 4) ? 1 : 0; + s_d3d.cur_texs[unit].mips = (tex->format >> 16) & 0xFFFFu; ++ s_d3d.cur_texs[unit].pitch = tex->control3 & 0xFFFFFu; + s_d3d.cur_texs[unit].addr = tex->address; + s_d3d.cur_texs[unit].filter = tex->filter; + s_d3d.cur_texs[unit].ctrl0 = tex->control0; diff --git a/tasks/sp00nznet__ps3recomp-600/tests/test.sh b/tasks/sp00nznet__ps3recomp-600/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-600/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-600/tests/verifier.py b/tasks/sp00nznet__ps3recomp-600/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-600/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-604/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-604/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-604/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-604/instruction.md b/tasks/sp00nznet__ps3recomp-604/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..30452a600123c597b5711bde787c7282fe912f30 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-604/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** rsx_draw_engine: release a recreated depth target's snapshot once + +## Description + +`eng_zdepth_get` released `z->snapshot` twice when it recreated a depth target. #502 added "the old size's snapshot goes with it" before the depth target's release, and #499 added the `z->conv` release followed by the same `z->snapshot` release; both merged into v0.18.0 side by side: + +```c +if (z->snapshot && g.be->texture_release) g.be->texture_release(g.be->user, z->snapshot); // #502 +if (z->handle) g.be->depth_target_release(g.be->user, z->handle); +if (z->conv) g.be->texture_release(g.be->user, z->conv); // #499 +if (z->snapshot) g.be->texture_release(g.be->user, z->snapshot); // same handle again +``` + +The second call hands the backend a handle it already released. The Metal backend ignores a retired slot and the Vulkan one finds no object, so nothing visible happens today; but the contract is one release per texture, and a backend that recycles handles immediately would free whatever took the slot in between. + +This drops the first call. The one after the conv texture covers the same snapshot, and the order of the releases is otherwise unchanged. + +`test_rsx_draw_engine` now counts release calls per stub handle and checks that the snapshot of a recreated depth target is released once. On v0.18.0 that check fails (2 calls); with the change it passes, and the whole test passes (clang, macOS, built as in `macos.yml`). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-604/solution/patch.diff b/tasks/sp00nznet__ps3recomp-604/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5c7f28ebeb41f2d5cf3948b2fcfee505a162b0d1 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-604/solution/patch.diff @@ -0,0 +1,42 @@ +diff --git a/libs/video/rsx_draw_engine.c b/libs/video/rsx_draw_engine.c +index 8dff6011..0ecaf358 100644 +--- a/libs/video/rsx_draw_engine.c ++++ b/libs/video/rsx_draw_engine.c +@@ -996,7 +996,6 @@ static u32 eng_zdepth_get(u32 location, u32 offset, u32 rt_w, u32 rt_h) + + eng_zdepth* z = &g.zdepths[slot]; + /* The old size's snapshot goes with it: it can never be valid again. */ +- if (z->snapshot && g.be->texture_release) g.be->texture_release(g.be->user, z->snapshot); + if (z->handle) g.be->depth_target_release(g.be->user, z->handle); + if (z->conv) g.be->texture_release(g.be->user, z->conv); + if (z->snapshot) g.be->texture_release(g.be->user, z->snapshot); +diff --git a/libs/video/tests/test_rsx_draw_engine.c b/libs/video/tests/test_rsx_draw_engine.c +index 8099901a..23ea04ea 100644 +--- a/libs/video/tests/test_rsx_draw_engine.c ++++ b/libs/video/tests/test_rsx_draw_engine.c +@@ -68,6 +68,7 @@ void cellGcm_replay_display_buffers_to_engine(void) {} + typedef struct { + u32 next_handle; + u8 alive[STUB_MAX_OBJECTS]; ++ u8 n_released[STUB_MAX_OBJECTS]; /* release calls per handle: each object is released once */ + + int n_texture_create, n_texture_release, n_texture_upload; + int n_color_create, n_color_release, n_color_seeded; +@@ -137,7 +138,7 @@ static void stub_texture_upload(void* u, u32 t, u32 face, u32 mip, u32 w, u32 h, + static void stub_release(void* u, u32 handle) + { + (void)u; +- if (handle && handle < STUB_MAX_OBJECTS) stub.alive[handle] = 0; ++ if (handle && handle < STUB_MAX_OBJECTS) { stub.alive[handle] = 0; stub.n_released[handle]++; } + stub.last_released = handle; + } + +@@ -1796,6 +1797,8 @@ static void test_depth_snapshot_release(void) + CHECK(stub.n_depth_create >= 3 && !stub.alive[second], + "a recreated depth target releases its old snapshot (%d depth targets)", + stub.n_depth_create); ++ CHECK(stub.n_released[second] == 1, ++ "and releases it once (%d calls)", stub.n_released[second]); + engine_down(); + } + diff --git a/tasks/sp00nznet__ps3recomp-604/solution/solve.sh b/tasks/sp00nznet__ps3recomp-604/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-604/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-604/task.toml b/tasks/sp00nznet__ps3recomp-604/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5388a3b8998cd29940bb5541eab17c88b8420ea8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-604/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-604" +description = "rsx_draw_engine: release a recreated depth target's snapshot once" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/604" +source_access = "auto" +built_at = "2026-11-16T16:09:59.692094+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:fa3be2fb9d016a90c1050055ff8866b00c893ee6a71a6e9b59f82b88d4edd9a1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "libs/video/rsx_draw_engine.c", + "libs/video/tests/test_rsx_draw_engine.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.123869+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-604/tests/capture.py b/tasks/sp00nznet__ps3recomp-604/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-604/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-604/tests/instruction.md b/tasks/sp00nznet__ps3recomp-604/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..30452a600123c597b5711bde787c7282fe912f30 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-604/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** rsx_draw_engine: release a recreated depth target's snapshot once + +## Description + +`eng_zdepth_get` released `z->snapshot` twice when it recreated a depth target. #502 added "the old size's snapshot goes with it" before the depth target's release, and #499 added the `z->conv` release followed by the same `z->snapshot` release; both merged into v0.18.0 side by side: + +```c +if (z->snapshot && g.be->texture_release) g.be->texture_release(g.be->user, z->snapshot); // #502 +if (z->handle) g.be->depth_target_release(g.be->user, z->handle); +if (z->conv) g.be->texture_release(g.be->user, z->conv); // #499 +if (z->snapshot) g.be->texture_release(g.be->user, z->snapshot); // same handle again +``` + +The second call hands the backend a handle it already released. The Metal backend ignores a retired slot and the Vulkan one finds no object, so nothing visible happens today; but the contract is one release per texture, and a backend that recycles handles immediately would free whatever took the slot in between. + +This drops the first call. The one after the conv texture covers the same snapshot, and the order of the releases is otherwise unchanged. + +`test_rsx_draw_engine` now counts release calls per stub handle and checks that the snapshot of a recreated depth target is released once. On v0.18.0 that check fails (2 calls); with the change it passes, and the whole test passes (clang, macOS, built as in `macos.yml`). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-604/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-604/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5c7f28ebeb41f2d5cf3948b2fcfee505a162b0d1 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-604/tests/oracle.patch @@ -0,0 +1,42 @@ +diff --git a/libs/video/rsx_draw_engine.c b/libs/video/rsx_draw_engine.c +index 8dff6011..0ecaf358 100644 +--- a/libs/video/rsx_draw_engine.c ++++ b/libs/video/rsx_draw_engine.c +@@ -996,7 +996,6 @@ static u32 eng_zdepth_get(u32 location, u32 offset, u32 rt_w, u32 rt_h) + + eng_zdepth* z = &g.zdepths[slot]; + /* The old size's snapshot goes with it: it can never be valid again. */ +- if (z->snapshot && g.be->texture_release) g.be->texture_release(g.be->user, z->snapshot); + if (z->handle) g.be->depth_target_release(g.be->user, z->handle); + if (z->conv) g.be->texture_release(g.be->user, z->conv); + if (z->snapshot) g.be->texture_release(g.be->user, z->snapshot); +diff --git a/libs/video/tests/test_rsx_draw_engine.c b/libs/video/tests/test_rsx_draw_engine.c +index 8099901a..23ea04ea 100644 +--- a/libs/video/tests/test_rsx_draw_engine.c ++++ b/libs/video/tests/test_rsx_draw_engine.c +@@ -68,6 +68,7 @@ void cellGcm_replay_display_buffers_to_engine(void) {} + typedef struct { + u32 next_handle; + u8 alive[STUB_MAX_OBJECTS]; ++ u8 n_released[STUB_MAX_OBJECTS]; /* release calls per handle: each object is released once */ + + int n_texture_create, n_texture_release, n_texture_upload; + int n_color_create, n_color_release, n_color_seeded; +@@ -137,7 +138,7 @@ static void stub_texture_upload(void* u, u32 t, u32 face, u32 mip, u32 w, u32 h, + static void stub_release(void* u, u32 handle) + { + (void)u; +- if (handle && handle < STUB_MAX_OBJECTS) stub.alive[handle] = 0; ++ if (handle && handle < STUB_MAX_OBJECTS) { stub.alive[handle] = 0; stub.n_released[handle]++; } + stub.last_released = handle; + } + +@@ -1796,6 +1797,8 @@ static void test_depth_snapshot_release(void) + CHECK(stub.n_depth_create >= 3 && !stub.alive[second], + "a recreated depth target releases its old snapshot (%d depth targets)", + stub.n_depth_create); ++ CHECK(stub.n_released[second] == 1, ++ "and releases it once (%d calls)", stub.n_released[second]); + engine_down(); + } + diff --git a/tasks/sp00nznet__ps3recomp-604/tests/test.sh b/tasks/sp00nznet__ps3recomp-604/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-604/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-604/tests/verifier.py b/tasks/sp00nznet__ps3recomp-604/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-604/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-606/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-606/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-606/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-606/instruction.md b/tasks/sp00nznet__ps3recomp-606/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..015f1b2f7d2ebecfab414c6fc04595d8bc45fa59 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-606/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** cellAudio: AUDIO_WAV and AUDIO_PEAK on the POSIX mix thread too, holes in AUDIO_RATE + +## Description + +`AUDIO_WAV=` (a raw f32le stereo 48 kHz dump of the final mix) and `AUDIO_PEAK=1` (the loudest sample of the mix) were written inline in the Windows mix thread, so on macOS and Linux there was no way to record what the mixer produced. They are now two helpers, `audio_dump_mix` and `audio_mix_peak`, that both mix threads call. The POSIX thread prints the peak once per second (`[audio-peak] N s: peak x`); the Windows thread keeps its output as it was. + +`AUDIO_RATE=1` on Windows also counts holes: a block with nothing in it right after a block with sound on the same port, which is the guest's audio engine being late, whatever the device does with the stream. It adds `holes a+b` (ports 0 and 1) to the line it already prints every 5 s. The counting is `#ifdef _WIN32`, since only that report uses it. + +How it was used: `AUDIO_WAV` plus a count of silent 256-frame blocks per 10 s is what showed that v0.17.0 played about half of the blocks of a title's audio engine as silence (the `SPU_PCSAMPLE` lookup per MFC access, fixed in #243); `holes` is what separates "the device ran dry" from "the guest was late". + +There is no automated test: the mixer needs a guest to feed it. Checked by running a title on macOS with `AUDIO_WAV` and `AUDIO_PEAK` (the dump is a valid f32 stream with the expected block count), and the file compiles with clang on macOS and MinGW GCC. + +Open PRs: none touches these lines except #213, a large branch, in `cellAudio.c` near the Windows `AUDIO_PEAK`/`AUDIO_WAV` code that this moves into helpers. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-606/solution/patch.diff b/tasks/sp00nznet__ps3recomp-606/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0d4326be03270523596c3503ed8bea6f03b0e890 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-606/solution/patch.diff @@ -0,0 +1,116 @@ +diff --git a/libs/audio/cellAudio.c b/libs/audio/cellAudio.c +index 02b751b2..f231ea26 100644 +--- a/libs/audio/cellAudio.c ++++ b/libs/audio/cellAudio.c +@@ -145,6 +145,9 @@ static u64 s_audio_start_us = 0; + + /* Mixing thread */ + static unsigned long long g_audio_dropped; /* frames the device had no room for */ ++#ifdef _WIN32 ++static unsigned g_audio_holes[CELL_AUDIO_PORT_MAX]; /* AUDIO_RATE: empty blocks right after a block with sound */ ++#endif + static volatile int s_mix_thread_running = 0; + static thread_t s_mix_thread; + #ifndef _WIN32 +@@ -492,6 +495,17 @@ static void audio_mix_one_block(void) + p, (unsigned long long)port->read_index, block_idx, map); + } } } + ++#ifdef _WIN32 /* reported by the Windows mix thread's AUDIO_RATE */ ++ /* AUDIO_RATE: a block with nothing in it right after one with sound is a hole, the guest's audio engine late ++ * with it (what the mix then plays is a click or a gap, whatever the device does). */ ++ { static int hole_on = -1; static u32 prev_nz[CELL_AUDIO_PORT_MAX]; ++ if (hole_on < 0) hole_on = getenv("AUDIO_RATE") ? 1 : 0; ++ if (hole_on) { int nz = 0; ++ for (u32 s2 = 0; s2 < CELL_AUDIO_BLOCK_SAMPLES * nch; s2 += 2) if (src[s2] != 0.0f) { nz = 1; break; } ++ if (!nz && prev_nz[p]) g_audio_holes[p]++; ++ prev_nz[p] = nz; } } ++#endif ++ + for (u32 s = 0; s < CELL_AUDIO_BLOCK_SAMPLES; s++) { + float left, right; + if (nch >= 2) { +@@ -559,6 +573,26 @@ static void audio_notify_event_queues(void) + } + } + ++/* The loudest sample of the block just mixed (AUDIO_PEAK). */ ++static float audio_mix_peak(void) ++{ ++ float pk = 0.0f; ++ for (u32 i = 0; i < CELL_AUDIO_BLOCK_SAMPLES * 2; i++) { ++ const float a = s_mix_buffer[i] < 0 ? -s_mix_buffer[i] : s_mix_buffer[i]; ++ if (a > pk) pk = a; ++ } ++ return pk; ++} ++ ++/* AUDIO_WAV=: append the final mix as raw f32le stereo 48 kHz ++ * (ffmpeg -f f32le -ar 48000 -ac 2 -i ). */ ++static void audio_dump_mix(void) ++{ ++ static FILE* wf = (FILE*)-1; ++ if (wf == (FILE*)-1) { const char* e = getenv("AUDIO_WAV"); wf = e ? fopen(e, "wb") : NULL; } ++ if (wf) fwrite(s_mix_buffer, sizeof(float), CELL_AUDIO_BLOCK_SAMPLES * 2, wf); ++} ++ + #ifdef _WIN32 + static unsigned long long g_audio_underruns; + static unsigned __stdcall audio_mix_thread_func(void* arg) +@@ -613,16 +647,10 @@ static unsigned __stdcall audio_mix_thread_func(void* arg) + /* AUDIO_PEAK=1: report the mixed block's peak amplitude periodically so + * "is any port producing sound" is answerable (LBP Bink movie audio). */ + { static int _ap = -1; if (_ap < 0) _ap = getenv("AUDIO_PEAK") ? 1 : 0; +- if (_ap) { static unsigned _n = 0; float pk = 0.0f; +- for (u32 i = 0; i < CELL_AUDIO_BLOCK_SAMPLES * 2; i++) { +- float a = s_mix_buffer[i]; if (a < 0) a = -a; if (a > pk) pk = a; } ++ if (_ap) { static unsigned _n = 0; const float pk = audio_mix_peak(); + if ((++_n % 200) == 0 || (pk > 0.001f && _n < 40)) + fprintf(stderr, "[audio-peak] block#%u peak=%.4f\n", _n, pk); } } +- /* AUDIO_WAV=: append the final mix as raw f32le stereo 48 kHz +- * (ffmpeg -f f32le -ar 48000 -ac 2 -i ). */ +- { static FILE* _wf = (FILE*)-1; +- if (_wf == (FILE*)-1) { const char* e = getenv("AUDIO_WAV"); _wf = e ? fopen(e, "wb") : NULL; } +- if (_wf) fwrite(s_mix_buffer, sizeof(float), CELL_AUDIO_BLOCK_SAMPLES * 2, _wf); } ++ audio_dump_mix(); + audio_backend_submit(s_mix_buffer, CELL_AUDIO_BLOCK_SAMPLES); + /* AUDIO_RATE=1: blocks mixed vs real time, and frames dropped. */ + { static int on = -1; if (on < 0) on = getenv("AUDIO_RATE") ? 1 : 0; +@@ -631,14 +659,15 @@ static unsigned __stdcall audio_mix_thread_func(void* arg) + { int nz = 0; for (u32 i = 0; i < CELL_AUDIO_BLOCK_SAMPLES * 2; i++) if (s_mix_buffer[i] != 0.0f) { nz = 1; break; } + if (!nz) z++; } + if (now - t0 >= 5000) { +- fprintf(stderr, "[audio-rate] %.1f blocks/s (real time 187.5), silent %.1f%%, dropped %.0f frames/s, underruns %llu, device buf %u%c", ++ fprintf(stderr, "[audio-rate] %.1f blocks/s (real time 187.5), silent %.1f%%, dropped %.0f frames/s, underruns %llu, device buf %u, holes %u+%u%c", + n * 1000.0 / (now - t0), n ? 100.0 * z / n : 0.0, (g_audio_dropped - d0) * 1000.0 / (now - t0), + g_audio_underruns - u0, + #if AUDIO_BACKEND_WASAPI +- (unsigned)s_wasapi_buf_frames, 10); ++ (unsigned)s_wasapi_buf_frames, g_audio_holes[0], g_audio_holes[1], 10); + #else +- 0u, 10); ++ 0u, g_audio_holes[0], g_audio_holes[1], 10); + #endif ++ g_audio_holes[0] = g_audio_holes[1] = 0; + n = z = 0; d0 = g_audio_dropped; u0 = g_audio_underruns; t0 = now; } } } + + /* Notify event queues */ +@@ -654,10 +683,18 @@ static void* audio_mix_thread_func(void* arg) + (void)arg; + printf("[cellAudio] Mixing thread started\n"); + ++ unsigned long blocks = 0; float peak = 0.0f; + while (s_mix_thread_running) { + audio_mix_one_block(); ++ audio_dump_mix(); + audio_backend_submit(s_mix_buffer, CELL_AUDIO_BLOCK_SAMPLES); + audio_notify_event_queues(); ++ /* AUDIO_PEAK=1: the loudest sample of every second of mixed output (187.5 blocks of 256). */ ++ { static int pk_on = -1; if (pk_on < 0) pk_on = getenv("AUDIO_PEAK") ? 1 : 0; ++ if (pk_on) { ++ const float pk = audio_mix_peak(); if (pk > peak) peak = pk; ++ if (++blocks % 188 == 0) { fprintf(stderr, "[audio-peak] %lu s: peak %.4f\n", blocks / 188, peak); peak = 0.0f; } ++ } } + + u32 queued = audio_backend_queued_samples(); + if (queued > CELL_AUDIO_BLOCK_SAMPLES * 4) { diff --git a/tasks/sp00nznet__ps3recomp-606/solution/solve.sh b/tasks/sp00nznet__ps3recomp-606/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-606/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-606/task.toml b/tasks/sp00nznet__ps3recomp-606/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..46db510cb4fedcb913d1f89c6f06f9432b159ea0 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-606/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-606" +description = "cellAudio: AUDIO_WAV and AUDIO_PEAK on the POSIX mix thread too, holes in AUDIO_RATE" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/606" +source_access = "auto" +built_at = "2026-11-16T16:09:59.690284+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:df6e02f2279a02e48bd9abd3fc6d41bcb1cffda7d727507fbd86fa0c5ec59f1b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "libs/audio/cellAudio.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 59 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.124351+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-606/tests/capture.py b/tasks/sp00nznet__ps3recomp-606/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-606/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-606/tests/instruction.md b/tasks/sp00nznet__ps3recomp-606/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..015f1b2f7d2ebecfab414c6fc04595d8bc45fa59 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-606/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** cellAudio: AUDIO_WAV and AUDIO_PEAK on the POSIX mix thread too, holes in AUDIO_RATE + +## Description + +`AUDIO_WAV=` (a raw f32le stereo 48 kHz dump of the final mix) and `AUDIO_PEAK=1` (the loudest sample of the mix) were written inline in the Windows mix thread, so on macOS and Linux there was no way to record what the mixer produced. They are now two helpers, `audio_dump_mix` and `audio_mix_peak`, that both mix threads call. The POSIX thread prints the peak once per second (`[audio-peak] N s: peak x`); the Windows thread keeps its output as it was. + +`AUDIO_RATE=1` on Windows also counts holes: a block with nothing in it right after a block with sound on the same port, which is the guest's audio engine being late, whatever the device does with the stream. It adds `holes a+b` (ports 0 and 1) to the line it already prints every 5 s. The counting is `#ifdef _WIN32`, since only that report uses it. + +How it was used: `AUDIO_WAV` plus a count of silent 256-frame blocks per 10 s is what showed that v0.17.0 played about half of the blocks of a title's audio engine as silence (the `SPU_PCSAMPLE` lookup per MFC access, fixed in #243); `holes` is what separates "the device ran dry" from "the guest was late". + +There is no automated test: the mixer needs a guest to feed it. Checked by running a title on macOS with `AUDIO_WAV` and `AUDIO_PEAK` (the dump is a valid f32 stream with the expected block count), and the file compiles with clang on macOS and MinGW GCC. + +Open PRs: none touches these lines except #213, a large branch, in `cellAudio.c` near the Windows `AUDIO_PEAK`/`AUDIO_WAV` code that this moves into helpers. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-606/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-606/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0d4326be03270523596c3503ed8bea6f03b0e890 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-606/tests/oracle.patch @@ -0,0 +1,116 @@ +diff --git a/libs/audio/cellAudio.c b/libs/audio/cellAudio.c +index 02b751b2..f231ea26 100644 +--- a/libs/audio/cellAudio.c ++++ b/libs/audio/cellAudio.c +@@ -145,6 +145,9 @@ static u64 s_audio_start_us = 0; + + /* Mixing thread */ + static unsigned long long g_audio_dropped; /* frames the device had no room for */ ++#ifdef _WIN32 ++static unsigned g_audio_holes[CELL_AUDIO_PORT_MAX]; /* AUDIO_RATE: empty blocks right after a block with sound */ ++#endif + static volatile int s_mix_thread_running = 0; + static thread_t s_mix_thread; + #ifndef _WIN32 +@@ -492,6 +495,17 @@ static void audio_mix_one_block(void) + p, (unsigned long long)port->read_index, block_idx, map); + } } } + ++#ifdef _WIN32 /* reported by the Windows mix thread's AUDIO_RATE */ ++ /* AUDIO_RATE: a block with nothing in it right after one with sound is a hole, the guest's audio engine late ++ * with it (what the mix then plays is a click or a gap, whatever the device does). */ ++ { static int hole_on = -1; static u32 prev_nz[CELL_AUDIO_PORT_MAX]; ++ if (hole_on < 0) hole_on = getenv("AUDIO_RATE") ? 1 : 0; ++ if (hole_on) { int nz = 0; ++ for (u32 s2 = 0; s2 < CELL_AUDIO_BLOCK_SAMPLES * nch; s2 += 2) if (src[s2] != 0.0f) { nz = 1; break; } ++ if (!nz && prev_nz[p]) g_audio_holes[p]++; ++ prev_nz[p] = nz; } } ++#endif ++ + for (u32 s = 0; s < CELL_AUDIO_BLOCK_SAMPLES; s++) { + float left, right; + if (nch >= 2) { +@@ -559,6 +573,26 @@ static void audio_notify_event_queues(void) + } + } + ++/* The loudest sample of the block just mixed (AUDIO_PEAK). */ ++static float audio_mix_peak(void) ++{ ++ float pk = 0.0f; ++ for (u32 i = 0; i < CELL_AUDIO_BLOCK_SAMPLES * 2; i++) { ++ const float a = s_mix_buffer[i] < 0 ? -s_mix_buffer[i] : s_mix_buffer[i]; ++ if (a > pk) pk = a; ++ } ++ return pk; ++} ++ ++/* AUDIO_WAV=: append the final mix as raw f32le stereo 48 kHz ++ * (ffmpeg -f f32le -ar 48000 -ac 2 -i ). */ ++static void audio_dump_mix(void) ++{ ++ static FILE* wf = (FILE*)-1; ++ if (wf == (FILE*)-1) { const char* e = getenv("AUDIO_WAV"); wf = e ? fopen(e, "wb") : NULL; } ++ if (wf) fwrite(s_mix_buffer, sizeof(float), CELL_AUDIO_BLOCK_SAMPLES * 2, wf); ++} ++ + #ifdef _WIN32 + static unsigned long long g_audio_underruns; + static unsigned __stdcall audio_mix_thread_func(void* arg) +@@ -613,16 +647,10 @@ static unsigned __stdcall audio_mix_thread_func(void* arg) + /* AUDIO_PEAK=1: report the mixed block's peak amplitude periodically so + * "is any port producing sound" is answerable (LBP Bink movie audio). */ + { static int _ap = -1; if (_ap < 0) _ap = getenv("AUDIO_PEAK") ? 1 : 0; +- if (_ap) { static unsigned _n = 0; float pk = 0.0f; +- for (u32 i = 0; i < CELL_AUDIO_BLOCK_SAMPLES * 2; i++) { +- float a = s_mix_buffer[i]; if (a < 0) a = -a; if (a > pk) pk = a; } ++ if (_ap) { static unsigned _n = 0; const float pk = audio_mix_peak(); + if ((++_n % 200) == 0 || (pk > 0.001f && _n < 40)) + fprintf(stderr, "[audio-peak] block#%u peak=%.4f\n", _n, pk); } } +- /* AUDIO_WAV=: append the final mix as raw f32le stereo 48 kHz +- * (ffmpeg -f f32le -ar 48000 -ac 2 -i ). */ +- { static FILE* _wf = (FILE*)-1; +- if (_wf == (FILE*)-1) { const char* e = getenv("AUDIO_WAV"); _wf = e ? fopen(e, "wb") : NULL; } +- if (_wf) fwrite(s_mix_buffer, sizeof(float), CELL_AUDIO_BLOCK_SAMPLES * 2, _wf); } ++ audio_dump_mix(); + audio_backend_submit(s_mix_buffer, CELL_AUDIO_BLOCK_SAMPLES); + /* AUDIO_RATE=1: blocks mixed vs real time, and frames dropped. */ + { static int on = -1; if (on < 0) on = getenv("AUDIO_RATE") ? 1 : 0; +@@ -631,14 +659,15 @@ static unsigned __stdcall audio_mix_thread_func(void* arg) + { int nz = 0; for (u32 i = 0; i < CELL_AUDIO_BLOCK_SAMPLES * 2; i++) if (s_mix_buffer[i] != 0.0f) { nz = 1; break; } + if (!nz) z++; } + if (now - t0 >= 5000) { +- fprintf(stderr, "[audio-rate] %.1f blocks/s (real time 187.5), silent %.1f%%, dropped %.0f frames/s, underruns %llu, device buf %u%c", ++ fprintf(stderr, "[audio-rate] %.1f blocks/s (real time 187.5), silent %.1f%%, dropped %.0f frames/s, underruns %llu, device buf %u, holes %u+%u%c", + n * 1000.0 / (now - t0), n ? 100.0 * z / n : 0.0, (g_audio_dropped - d0) * 1000.0 / (now - t0), + g_audio_underruns - u0, + #if AUDIO_BACKEND_WASAPI +- (unsigned)s_wasapi_buf_frames, 10); ++ (unsigned)s_wasapi_buf_frames, g_audio_holes[0], g_audio_holes[1], 10); + #else +- 0u, 10); ++ 0u, g_audio_holes[0], g_audio_holes[1], 10); + #endif ++ g_audio_holes[0] = g_audio_holes[1] = 0; + n = z = 0; d0 = g_audio_dropped; u0 = g_audio_underruns; t0 = now; } } } + + /* Notify event queues */ +@@ -654,10 +683,18 @@ static void* audio_mix_thread_func(void* arg) + (void)arg; + printf("[cellAudio] Mixing thread started\n"); + ++ unsigned long blocks = 0; float peak = 0.0f; + while (s_mix_thread_running) { + audio_mix_one_block(); ++ audio_dump_mix(); + audio_backend_submit(s_mix_buffer, CELL_AUDIO_BLOCK_SAMPLES); + audio_notify_event_queues(); ++ /* AUDIO_PEAK=1: the loudest sample of every second of mixed output (187.5 blocks of 256). */ ++ { static int pk_on = -1; if (pk_on < 0) pk_on = getenv("AUDIO_PEAK") ? 1 : 0; ++ if (pk_on) { ++ const float pk = audio_mix_peak(); if (pk > peak) peak = pk; ++ if (++blocks % 188 == 0) { fprintf(stderr, "[audio-peak] %lu s: peak %.4f\n", blocks / 188, peak); peak = 0.0f; } ++ } } + + u32 queued = audio_backend_queued_samples(); + if (queued > CELL_AUDIO_BLOCK_SAMPLES * 4) { diff --git a/tasks/sp00nznet__ps3recomp-606/tests/test.sh b/tasks/sp00nznet__ps3recomp-606/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-606/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-606/tests/verifier.py b/tasks/sp00nznet__ps3recomp-606/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-606/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-607/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-607/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-607/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-607/instruction.md b/tasks/sp00nznet__ps3recomp-607/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..07bea7ecd1636ca9dc0326f67e7a0cd5f76d58f6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-607/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** test_trophy_registration: link again, and run in CI + +## Description + +`libs/network/tests/test_trophy_registration.c` has not linked for a while, and nothing runs it, so it did not show. + +- `cellSysutilCheckCallback` now also pumps the message dialog (`cellMsgDialog_tick`, e56ea2f4), the PSN room transport (`np_psnr_pump`, #200) and the PSN terms check (`ps3_np_eula_tick`, #542). The fixture links `cellSysutil.c` and stubs none of them: three undefined symbols on v0.18.0. +- It also defines `g_ps3_guest_caller`, which `cellSysutil.c` already defines. clang lets that through; gcc reports a duplicate symbol. + +## Change + +- The fixture stubs the three pumps (as `test_license_area.c` and `test_dialog_abort.c` do) and uses `cellSysutil.c`'s `g_ps3_guest_caller`. +- `tools/test_trophy_registration.py` builds and runs it, like the other fixture scripts, so the `tools/test_*.py` loop in CI picks it up. + +## Tests + +- `python3 tools/test_trophy_registration.py` passes with clang and with gcc-16 (macOS arm64). Without the stubs the fixture does not link. +- Not run on Linux or Windows here (the script skips Windows, as the other POSIX-linked fixtures do). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-607/solution/patch.diff b/tasks/sp00nznet__ps3recomp-607/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7fa48c967b2d1687af10e849c2f0cce60af95b5b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-607/solution/patch.diff @@ -0,0 +1,51 @@ +diff --git a/libs/network/tests/test_trophy_registration.c b/libs/network/tests/test_trophy_registration.c +index cdbee09e..b08a5b24 100644 +--- a/libs/network/tests/test_trophy_registration.c ++++ b/libs/network/tests/test_trophy_registration.c +@@ -13,7 +13,12 @@ int spu_coh_is_reserved(uint32_t a) { (void)a; return 0; } + void spu_coh_notify_write(uint32_t a) { (void)a; } + void spu_lockline_lock(void) {} + void spu_lockline_unlock(void) {} +-ps3_guest_caller_fn g_ps3_guest_caller; ++/* g_ps3_guest_caller is cellSysutil.c's (defining it here too is a duplicate ++ * symbol under gcc). cellSysutilCheckCallback also pumps the message dialog, ++ * the PSN room transport and the PSN terms check; none is under test here. */ ++void cellMsgDialog_tick(void) {} ++void np_psnr_pump(void) {} ++void ps3_np_eula_tick(void) {} + static unsigned calls; + static void callback(u32 opd, u64 context, u64 status, u64 completed, u64 total, + u64 arg, u64 a, u64 b, u64 c) +diff --git a/tools/test_trophy_registration.py b/tools/test_trophy_registration.py +new file mode 100755 +index 00000000..39583d7d +--- /dev/null ++++ b/tools/test_trophy_registration.py +@@ -0,0 +1,27 @@ ++#!/usr/bin/env python3 ++"""Trophy registration delivers its completion through the guest's sysutil ++callbacks (libs/network/tests/test_trophy_registration.c, which compiles ++sceNpTrophy.c in and links cellSysutil.c).""" ++import os ++from pathlib import Path ++import subprocess ++import sys ++import tempfile ++ ++root = Path(__file__).resolve().parents[1] ++if os.name == 'nt': ++ print('SKIP: the trophy registration fixture uses POSIX linking') ++ raise SystemExit(0) ++with tempfile.TemporaryDirectory(prefix='trophy-registration-') as tmp: ++ binary = Path(tmp) / 'test' ++ linker = ['-Wl,-dead_strip', '-pthread'] if sys.platform == 'darwin' else ['-Wl,--gc-sections', '-pthread', '-lm'] ++ subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu17', '-O1', '-UNDEBUG', ++ '-ffunction-sections', '-fdata-sections', '-I' + str(root / 'include'), ++ str(root / 'libs/network/tests/test_trophy_registration.c'), ++ str(root / 'libs/system/cellSysutil.c'), *linker, ++ '-o', str(binary)], check=True) ++ result = subprocess.run([str(binary)], timeout=30, capture_output=True, text=True) ++ print(result.stdout.strip()) ++ if result.returncode: ++ print(result.stderr[-2000:]) ++ raise SystemExit('test_trophy_registration failed') diff --git a/tasks/sp00nznet__ps3recomp-607/solution/solve.sh b/tasks/sp00nznet__ps3recomp-607/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-607/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-607/task.toml b/tasks/sp00nznet__ps3recomp-607/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7a9e6a04dd1af8880b7e75be80fe571736ae0d57 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-607/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-607" +description = "test_trophy_registration: link again, and run in CI" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/607" +source_access = "auto" +built_at = "2026-11-16T16:09:59.638619+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5ac4ae542aa1d2fc38ce785ac9848d4acd2568ed3e6d5757b6d2a424153639ba" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:44Z" +diff_format = "unified" +context_files = [ + "libs/network/tests/test_trophy_registration.c", + "tools/test_trophy_registration.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 34 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.124885+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-607/tests/capture.py b/tasks/sp00nznet__ps3recomp-607/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-607/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-607/tests/instruction.md b/tasks/sp00nznet__ps3recomp-607/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..07bea7ecd1636ca9dc0326f67e7a0cd5f76d58f6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-607/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** test_trophy_registration: link again, and run in CI + +## Description + +`libs/network/tests/test_trophy_registration.c` has not linked for a while, and nothing runs it, so it did not show. + +- `cellSysutilCheckCallback` now also pumps the message dialog (`cellMsgDialog_tick`, e56ea2f4), the PSN room transport (`np_psnr_pump`, #200) and the PSN terms check (`ps3_np_eula_tick`, #542). The fixture links `cellSysutil.c` and stubs none of them: three undefined symbols on v0.18.0. +- It also defines `g_ps3_guest_caller`, which `cellSysutil.c` already defines. clang lets that through; gcc reports a duplicate symbol. + +## Change + +- The fixture stubs the three pumps (as `test_license_area.c` and `test_dialog_abort.c` do) and uses `cellSysutil.c`'s `g_ps3_guest_caller`. +- `tools/test_trophy_registration.py` builds and runs it, like the other fixture scripts, so the `tools/test_*.py` loop in CI picks it up. + +## Tests + +- `python3 tools/test_trophy_registration.py` passes with clang and with gcc-16 (macOS arm64). Without the stubs the fixture does not link. +- Not run on Linux or Windows here (the script skips Windows, as the other POSIX-linked fixtures do). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-607/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-607/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7fa48c967b2d1687af10e849c2f0cce60af95b5b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-607/tests/oracle.patch @@ -0,0 +1,51 @@ +diff --git a/libs/network/tests/test_trophy_registration.c b/libs/network/tests/test_trophy_registration.c +index cdbee09e..b08a5b24 100644 +--- a/libs/network/tests/test_trophy_registration.c ++++ b/libs/network/tests/test_trophy_registration.c +@@ -13,7 +13,12 @@ int spu_coh_is_reserved(uint32_t a) { (void)a; return 0; } + void spu_coh_notify_write(uint32_t a) { (void)a; } + void spu_lockline_lock(void) {} + void spu_lockline_unlock(void) {} +-ps3_guest_caller_fn g_ps3_guest_caller; ++/* g_ps3_guest_caller is cellSysutil.c's (defining it here too is a duplicate ++ * symbol under gcc). cellSysutilCheckCallback also pumps the message dialog, ++ * the PSN room transport and the PSN terms check; none is under test here. */ ++void cellMsgDialog_tick(void) {} ++void np_psnr_pump(void) {} ++void ps3_np_eula_tick(void) {} + static unsigned calls; + static void callback(u32 opd, u64 context, u64 status, u64 completed, u64 total, + u64 arg, u64 a, u64 b, u64 c) +diff --git a/tools/test_trophy_registration.py b/tools/test_trophy_registration.py +new file mode 100755 +index 00000000..39583d7d +--- /dev/null ++++ b/tools/test_trophy_registration.py +@@ -0,0 +1,27 @@ ++#!/usr/bin/env python3 ++"""Trophy registration delivers its completion through the guest's sysutil ++callbacks (libs/network/tests/test_trophy_registration.c, which compiles ++sceNpTrophy.c in and links cellSysutil.c).""" ++import os ++from pathlib import Path ++import subprocess ++import sys ++import tempfile ++ ++root = Path(__file__).resolve().parents[1] ++if os.name == 'nt': ++ print('SKIP: the trophy registration fixture uses POSIX linking') ++ raise SystemExit(0) ++with tempfile.TemporaryDirectory(prefix='trophy-registration-') as tmp: ++ binary = Path(tmp) / 'test' ++ linker = ['-Wl,-dead_strip', '-pthread'] if sys.platform == 'darwin' else ['-Wl,--gc-sections', '-pthread', '-lm'] ++ subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu17', '-O1', '-UNDEBUG', ++ '-ffunction-sections', '-fdata-sections', '-I' + str(root / 'include'), ++ str(root / 'libs/network/tests/test_trophy_registration.c'), ++ str(root / 'libs/system/cellSysutil.c'), *linker, ++ '-o', str(binary)], check=True) ++ result = subprocess.run([str(binary)], timeout=30, capture_output=True, text=True) ++ print(result.stdout.strip()) ++ if result.returncode: ++ print(result.stderr[-2000:]) ++ raise SystemExit('test_trophy_registration failed') diff --git a/tasks/sp00nznet__ps3recomp-607/tests/test.sh b/tasks/sp00nznet__ps3recomp-607/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-607/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-607/tests/verifier.py b/tasks/sp00nznet__ps3recomp-607/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-607/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-608/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-608/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-608/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-608/instruction.md b/tasks/sp00nznet__ps3recomp-608/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..95e3fa5b523910e72e184dd4d1a2526411f0389a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-608/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** test_gcm_flip_status: execute each flip before its tick, and run in CI + +## Description + +`libs/video/tests/test_gcm_flip_status.c` fails its first assert (line 41) on master, and has since v0.16.0. Nothing runs it, so it did not show. + +b00e0e2a ("a beat with no flip outstanding completes nothing") made `cellGcmTickFlip` complete only a flip the RSX has executed: a flip marker the drain reached, or a flip requested outside the command stream. The fixture was written a day earlier (fa001d07) and requests its flips with `cellGcmResetFlipStatus` alone. Its first tick therefore completes nothing, and `flips == 1 && status == DONE` fails. The code is right; the fixture predates it. + +## Change + +- The fixture executes each flip before the tick that is to complete it, as the drain does when it reaches the flip's marker (`s_fifo_flips_reached++`). +- The plain case first checks that a tick before the execution completes nothing and runs no handler, which covers b00e0e2a. +- `tools/test_gcm_flip_status.py` builds and runs it, like the other GCM fixture scripts, so the `tools/test_*.py` loop in CI picks it up. + +## Tests + +- `python3 tools/test_gcm_flip_status.py` passes with clang and with gcc-16 (macOS arm64). +- Both rules still fail it: + - completing a flip on every beat again (before b00e0e2a) fails the new check; + - dropping the request-sequence check of fa001d07 fails the late-completion case. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-608/solution/patch.diff b/tasks/sp00nznet__ps3recomp-608/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4854799742bb94886edc6c48f8baeb0dc6f507c6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-608/solution/patch.diff @@ -0,0 +1,92 @@ +diff --git a/libs/video/tests/test_gcm_flip_status.c b/libs/video/tests/test_gcm_flip_status.c +index d4d3ed7b..4f14a60d 100644 +--- a/libs/video/tests/test_gcm_flip_status.c ++++ b/libs/video/tests/test_gcm_flip_status.c +@@ -7,6 +7,8 @@ + * guest thread next pumps, and the title may have requested another flip by + * then. That newer request must stay WAITING until a tick of its own + * completes it, and so must one that outlives cellGcmSetWaitFlip's bound. ++ * A beat completes only a flip the RSX has executed (b00e0e2a): each flip ++ * here is executed before the tick that is to complete it. + */ + #include "../cellGcmSys.c" + #include +@@ -21,6 +23,8 @@ void spu_coh_notify_write(uint32_t a) { (void)a; } + void spu_lockline_lock(void) {} + void spu_lockline_unlock(void) {} + ps3_guest_caller_fn g_ps3_guest_caller; ++/* What the drain does when it reaches a flip queued in the command stream. */ ++static void flip_executed(void) { s_fifo_flips_reached++; } + static unsigned flips; + static void callback(uint32_t opd, uint64_t a, uint64_t b, uint64_t c, + uint64_t d, uint64_t e, uint64_t f, uint64_t h, uint64_t i) +@@ -33,11 +37,15 @@ int main(void) + g_ps3_guest_caller = callback; + s_flip_handler_opd = 0x400; + +- /* The plain case: request, tick, deliver. */ ++ /* The plain case: request, execute, tick, deliver. */ + cellGcmResetFlipStatus(); + assert(cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_WAITING); + cellGcmTickFlip(); + ppu_gcm_pump(); ++ assert(flips == 0 && cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_WAITING); ++ flip_executed(); ++ cellGcmTickFlip(); ++ ppu_gcm_pump(); + assert(flips == 1 && cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_DONE); + /* No flip outstanding: a tick completes nothing and calls no handler. */ + cellGcmTickFlip(); +@@ -47,10 +55,12 @@ int main(void) + /* A newer request between the tick and the delivery: the late completion + * runs the handler for the old flip but leaves the new one WAITING. */ + cellGcmResetFlipStatus(); ++ flip_executed(); + cellGcmTickFlip(); + cellGcmResetFlipStatus(); + ppu_gcm_pump(); + assert(flips == 2 && cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_WAITING); ++ flip_executed(); + cellGcmTickFlip(); + ppu_gcm_pump(); + assert(flips == 3 && cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_DONE); +@@ -60,6 +70,7 @@ int main(void) + cellGcmResetFlipStatus(); + cellGcmSetWaitFlip(); + assert(cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_WAITING); ++ flip_executed(); + cellGcmTickFlip(); + ppu_gcm_pump(); + assert(flips == 4 && cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_DONE); +diff --git a/tools/test_gcm_flip_status.py b/tools/test_gcm_flip_status.py +new file mode 100755 +index 00000000..50469179 +--- /dev/null ++++ b/tools/test_gcm_flip_status.py +@@ -0,0 +1,26 @@ ++#!/usr/bin/env python3 ++"""The flip status against a late flip completion ++(libs/video/tests/test_gcm_flip_status.c, which compiles cellGcmSys.c in).""" ++import os ++from pathlib import Path ++import subprocess ++import sys ++import tempfile ++ ++root = Path(__file__).resolve().parents[1] ++if os.name == 'nt': ++ print('SKIP: the GCM flip status fixture uses POSIX linking') ++ raise SystemExit(0) ++with tempfile.TemporaryDirectory(prefix='gcm-flip-status-') as tmp: ++ binary = Path(tmp) / 'test' ++ linker = ['-Wl,-dead_strip', '-pthread'] if sys.platform == 'darwin' else ['-Wl,--gc-sections', '-pthread', '-lm'] ++ subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu17', '-O1', '-UNDEBUG', ++ '-ffunction-sections', '-fdata-sections', ++ '-I' + str(root / 'include'), '-I' + str(root / 'libs/video'), ++ str(root / 'libs/video/tests/test_gcm_flip_status.c'), *linker, ++ '-o', str(binary)], check=True) ++ result = subprocess.run([str(binary)], timeout=60, capture_output=True, text=True) ++ print(result.stdout.strip()) ++ if result.returncode: ++ print(result.stderr[-2000:]) ++ raise SystemExit('test_gcm_flip_status failed') diff --git a/tasks/sp00nznet__ps3recomp-608/solution/solve.sh b/tasks/sp00nznet__ps3recomp-608/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-608/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-608/task.toml b/tasks/sp00nznet__ps3recomp-608/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..24a3322453bff5bf4d8b8e9da4ef22d88a325263 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-608/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-608" +description = "test_gcm_flip_status: execute each flip before its tick, and run in CI" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/608" +source_access = "auto" +built_at = "2026-11-16T16:09:59.688412+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6fef54b44b28a2776d663af38487027b58a06104324a5b035f897bdba877005e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "libs/video/tests/test_gcm_flip_status.c", + "tools/test_gcm_flip_status.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 39 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.125393+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-608/tests/capture.py b/tasks/sp00nznet__ps3recomp-608/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-608/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-608/tests/instruction.md b/tasks/sp00nznet__ps3recomp-608/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..95e3fa5b523910e72e184dd4d1a2526411f0389a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-608/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** test_gcm_flip_status: execute each flip before its tick, and run in CI + +## Description + +`libs/video/tests/test_gcm_flip_status.c` fails its first assert (line 41) on master, and has since v0.16.0. Nothing runs it, so it did not show. + +b00e0e2a ("a beat with no flip outstanding completes nothing") made `cellGcmTickFlip` complete only a flip the RSX has executed: a flip marker the drain reached, or a flip requested outside the command stream. The fixture was written a day earlier (fa001d07) and requests its flips with `cellGcmResetFlipStatus` alone. Its first tick therefore completes nothing, and `flips == 1 && status == DONE` fails. The code is right; the fixture predates it. + +## Change + +- The fixture executes each flip before the tick that is to complete it, as the drain does when it reaches the flip's marker (`s_fifo_flips_reached++`). +- The plain case first checks that a tick before the execution completes nothing and runs no handler, which covers b00e0e2a. +- `tools/test_gcm_flip_status.py` builds and runs it, like the other GCM fixture scripts, so the `tools/test_*.py` loop in CI picks it up. + +## Tests + +- `python3 tools/test_gcm_flip_status.py` passes with clang and with gcc-16 (macOS arm64). +- Both rules still fail it: + - completing a flip on every beat again (before b00e0e2a) fails the new check; + - dropping the request-sequence check of fa001d07 fails the late-completion case. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-608/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-608/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4854799742bb94886edc6c48f8baeb0dc6f507c6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-608/tests/oracle.patch @@ -0,0 +1,92 @@ +diff --git a/libs/video/tests/test_gcm_flip_status.c b/libs/video/tests/test_gcm_flip_status.c +index d4d3ed7b..4f14a60d 100644 +--- a/libs/video/tests/test_gcm_flip_status.c ++++ b/libs/video/tests/test_gcm_flip_status.c +@@ -7,6 +7,8 @@ + * guest thread next pumps, and the title may have requested another flip by + * then. That newer request must stay WAITING until a tick of its own + * completes it, and so must one that outlives cellGcmSetWaitFlip's bound. ++ * A beat completes only a flip the RSX has executed (b00e0e2a): each flip ++ * here is executed before the tick that is to complete it. + */ + #include "../cellGcmSys.c" + #include +@@ -21,6 +23,8 @@ void spu_coh_notify_write(uint32_t a) { (void)a; } + void spu_lockline_lock(void) {} + void spu_lockline_unlock(void) {} + ps3_guest_caller_fn g_ps3_guest_caller; ++/* What the drain does when it reaches a flip queued in the command stream. */ ++static void flip_executed(void) { s_fifo_flips_reached++; } + static unsigned flips; + static void callback(uint32_t opd, uint64_t a, uint64_t b, uint64_t c, + uint64_t d, uint64_t e, uint64_t f, uint64_t h, uint64_t i) +@@ -33,11 +37,15 @@ int main(void) + g_ps3_guest_caller = callback; + s_flip_handler_opd = 0x400; + +- /* The plain case: request, tick, deliver. */ ++ /* The plain case: request, execute, tick, deliver. */ + cellGcmResetFlipStatus(); + assert(cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_WAITING); + cellGcmTickFlip(); + ppu_gcm_pump(); ++ assert(flips == 0 && cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_WAITING); ++ flip_executed(); ++ cellGcmTickFlip(); ++ ppu_gcm_pump(); + assert(flips == 1 && cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_DONE); + /* No flip outstanding: a tick completes nothing and calls no handler. */ + cellGcmTickFlip(); +@@ -47,10 +55,12 @@ int main(void) + /* A newer request between the tick and the delivery: the late completion + * runs the handler for the old flip but leaves the new one WAITING. */ + cellGcmResetFlipStatus(); ++ flip_executed(); + cellGcmTickFlip(); + cellGcmResetFlipStatus(); + ppu_gcm_pump(); + assert(flips == 2 && cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_WAITING); ++ flip_executed(); + cellGcmTickFlip(); + ppu_gcm_pump(); + assert(flips == 3 && cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_DONE); +@@ -60,6 +70,7 @@ int main(void) + cellGcmResetFlipStatus(); + cellGcmSetWaitFlip(); + assert(cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_WAITING); ++ flip_executed(); + cellGcmTickFlip(); + ppu_gcm_pump(); + assert(flips == 4 && cellGcmGetFlipStatus() == CELL_GCM_FLIP_STATUS_DONE); +diff --git a/tools/test_gcm_flip_status.py b/tools/test_gcm_flip_status.py +new file mode 100755 +index 00000000..50469179 +--- /dev/null ++++ b/tools/test_gcm_flip_status.py +@@ -0,0 +1,26 @@ ++#!/usr/bin/env python3 ++"""The flip status against a late flip completion ++(libs/video/tests/test_gcm_flip_status.c, which compiles cellGcmSys.c in).""" ++import os ++from pathlib import Path ++import subprocess ++import sys ++import tempfile ++ ++root = Path(__file__).resolve().parents[1] ++if os.name == 'nt': ++ print('SKIP: the GCM flip status fixture uses POSIX linking') ++ raise SystemExit(0) ++with tempfile.TemporaryDirectory(prefix='gcm-flip-status-') as tmp: ++ binary = Path(tmp) / 'test' ++ linker = ['-Wl,-dead_strip', '-pthread'] if sys.platform == 'darwin' else ['-Wl,--gc-sections', '-pthread', '-lm'] ++ subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu17', '-O1', '-UNDEBUG', ++ '-ffunction-sections', '-fdata-sections', ++ '-I' + str(root / 'include'), '-I' + str(root / 'libs/video'), ++ str(root / 'libs/video/tests/test_gcm_flip_status.c'), *linker, ++ '-o', str(binary)], check=True) ++ result = subprocess.run([str(binary)], timeout=60, capture_output=True, text=True) ++ print(result.stdout.strip()) ++ if result.returncode: ++ print(result.stderr[-2000:]) ++ raise SystemExit('test_gcm_flip_status failed') diff --git a/tasks/sp00nznet__ps3recomp-608/tests/test.sh b/tasks/sp00nznet__ps3recomp-608/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-608/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-608/tests/verifier.py b/tasks/sp00nznet__ps3recomp-608/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-608/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-609/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-609/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-609/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-609/instruction.md b/tasks/sp00nznet__ps3recomp-609/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f99e365300b2fd67caee440bdd76a3a44e924cd0 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-609/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** rsx_shader_msl: name the translator in the MSL cache by a hash of its sources + +## Description + +#511's disk cache (`PS3RECOMP_MSL_CACHE`) marks each file with the translator that wrote it, and uses the build time for that (`kTranslatorBuild = __DATE__ " " __TIME__`). Any rebuild of `rsx_shader_msl.cpp` gets a new time, even one that changes nothing in the translator, and so retires the whole cache. + +A port whose build script rebuilds the runtime from a clean tree (after a patch or pin change) is back to translating every shader on the FIFO walker's thread on its next run. In a retail title's opening cutscene that means walker passes of 160-360 ms and visible stutter, on every run after a rebuild. + +## Change + +- CMake hashes `rsx_shader_msl.cpp` and `rsx_shader_msl.h`: SHA-256 of their SHA-256s, cut to 23 hex digits to fit the 24-byte header field. +- The hash is passed as `PS3RECOMP_MSL_TRANSLATOR_ID` on `ps3recomp_msl_translation`. +- Both files are configure dependencies, so an edit to either reconfigures and gives a new id. What the build time was for, retiring files an older translator wrote, still happens. +- `kTranslatorBuild` takes the define when it is there. A build without it (another build system) keeps the build time. + +## Tests + +- Two separate configures of the same tree give the same id (`13f91979835c1d902bb0293`). +- An edit to `rsx_shader_msl.h` reconfigures on the next build and gives a new one. +- `test_shader_msl` (with its disk-cache cases): 167 passed, 0 failed (macOS arm64). +- In the title, the cache written before a clean rebuild of the runtime is still used after it: no new file is written for the shaders it already has. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-609/solution/patch.diff b/tasks/sp00nznet__ps3recomp-609/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3ed7c6e1a60dbc970e176e7516923e5bbf2bcdc8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-609/solution/patch.diff @@ -0,0 +1,47 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..6c11b0d0 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -277,6 +277,21 @@ if(UNIX) + endif() + endforeach() + endif() ++ # The translator's identity in the MSL translation cache: a hash of its ++ # sources, so a rebuild that changes nothing keeps the cached files and ++ # an edit to the translator retires them. (Its build time did the ++ # latter too, and threw the whole cache away on every rebuild.) ++ set(_msl_sources libs/video/rsx_shader_msl.cpp libs/video/rsx_shader_msl.h) ++ set(_msl_text "") ++ foreach(f IN LISTS _msl_sources) ++ file(SHA256 "${CMAKE_CURRENT_SOURCE_DIR}/${f}" _h) ++ string(APPEND _msl_text "${_h}") ++ endforeach() ++ string(SHA256 _msl_id "${_msl_text}") ++ string(SUBSTRING "${_msl_id}" 0 23 _msl_id) ++ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${_msl_sources}) ++ target_compile_definitions(ps3recomp_msl_translation INTERFACE ++ "PS3RECOMP_MSL_TRANSLATOR_ID=\"${_msl_id}\"") + target_link_libraries(ps3recomp_runtime PRIVATE ps3recomp_msl_translation) + set(PS3RECOMP_MSL_TRANSLATION ON) + message(STATUS " Shaders: guest programs translated to MSL (glslang ${glslang_VERSION}, ${SPVC_LIBS})") +diff --git a/libs/video/rsx_shader_msl.cpp b/libs/video/rsx_shader_msl.cpp +index 7dc6fd7f..473470fa 100644 +--- a/libs/video/rsx_shader_msl.cpp ++++ b/libs/video/rsx_shader_msl.cpp +@@ -224,7 +224,16 @@ done: + * this file's build: a file written by any other combination is a miss. */ + const u32 kCacheFormat = 1; + const u32 kCacheMagic = 0x4C534D52u; /* "RMSL" */ ++/* The translator's identity: what it was built from stands for the front-end ++ * and spirv-cross options above and the binding contract in rsx_shader_msl.h. ++ * The build passes a hash of those two files (CMakeLists.txt), so the files an ++ * older translator wrote become misses and a plain rebuild keeps them; without ++ * it, this file's compile time stands in, which retires them on every rebuild. */ ++#ifdef PS3RECOMP_MSL_TRANSLATOR_ID ++const char kTranslatorBuild[24] = PS3RECOMP_MSL_TRANSLATOR_ID; ++#else + const char kTranslatorBuild[24] = __DATE__ " " __TIME__; ++#endif + + struct Cache { + std::mutex lock; diff --git a/tasks/sp00nznet__ps3recomp-609/solution/solve.sh b/tasks/sp00nznet__ps3recomp-609/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-609/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-609/task.toml b/tasks/sp00nznet__ps3recomp-609/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..adcaf2a19a5b3fc3294ede4db19dc3d47108437f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-609/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-609" +description = "rsx_shader_msl: name the translator in the MSL cache by a hash of its sources" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/609" +source_access = "auto" +built_at = "2026-11-16T16:09:59.686677+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:372c1c47d4429ae7c4165ca1cbc3ca6ff786a9685ed0b1944f65a7cc5c5726ea" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "CMakeLists.txt", + "libs/video/rsx_shader_msl.cpp", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 24 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.125919+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-609/tests/capture.py b/tasks/sp00nznet__ps3recomp-609/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-609/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-609/tests/instruction.md b/tasks/sp00nznet__ps3recomp-609/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f99e365300b2fd67caee440bdd76a3a44e924cd0 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-609/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** rsx_shader_msl: name the translator in the MSL cache by a hash of its sources + +## Description + +#511's disk cache (`PS3RECOMP_MSL_CACHE`) marks each file with the translator that wrote it, and uses the build time for that (`kTranslatorBuild = __DATE__ " " __TIME__`). Any rebuild of `rsx_shader_msl.cpp` gets a new time, even one that changes nothing in the translator, and so retires the whole cache. + +A port whose build script rebuilds the runtime from a clean tree (after a patch or pin change) is back to translating every shader on the FIFO walker's thread on its next run. In a retail title's opening cutscene that means walker passes of 160-360 ms and visible stutter, on every run after a rebuild. + +## Change + +- CMake hashes `rsx_shader_msl.cpp` and `rsx_shader_msl.h`: SHA-256 of their SHA-256s, cut to 23 hex digits to fit the 24-byte header field. +- The hash is passed as `PS3RECOMP_MSL_TRANSLATOR_ID` on `ps3recomp_msl_translation`. +- Both files are configure dependencies, so an edit to either reconfigures and gives a new id. What the build time was for, retiring files an older translator wrote, still happens. +- `kTranslatorBuild` takes the define when it is there. A build without it (another build system) keeps the build time. + +## Tests + +- Two separate configures of the same tree give the same id (`13f91979835c1d902bb0293`). +- An edit to `rsx_shader_msl.h` reconfigures on the next build and gives a new one. +- `test_shader_msl` (with its disk-cache cases): 167 passed, 0 failed (macOS arm64). +- In the title, the cache written before a clean rebuild of the runtime is still used after it: no new file is written for the shaders it already has. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-609/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-609/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3ed7c6e1a60dbc970e176e7516923e5bbf2bcdc8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-609/tests/oracle.patch @@ -0,0 +1,47 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..6c11b0d0 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -277,6 +277,21 @@ if(UNIX) + endif() + endforeach() + endif() ++ # The translator's identity in the MSL translation cache: a hash of its ++ # sources, so a rebuild that changes nothing keeps the cached files and ++ # an edit to the translator retires them. (Its build time did the ++ # latter too, and threw the whole cache away on every rebuild.) ++ set(_msl_sources libs/video/rsx_shader_msl.cpp libs/video/rsx_shader_msl.h) ++ set(_msl_text "") ++ foreach(f IN LISTS _msl_sources) ++ file(SHA256 "${CMAKE_CURRENT_SOURCE_DIR}/${f}" _h) ++ string(APPEND _msl_text "${_h}") ++ endforeach() ++ string(SHA256 _msl_id "${_msl_text}") ++ string(SUBSTRING "${_msl_id}" 0 23 _msl_id) ++ set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${_msl_sources}) ++ target_compile_definitions(ps3recomp_msl_translation INTERFACE ++ "PS3RECOMP_MSL_TRANSLATOR_ID=\"${_msl_id}\"") + target_link_libraries(ps3recomp_runtime PRIVATE ps3recomp_msl_translation) + set(PS3RECOMP_MSL_TRANSLATION ON) + message(STATUS " Shaders: guest programs translated to MSL (glslang ${glslang_VERSION}, ${SPVC_LIBS})") +diff --git a/libs/video/rsx_shader_msl.cpp b/libs/video/rsx_shader_msl.cpp +index 7dc6fd7f..473470fa 100644 +--- a/libs/video/rsx_shader_msl.cpp ++++ b/libs/video/rsx_shader_msl.cpp +@@ -224,7 +224,16 @@ done: + * this file's build: a file written by any other combination is a miss. */ + const u32 kCacheFormat = 1; + const u32 kCacheMagic = 0x4C534D52u; /* "RMSL" */ ++/* The translator's identity: what it was built from stands for the front-end ++ * and spirv-cross options above and the binding contract in rsx_shader_msl.h. ++ * The build passes a hash of those two files (CMakeLists.txt), so the files an ++ * older translator wrote become misses and a plain rebuild keeps them; without ++ * it, this file's compile time stands in, which retires them on every rebuild. */ ++#ifdef PS3RECOMP_MSL_TRANSLATOR_ID ++const char kTranslatorBuild[24] = PS3RECOMP_MSL_TRANSLATOR_ID; ++#else + const char kTranslatorBuild[24] = __DATE__ " " __TIME__; ++#endif + + struct Cache { + std::mutex lock; diff --git a/tasks/sp00nznet__ps3recomp-609/tests/test.sh b/tasks/sp00nznet__ps3recomp-609/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-609/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-609/tests/verifier.py b/tasks/sp00nznet__ps3recomp-609/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-609/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-610/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-610/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-610/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-610/instruction.md b/tasks/sp00nznet__ps3recomp-610/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e754dba1b02a314ddd2557d59ad381f448389d26 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-610/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** ppu_loader: build with MinGW GCC + +## Description + +`runtime/ppu/ppu_loader.cpp` does not compile with MinGW-w64 GCC. MSVC and clang accept both things below; GCC does not (the file is built by the game project, not by the runtime library, so the runtime's own CI never compiles it with GCC; #402 made the tests build with GCC, this is the loader). + +- `samp_stack_guest` (the `PS3_SAMPLE_*` sampler) reads the sampled thread's stack under `__try` / `__except`, and GCC has no structured exception handling: `error: expected 'catch' before '__except'`. Without `_MSC_VER` it asks `ReadProcessMemory`, which fails on an unreadable address where a plain read would fault. +- `ppu_resv_break` was declared `extern "C"` and defined `static inline` further down: `error: 'void ppu_resv_break(uint64_t)' was declared 'extern' and later 'static'`. It is now declared `static inline` the same way; nothing else refers to it by name (`ppu_resv_break_store` and `ppu_resv_break_line` are the exported ones). + +Checked: `x86_64-w64-mingw32-g++ -std=c++20 -fsyntax-only` on `ppu_loader.cpp` reports the errors above on v0.18.0 and none with this change (and the whole host of a game port cross-builds and links with MinGW GCC on macOS); clang on macOS still compiles it. MSVC and clang-cl take the `__try` branch exactly as before. + +No test: it is a compile fix, and the loader needs the generated `ppu_recomp.h` of a game project. + +No open PR touches these lines (#528, #556, #596 and #599 change other parts of `ppu_loader.cpp`). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-610/solution/patch.diff b/tasks/sp00nznet__ps3recomp-610/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f578fcf2ba3cc620b7e37062b6b41781ef38ecaf --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-610/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/runtime/ppu/ppu_loader.cpp b/runtime/ppu/ppu_loader.cpp +index 9309f2d3..6252c832 100644 +--- a/runtime/ppu/ppu_loader.cpp ++++ b/runtime/ppu/ppu_loader.cpp +@@ -632,7 +632,12 @@ static uint32_t samp_stack_guest(HANDLE h, const CONTEXT* c) + const uintptr_t* sp = (const uintptr_t*)c->Rsp; + for (int i = 0; i < 512; i++) { /* 4 KB of stack */ + uintptr_t v; ++#ifdef _MSC_VER + __try { v = sp[i]; } __except (1) { return 0; } ++#else ++ /* no SEH in GCC/MinGW: ReadProcessMemory fails on an unreadable address where a plain read would fault */ ++ if (!ReadProcessMemory(GetCurrentProcess(), sp + i, &v, sizeof v, NULL)) return 0; ++#endif + uint32_t g = samp_lookup(v); + if (g) return g; + } +@@ -788,7 +793,7 @@ static DWORD WINAPI samp_thread(LPVOID p) + * Writing the word leaves memory self-consistent: lwarx, the CAS and the + * polling reader all see the same thing, so the guest behaves as it would if + * whatever should have cleared the counter had done so. */ +-extern "C" void ppu_resv_break(uint64_t ea); ++static inline void ppu_resv_break(uint64_t ea); /* defined below; GCC rejects extern followed by static */ + static DWORD WINAPI poke_thread(LPVOID p) + { + const uint32_t ea = (uint32_t)(uintptr_t)p; diff --git a/tasks/sp00nznet__ps3recomp-610/solution/solve.sh b/tasks/sp00nznet__ps3recomp-610/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-610/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-610/task.toml b/tasks/sp00nznet__ps3recomp-610/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..48ab3a324942b664c5bdda4a820bcfe2caaf78fc --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-610/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-610" +description = "ppu_loader: build with MinGW GCC" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/610" +source_access = "auto" +built_at = "2026-11-16T16:09:59.685128+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9e72dd74d08241821e7197a464677a2f9276fb24cc45cf1d3d640c2e808dc8ff" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "runtime/ppu/ppu_loader.cpp", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 7 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.126432+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-610/tests/capture.py b/tasks/sp00nznet__ps3recomp-610/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-610/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-610/tests/instruction.md b/tasks/sp00nznet__ps3recomp-610/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e754dba1b02a314ddd2557d59ad381f448389d26 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-610/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** ppu_loader: build with MinGW GCC + +## Description + +`runtime/ppu/ppu_loader.cpp` does not compile with MinGW-w64 GCC. MSVC and clang accept both things below; GCC does not (the file is built by the game project, not by the runtime library, so the runtime's own CI never compiles it with GCC; #402 made the tests build with GCC, this is the loader). + +- `samp_stack_guest` (the `PS3_SAMPLE_*` sampler) reads the sampled thread's stack under `__try` / `__except`, and GCC has no structured exception handling: `error: expected 'catch' before '__except'`. Without `_MSC_VER` it asks `ReadProcessMemory`, which fails on an unreadable address where a plain read would fault. +- `ppu_resv_break` was declared `extern "C"` and defined `static inline` further down: `error: 'void ppu_resv_break(uint64_t)' was declared 'extern' and later 'static'`. It is now declared `static inline` the same way; nothing else refers to it by name (`ppu_resv_break_store` and `ppu_resv_break_line` are the exported ones). + +Checked: `x86_64-w64-mingw32-g++ -std=c++20 -fsyntax-only` on `ppu_loader.cpp` reports the errors above on v0.18.0 and none with this change (and the whole host of a game port cross-builds and links with MinGW GCC on macOS); clang on macOS still compiles it. MSVC and clang-cl take the `__try` branch exactly as before. + +No test: it is a compile fix, and the loader needs the generated `ppu_recomp.h` of a game project. + +No open PR touches these lines (#528, #556, #596 and #599 change other parts of `ppu_loader.cpp`). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-610/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-610/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f578fcf2ba3cc620b7e37062b6b41781ef38ecaf --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-610/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/runtime/ppu/ppu_loader.cpp b/runtime/ppu/ppu_loader.cpp +index 9309f2d3..6252c832 100644 +--- a/runtime/ppu/ppu_loader.cpp ++++ b/runtime/ppu/ppu_loader.cpp +@@ -632,7 +632,12 @@ static uint32_t samp_stack_guest(HANDLE h, const CONTEXT* c) + const uintptr_t* sp = (const uintptr_t*)c->Rsp; + for (int i = 0; i < 512; i++) { /* 4 KB of stack */ + uintptr_t v; ++#ifdef _MSC_VER + __try { v = sp[i]; } __except (1) { return 0; } ++#else ++ /* no SEH in GCC/MinGW: ReadProcessMemory fails on an unreadable address where a plain read would fault */ ++ if (!ReadProcessMemory(GetCurrentProcess(), sp + i, &v, sizeof v, NULL)) return 0; ++#endif + uint32_t g = samp_lookup(v); + if (g) return g; + } +@@ -788,7 +793,7 @@ static DWORD WINAPI samp_thread(LPVOID p) + * Writing the word leaves memory self-consistent: lwarx, the CAS and the + * polling reader all see the same thing, so the guest behaves as it would if + * whatever should have cleared the counter had done so. */ +-extern "C" void ppu_resv_break(uint64_t ea); ++static inline void ppu_resv_break(uint64_t ea); /* defined below; GCC rejects extern followed by static */ + static DWORD WINAPI poke_thread(LPVOID p) + { + const uint32_t ea = (uint32_t)(uintptr_t)p; diff --git a/tasks/sp00nznet__ps3recomp-610/tests/test.sh b/tasks/sp00nznet__ps3recomp-610/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-610/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-610/tests/verifier.py b/tasks/sp00nznet__ps3recomp-610/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-610/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-611/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-611/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-611/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-611/instruction.md b/tasks/sp00nznet__ps3recomp-611/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..abe9b6fb3b165d700d00f327c6a46c9ba5118511 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-611/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** cellAtrac: PS3RECOMP_ATRAC_LGPL=OFF links a stub in place of the LGPL decoder + +## Description + +cellAtrac decodes ATRAC3plus with the FFmpeg decoder vendored in `third_party/at3_standalone` (LGPL-2.1-or-later, "kept as a separable component"), and the runtime always compiles it in. A port that has to ship one statically linked binary under a permissive license has no way to leave it out. + +`PS3RECOMP_ATRAC_LGPL` (default **ON**, so nothing changes for anyone) can now be turned OFF. Then `third_party/at3_stub/at3_stub.c` provides the four `at3p_*` entry points of `at3_bridge.h`: `at3p_open` returns NULL, so `cellAtracSetData` refuses to set up a track and the title sees an ATRAC error, which is the path it already has for a track it cannot decode. No decoder object is in the library. + +Checked on macOS (clang, Ninja, Release), `--target ps3recomp_runtime`, both settings: +- ON: `libps3recomp_runtime.a` contains `at3_bridge.cpp.o`, `atrac3.cpp.o`, `atrac3plus.cpp.o` and the rest of the decoder, as before. +- OFF: it contains `at3_stub.c.o` and none of those. + +The Linux workflow builds the library the OFF way once (gcc, Release only) and asserts the same with `ar t`; I could not run that workflow, only the commands in it. `docs/BUILDING.md` describes the option next to the FFmpeg/LGPL note. + +Open PRs: only #213 changes `CMakeLists.txt` anywhere near (`CONFIGURE_DEPENDS` on the globs, a few lines away; no overlapping lines). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-611/solution/patch.diff b/tasks/sp00nznet__ps3recomp-611/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3d92dd4fc79d2b914700c9b3d7e4758056609a76 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-611/solution/patch.diff @@ -0,0 +1,86 @@ +diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml +index 99c0b20c..ec673b05 100644 +--- a/.github/workflows/linux.yml ++++ b/.github/workflows/linux.yml +@@ -79,6 +79,19 @@ jobs: + exit 1 + fi + ++ # PS3RECOMP_ATRAC_LGPL=OFF links a stub instead of the LGPL-2.1 ATRAC3plus ++ # decoder: the library builds, and no decoder object is in the archive. ++ - name: Build without the LGPL ATRAC decoder ++ if: matrix.compiler == 'gcc' && matrix.build_type == 'Release' ++ run: | ++ CC=gcc CXX=g++ cmake -S . -B build-nolgpl -G Ninja -DCMAKE_BUILD_TYPE=Release -DPS3RECOMP_ATRAC_LGPL=OFF ++ cmake --build build-nolgpl --target ps3recomp_runtime ++ ar t build-nolgpl/libps3recomp_runtime.a | grep -q '^at3_stub.c.o$' ++ if ar t build-nolgpl/libps3recomp_runtime.a | grep -qE '^(atrac3|atrac3plus|at3_bridge)'; then ++ echo "an LGPL decoder object is in the library" ++ exit 1 ++ fi ++ + # The Python suites are the project's real correctness net -- the + # conformance one compiles and runs 1300+ lifted instruction cases with + # the host compiler, so it is genuinely testing this platform's codegen +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..b9e9fd4b 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -76,9 +76,16 @@ endif() + list(APPEND HLE_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/libs/video/rsx_shader_msl.cpp") + # cellAtrac decodes with FFmpeg's ATRAC3plus decoder as extracted by PPSSPP + # (LGPL-2.1, kept separate in third_party/at3_standalone -- see its README). +-file(GLOB AT3_SOURCES "third_party/at3_standalone/*.cpp") +-set_source_files_properties(${AT3_SOURCES} PROPERTIES COMPILE_OPTIONS "-w") # upstream code +-list(APPEND HLE_SOURCES ${AT3_SOURCES}) ++# PS3RECOMP_ATRAC_LGPL=OFF swaps the decoder for a stub that fails every open, which keeps the library and any ++# binary linked from it free of LGPL code (third_party/at3_stub); the title then sees an ATRAC error. ++option(PS3RECOMP_ATRAC_LGPL "Link the LGPL-2.1 ATRAC3plus decoder (cellAtrac)" ON) ++if(PS3RECOMP_ATRAC_LGPL) ++ file(GLOB AT3_SOURCES "third_party/at3_standalone/*.cpp") ++ set_source_files_properties(${AT3_SOURCES} PROPERTIES COMPILE_OPTIONS "-w") # upstream code ++ list(APPEND HLE_SOURCES ${AT3_SOURCES}) ++else() ++ list(APPEND HLE_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/third_party/at3_stub/at3_stub.c") ++endif() + + # Runtime core (syscalls, PPU, SPU, memory) + file(GLOB_RECURSE RUNTIME_SOURCES +diff --git a/docs/BUILDING.md b/docs/BUILDING.md +index 3bbabf62..48e4a1fc 100644 +--- a/docs/BUILDING.md ++++ b/docs/BUILDING.md +@@ -159,6 +159,13 @@ compiled into the runtime. If you redistribute FFmpeg DLLs with a port, use an + LGPL-only build: distro and MSYS2 packages are usually built with GPL parts + enabled (`--enable-gpl`), which changes what you may ship. + ++cellAtrac decodes ATRAC3plus with a vendored FFmpeg decoder ++(`third_party/at3_standalone`, LGPL-2.1-or-later, kept as a separable ++component), which is compiled into the runtime. For a binary that has to stay ++free of LGPL code, configure with `-DPS3RECOMP_ATRAC_LGPL=OFF`: a stub ++(`third_party/at3_stub`) replaces it, every ATRAC track fails to open, and the ++title sees an ATRAC error. The default is ON. ++ + ### Running the Tests + + ```bash +diff --git a/third_party/at3_stub/at3_stub.c b/third_party/at3_stub/at3_stub.c +new file mode 100644 +index 00000000..c05fb57f +--- /dev/null ++++ b/third_party/at3_stub/at3_stub.c +@@ -0,0 +1,14 @@ ++/* Stand-in for the ATRAC3plus decoder (third_party/at3_standalone, LGPL-2.1) in builds that must stay free of LGPL ++ * code, e.g. a single statically linked binary under a permissive license (PS3RECOMP_ATRAC_LGPL=OFF). ++ * at3p_open reports failure, so cellAtrac refuses to set up a track and the title sees an ATRAC error. */ ++#include "../at3_standalone/at3_bridge.h" ++#include ++ ++void* at3p_open(int channels, int* block_align) { (void)channels; (void)block_align; return NULL; } ++void at3p_close(void* dec) { (void)dec; } ++void at3p_flush(void* dec) { (void)dec; } ++int at3p_decode(void* dec, float* left, float* right, int* samples, const uint8_t* frame, int frame_bytes) ++{ ++ (void)dec; (void)left; (void)right; (void)samples; (void)frame; (void)frame_bytes; ++ return -1; ++} diff --git a/tasks/sp00nznet__ps3recomp-611/solution/solve.sh b/tasks/sp00nznet__ps3recomp-611/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-611/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-611/task.toml b/tasks/sp00nznet__ps3recomp-611/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d81cc6bb008f667d3491506c85ce779d85427aa9 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-611/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-611" +description = "cellAtrac: PS3RECOMP_ATRAC_LGPL=OFF links a stub in place of the LGPL decoder" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/611" +source_access = "auto" +built_at = "2026-11-16T16:09:59.683553+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2a313a291df99d50d0c0bb8f99fd06579deaa4d4de8a13459a394b6f391a7fb9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + ".github/workflows/linux.yml", + "CMakeLists.txt", + "docs/BUILDING.md", + "third_party/at3_stub/at3_stub.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 47 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.126951+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-611/tests/capture.py b/tasks/sp00nznet__ps3recomp-611/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-611/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-611/tests/instruction.md b/tasks/sp00nznet__ps3recomp-611/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..abe9b6fb3b165d700d00f327c6a46c9ba5118511 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-611/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** cellAtrac: PS3RECOMP_ATRAC_LGPL=OFF links a stub in place of the LGPL decoder + +## Description + +cellAtrac decodes ATRAC3plus with the FFmpeg decoder vendored in `third_party/at3_standalone` (LGPL-2.1-or-later, "kept as a separable component"), and the runtime always compiles it in. A port that has to ship one statically linked binary under a permissive license has no way to leave it out. + +`PS3RECOMP_ATRAC_LGPL` (default **ON**, so nothing changes for anyone) can now be turned OFF. Then `third_party/at3_stub/at3_stub.c` provides the four `at3p_*` entry points of `at3_bridge.h`: `at3p_open` returns NULL, so `cellAtracSetData` refuses to set up a track and the title sees an ATRAC error, which is the path it already has for a track it cannot decode. No decoder object is in the library. + +Checked on macOS (clang, Ninja, Release), `--target ps3recomp_runtime`, both settings: +- ON: `libps3recomp_runtime.a` contains `at3_bridge.cpp.o`, `atrac3.cpp.o`, `atrac3plus.cpp.o` and the rest of the decoder, as before. +- OFF: it contains `at3_stub.c.o` and none of those. + +The Linux workflow builds the library the OFF way once (gcc, Release only) and asserts the same with `ar t`; I could not run that workflow, only the commands in it. `docs/BUILDING.md` describes the option next to the FFmpeg/LGPL note. + +Open PRs: only #213 changes `CMakeLists.txt` anywhere near (`CONFIGURE_DEPENDS` on the globs, a few lines away; no overlapping lines). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-611/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-611/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3d92dd4fc79d2b914700c9b3d7e4758056609a76 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-611/tests/oracle.patch @@ -0,0 +1,86 @@ +diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml +index 99c0b20c..ec673b05 100644 +--- a/.github/workflows/linux.yml ++++ b/.github/workflows/linux.yml +@@ -79,6 +79,19 @@ jobs: + exit 1 + fi + ++ # PS3RECOMP_ATRAC_LGPL=OFF links a stub instead of the LGPL-2.1 ATRAC3plus ++ # decoder: the library builds, and no decoder object is in the archive. ++ - name: Build without the LGPL ATRAC decoder ++ if: matrix.compiler == 'gcc' && matrix.build_type == 'Release' ++ run: | ++ CC=gcc CXX=g++ cmake -S . -B build-nolgpl -G Ninja -DCMAKE_BUILD_TYPE=Release -DPS3RECOMP_ATRAC_LGPL=OFF ++ cmake --build build-nolgpl --target ps3recomp_runtime ++ ar t build-nolgpl/libps3recomp_runtime.a | grep -q '^at3_stub.c.o$' ++ if ar t build-nolgpl/libps3recomp_runtime.a | grep -qE '^(atrac3|atrac3plus|at3_bridge)'; then ++ echo "an LGPL decoder object is in the library" ++ exit 1 ++ fi ++ + # The Python suites are the project's real correctness net -- the + # conformance one compiles and runs 1300+ lifted instruction cases with + # the host compiler, so it is genuinely testing this platform's codegen +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..b9e9fd4b 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -76,9 +76,16 @@ endif() + list(APPEND HLE_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/libs/video/rsx_shader_msl.cpp") + # cellAtrac decodes with FFmpeg's ATRAC3plus decoder as extracted by PPSSPP + # (LGPL-2.1, kept separate in third_party/at3_standalone -- see its README). +-file(GLOB AT3_SOURCES "third_party/at3_standalone/*.cpp") +-set_source_files_properties(${AT3_SOURCES} PROPERTIES COMPILE_OPTIONS "-w") # upstream code +-list(APPEND HLE_SOURCES ${AT3_SOURCES}) ++# PS3RECOMP_ATRAC_LGPL=OFF swaps the decoder for a stub that fails every open, which keeps the library and any ++# binary linked from it free of LGPL code (third_party/at3_stub); the title then sees an ATRAC error. ++option(PS3RECOMP_ATRAC_LGPL "Link the LGPL-2.1 ATRAC3plus decoder (cellAtrac)" ON) ++if(PS3RECOMP_ATRAC_LGPL) ++ file(GLOB AT3_SOURCES "third_party/at3_standalone/*.cpp") ++ set_source_files_properties(${AT3_SOURCES} PROPERTIES COMPILE_OPTIONS "-w") # upstream code ++ list(APPEND HLE_SOURCES ${AT3_SOURCES}) ++else() ++ list(APPEND HLE_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/third_party/at3_stub/at3_stub.c") ++endif() + + # Runtime core (syscalls, PPU, SPU, memory) + file(GLOB_RECURSE RUNTIME_SOURCES +diff --git a/docs/BUILDING.md b/docs/BUILDING.md +index 3bbabf62..48e4a1fc 100644 +--- a/docs/BUILDING.md ++++ b/docs/BUILDING.md +@@ -159,6 +159,13 @@ compiled into the runtime. If you redistribute FFmpeg DLLs with a port, use an + LGPL-only build: distro and MSYS2 packages are usually built with GPL parts + enabled (`--enable-gpl`), which changes what you may ship. + ++cellAtrac decodes ATRAC3plus with a vendored FFmpeg decoder ++(`third_party/at3_standalone`, LGPL-2.1-or-later, kept as a separable ++component), which is compiled into the runtime. For a binary that has to stay ++free of LGPL code, configure with `-DPS3RECOMP_ATRAC_LGPL=OFF`: a stub ++(`third_party/at3_stub`) replaces it, every ATRAC track fails to open, and the ++title sees an ATRAC error. The default is ON. ++ + ### Running the Tests + + ```bash +diff --git a/third_party/at3_stub/at3_stub.c b/third_party/at3_stub/at3_stub.c +new file mode 100644 +index 00000000..c05fb57f +--- /dev/null ++++ b/third_party/at3_stub/at3_stub.c +@@ -0,0 +1,14 @@ ++/* Stand-in for the ATRAC3plus decoder (third_party/at3_standalone, LGPL-2.1) in builds that must stay free of LGPL ++ * code, e.g. a single statically linked binary under a permissive license (PS3RECOMP_ATRAC_LGPL=OFF). ++ * at3p_open reports failure, so cellAtrac refuses to set up a track and the title sees an ATRAC error. */ ++#include "../at3_standalone/at3_bridge.h" ++#include ++ ++void* at3p_open(int channels, int* block_align) { (void)channels; (void)block_align; return NULL; } ++void at3p_close(void* dec) { (void)dec; } ++void at3p_flush(void* dec) { (void)dec; } ++int at3p_decode(void* dec, float* left, float* right, int* samples, const uint8_t* frame, int frame_bytes) ++{ ++ (void)dec; (void)left; (void)right; (void)samples; (void)frame; (void)frame_bytes; ++ return -1; ++} diff --git a/tasks/sp00nznet__ps3recomp-611/tests/test.sh b/tasks/sp00nznet__ps3recomp-611/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-611/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-611/tests/verifier.py b/tasks/sp00nznet__ps3recomp-611/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-611/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-612/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-612/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-612/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-612/instruction.md b/tasks/sp00nznet__ps3recomp-612/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4a1db6d7146a70889c10a1ce75b2dad34f4dc811 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-612/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** cellPad: the keyboard fallback on port 0 on macOS and with SDL + +## Description + +With no controller plugged in, a title gets a pad on port 0 that is reported present and never presses anything: it can be watched but not played. The keyboard fallback for that case (arrows = d-pad, Z/X/A/S = cross/circle/square/triangle, Q/W = L1/R1, 1/2 = L2/R2, Return = START, Tab = SELECT, the left stick mirrors the d-pad, only while a window of the process has the focus, `PAD_NO_KEYBOARD=1` turns it off) existed for the XInput backend only. This makes it the same code on every host, and takes the keys from where the host has them: + +- XInput backend (Windows): `GetAsyncKeyState`, as before. +- macOS: `CGEventSourceKeyState` with the `kVK_*` codes, which needs no event tap and no window; "focused" is `NSApplication.isActive`, asked through the Objective-C runtime so the file stays plain C. The three entry points are declared by hand (the system headers clash with this project's `bool` and `GetCurrentThread`/`GetCurrentProcess`); the build links `ApplicationServices`. +- everywhere else, and SDL on Windows: `SDL_GetKeyboardState` and `SDL_GetKeyboardFocus`. The state is kept current by whoever pumps SDL's events (the Vulkan window); with no video subsystem nothing is ever pressed. + +The mapping table and the polling are one function now; the Windows block moved out of the XInput section (a move more than a rewrite: `git diff --histogram` shows 17 added and 15 removed lines in `cellPad.c` besides the new source variants). + +`libs/input/tests/test_pad_keyboard.c` drives the table through a fake SDL keyboard and focus: every key, the d-pad and the stick, several keys at once, and the release of everything when the focus is lost. `PS3RECOMP_PAD_KEYBOARD_SDL` selects the SDL source on macOS too so that one test covers the same logic everywhere. It fails on v0.18.0 (first key assert) and passes here; it is added to the Linux and macOS workflows next to the hot-plug test (YAML parses; I could not run the workflows). + +Checked: macOS (clang) for the test and the build; `-fsyntax-only` for the Linux branch (`-U__APPLE__`), for MinGW GCC with XInput and with `PS3RECOMP_PAD_USE_SDL2`. The macOS source I checked only in part: posting a key with `CGEventPost` and reading `CGEventSourceKeyState(…, 6)` goes 0 → 1 → 0 for Z, as the table assumes; the `isActive` focus query I did not test on its own. Linux and Windows were not run. + +No open PR touches this code (#213 and #447 change `cellPad.c` elsewhere, with no overlapping hunks). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-612/solution/patch.diff b/tasks/sp00nznet__ps3recomp-612/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5891862a8103bf776056d961f3257f4e34606ccd --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-612/solution/patch.diff @@ -0,0 +1,456 @@ +diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml +index 99c0b20c..2a550355 100644 +--- a/.github/workflows/linux.yml ++++ b/.github/workflows/linux.yml +@@ -225,6 +225,12 @@ jobs: + ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} -std=gnu17 -I include $(sdl2-config --cflags) -o /tmp/test_pad_hotplug libs/input/tests/test_pad_hotplug.c $(sdl2-config --libs) -lm + /tmp/test_pad_hotplug + ++ # cellPad keyboard fallback on port 0 (SDL source, fake keyboard and focus). ++ - name: Run the pad keyboard test ++ run: | ++ ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} -std=gnu17 -DPS3RECOMP_PAD_KEYBOARD_SDL -I include $(sdl2-config --cflags) -o /tmp/test_pad_keyboard libs/input/tests/test_pad_keyboard.c $(sdl2-config --libs) -lm ++ /tmp/test_pad_keyboard ++ + + # Guest vertex and fragment programs through the decompilers, glslang + # and spirv-cross: asserts the MSL carries the buffer, texture, sampler +diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml +index aeb9e948..08b5d08d 100644 +--- a/.github/workflows/macos.yml ++++ b/.github/workflows/macos.yml +@@ -200,6 +200,13 @@ jobs: + clang -std=gnu17 -I include $(sdl2-config --cflags) -I "$(sdl2-config --prefix)/include" -o /tmp/test_pad_hotplug libs/input/tests/test_pad_hotplug.c $(sdl2-config --libs) + /tmp/test_pad_hotplug + ++ # cellPad keyboard fallback on port 0 (read through SDL here too, with a ++ # fake keyboard and focus; the real macOS source is CGEventSourceKeyState). ++ - name: Run the pad keyboard test ++ run: | ++ clang -std=gnu17 -DPS3RECOMP_PAD_KEYBOARD_SDL -I include $(sdl2-config --cflags) -I "$(sdl2-config --prefix)/include" -o /tmp/test_pad_keyboard libs/input/tests/test_pad_keyboard.c $(sdl2-config --libs) ++ /tmp/test_pad_keyboard ++ + # Drives a real NV4097 command buffer through cellGcm -> RSX -> the Metal + # backend and asserts the presented pixel matches the guest clear colour. + # Headless, so it needs no display: exit 0 means the whole graphics bridge +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..c333473c 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -168,6 +168,7 @@ if(APPLE) + "-framework QuartzCore" + "-framework Foundation" + "-framework AppKit" ++ "-framework ApplicationServices" + ) + set_source_files_properties( + "${CMAKE_CURRENT_SOURCE_DIR}/libs/video/rsx_metal_backend.m" +diff --git a/libs/input/cellPad.c b/libs/input/cellPad.c +index afdd93de..5f8a2fa2 100644 +--- a/libs/input/cellPad.c ++++ b/libs/input/cellPad.c +@@ -191,6 +191,163 @@ static void pad_rumble_levels(u8 small_on, u8 large, u16* lo, u16* hi) + *hi = small_on ? 0xFFFFu : 0u; + } + ++/* Keyboard fallback for port 0. ++ * ++ * On a machine with no controller plugged in a title gets a pad that is reported ++ * present and never presses anything -- it can be watched but not played. That is ++ * what The Simpsons Arcade Game hit: it reached its attract loop and no input ++ * existed to start a game. ++ * ++ * Only fills in for port 0, only when the backend found no controller there, so a ++ * real controller always wins and nothing changes for a port that has one. Keys ++ * are read only while a window of THIS process is in the foreground, so typing in ++ * another application does not drive the game. Set PAD_NO_KEYBOARD=1 to ++ * disable it entirely. ++ * ++ * Arrows = d-pad, Z/X/A/S = cross/circle/square/triangle, Q/W = L1/R1, ++ * 1/2 = L2/R2, Enter = START, Tab = SELECT. The left stick mirrors the d-pad ++ * so a title that reads the stick instead is playable too. ++ * ++ * Where the keys come from: GetAsyncKeyState with the XInput backend; on macOS ++ * CGEventSourceKeyState, which needs no event tap and no window; elsewhere SDL's ++ * keyboard state, which is kept current by whoever pumps SDL's events (in ++ * practice the window of the video backend). PS3RECOMP_PAD_KEYBOARD_SDL selects ++ * the SDL source on macOS too, which is how the keyboard test is built. */ ++#if PAD_BACKEND_XINPUT ++static int pad_host_window_focused(void) ++{ ++ HWND fg = GetForegroundWindow(); ++ if (!fg) return 0; ++ DWORD pid = 0; ++ GetWindowThreadProcessId(fg, &pid); ++ return pid == GetCurrentProcessId(); ++} ++static int pad_key_down(int key) { return (GetAsyncKeyState(key) & 0x8000) != 0; } ++#define PADKEY_UP VK_UP ++#define PADKEY_DOWN VK_DOWN ++#define PADKEY_LEFT VK_LEFT ++#define PADKEY_RIGHT VK_RIGHT ++#define PADKEY_Z 'Z' ++#define PADKEY_X 'X' ++#define PADKEY_A 'A' ++#define PADKEY_S 'S' ++#define PADKEY_Q 'Q' ++#define PADKEY_W 'W' ++#define PADKEY_1 '1' ++#define PADKEY_2 '2' ++#define PADKEY_RETURN VK_RETURN ++#define PADKEY_TAB VK_TAB ++#elif defined(__APPLE__) && !defined(PS3RECOMP_PAD_KEYBOARD_SDL) ++/* macOS: virtual key codes (Carbon HIToolbox/Events.h kVK_*), polled with CGEventSourceKeyState, ++ * which needs no event tap and no window. "Focused" is NSApplication.isActive of this process, ++ * queried through the Objective-C runtime so this file stays plain C. */ ++/* The system headers are not included on purpose: ApplicationServices / objc.h clash with this ++ * project's own `bool` and GetCurrentThread/GetCurrentProcess names, so the three entry points ++ * are declared by hand (CGKeyCode is uint16_t, kCGEventSourceStateCombinedSessionState is 0). */ ++extern unsigned char CGEventSourceKeyState(int stateID, unsigned short key); ++extern void* objc_getClass(const char* name); ++extern void* sel_registerName(const char* name); ++extern void objc_msgSend(void); ++static int pad_host_window_focused(void) ++{ ++ void* cls = objc_getClass("NSApplication"); ++ if (!cls) return 0; ++ void* app = ((void* (*)(void*, void*))objc_msgSend)(cls, sel_registerName("sharedApplication")); ++ return app && ((signed char (*)(void*, void*))objc_msgSend)(app, sel_registerName("isActive")); ++} ++static int pad_key_down(int key) ++{ ++ return CGEventSourceKeyState(0, (unsigned short)key) != 0; ++} ++#define PADKEY_UP 126 ++#define PADKEY_DOWN 125 ++#define PADKEY_LEFT 123 ++#define PADKEY_RIGHT 124 ++#define PADKEY_Z 6 ++#define PADKEY_X 7 ++#define PADKEY_A 0 ++#define PADKEY_S 1 ++#define PADKEY_Q 12 ++#define PADKEY_W 13 ++#define PADKEY_1 18 ++#define PADKEY_2 19 ++#define PADKEY_RETURN 36 ++#define PADKEY_TAB 48 ++#elif PAD_BACKEND_SDL2 ++/* Everywhere else the keyboard is SDL's: scancodes are physical keys, like the macOS codes above. The state is kept ++ * current by whoever pumps SDL's events (the window of the RSX backend); without a video subsystem nothing is ever ++ * pressed. "Focused" is that some window of this process has the keyboard focus. */ ++static int pad_host_window_focused(void) ++{ ++ return SDL_GetKeyboardFocus() != NULL; ++} ++static int pad_key_down(int key) ++{ ++ return SDL_GetKeyboardState(NULL)[key] != 0; ++} ++#define PADKEY_UP SDL_SCANCODE_UP ++#define PADKEY_DOWN SDL_SCANCODE_DOWN ++#define PADKEY_LEFT SDL_SCANCODE_LEFT ++#define PADKEY_RIGHT SDL_SCANCODE_RIGHT ++#define PADKEY_Z SDL_SCANCODE_Z ++#define PADKEY_X SDL_SCANCODE_X ++#define PADKEY_A SDL_SCANCODE_A ++#define PADKEY_S SDL_SCANCODE_S ++#define PADKEY_Q SDL_SCANCODE_Q ++#define PADKEY_W SDL_SCANCODE_W ++#define PADKEY_1 SDL_SCANCODE_1 ++#define PADKEY_2 SDL_SCANCODE_2 ++#define PADKEY_RETURN SDL_SCANCODE_RETURN ++#define PADKEY_TAB SDL_SCANCODE_TAB ++#endif ++ ++static void pad_poll_keyboard(void) ++{ ++ static int off = -1; ++ if (off < 0) off = getenv("PAD_NO_KEYBOARD") ? 1 : 0; ++ if (off) return; ++ ++ PadHostState* hs = &s_host_state[0]; ++ if (!pad_host_window_focused()) { ++ /* Release everything on focus loss, or a key held while alt-tabbing ++ * would stay down forever. */ ++ hs->buttons = 0; ++ hs->analog_lx = hs->analog_ly = 128; ++ hs->analog_rx = hs->analog_ry = 128; ++ hs->connected = 1; ++ return; ++ } ++ ++ static const struct { int vk; u16 btn; } map[] = { ++ { PADKEY_UP, CELL_PAD_CTRL_UP }, { PADKEY_DOWN, CELL_PAD_CTRL_DOWN }, ++ { PADKEY_LEFT, CELL_PAD_CTRL_LEFT }, { PADKEY_RIGHT, CELL_PAD_CTRL_RIGHT }, ++ { PADKEY_Z, CELL_PAD_CTRL_CROSS }, { PADKEY_X, CELL_PAD_CTRL_CIRCLE }, ++ { PADKEY_A, CELL_PAD_CTRL_SQUARE }, { PADKEY_S, CELL_PAD_CTRL_TRIANGLE }, ++ { PADKEY_Q, CELL_PAD_CTRL_L1 }, { PADKEY_W, CELL_PAD_CTRL_R1 }, ++ { PADKEY_1, CELL_PAD_CTRL_L2 }, { PADKEY_2, CELL_PAD_CTRL_R2 }, ++ { PADKEY_RETURN, CELL_PAD_CTRL_START }, { PADKEY_TAB, CELL_PAD_CTRL_SELECT }, ++ }; ++ ++ u16 btns = 0; ++ for (unsigned i = 0; i < sizeof map / sizeof map[0]; i++) ++ if (pad_key_down(map[i].vk)) btns |= map[i].btn; ++ ++ hs->buttons = btns; ++ hs->connected = 1; ++ hs->analog_lx = (u8)((btns & CELL_PAD_CTRL_LEFT) ? 0 : ++ (btns & CELL_PAD_CTRL_RIGHT) ? 255 : 128); ++ hs->analog_ly = (u8)((btns & CELL_PAD_CTRL_UP) ? 0 : ++ (btns & CELL_PAD_CTRL_DOWN) ? 255 : 128); ++ hs->analog_rx = hs->analog_ry = 128; ++ hs->trigger_l2 = (u8)((btns & CELL_PAD_CTRL_L2) ? 255 : 0); ++ hs->trigger_r2 = (u8)((btns & CELL_PAD_CTRL_R2) ? 255 : 0); ++ ++ { static int said = 0; ++ if (!said && btns) { said = 1; ++ printf("[cellPad] keyboard fallback active on port 0 (no controller)\n"); ++ fflush(stdout); } } ++} ++ + /* --------------------------------------------------------------------------- + * XInput backend + * -----------------------------------------------------------------------*/ +@@ -251,80 +408,6 @@ static u8 pad_xinput_stick_to_u8(short raw, short deadzone) + return (u8)val; + } + +-/* Keyboard fallback for port 0. +- * +- * The only backend here is XInput, so on a machine with no controller plugged +- * in a title gets a pad that is reported present and never presses anything -- +- * it can be watched but not played. That is what The Simpsons Arcade Game hit: +- * it reached its attract loop and no input existed to start a game. +- * +- * Only fills in for port 0, only when XInput found nothing there, so a real +- * controller always wins and nothing changes for a port that has one. Keys are +- * read only while a window of THIS process is in the foreground, so typing in +- * another application does not drive the game. Set PAD_NO_KEYBOARD=1 to +- * disable it entirely. +- * +- * Arrows = d-pad, Z/X/A/S = cross/circle/square/triangle, Q/W = L1/R1, +- * 1/2 = L2/R2, Enter = START, Tab = SELECT. The left stick mirrors the d-pad +- * so a title that reads the stick instead is playable too. */ +-#ifdef _WIN32 +-static int pad_host_window_focused(void) +-{ +- HWND fg = GetForegroundWindow(); +- if (!fg) return 0; +- DWORD pid = 0; +- GetWindowThreadProcessId(fg, &pid); +- return pid == GetCurrentProcessId(); +-} +- +-static void pad_poll_keyboard(void) +-{ +- static int off = -1; +- if (off < 0) off = getenv("PAD_NO_KEYBOARD") ? 1 : 0; +- if (off) return; +- +- PadHostState* hs = &s_host_state[0]; +- if (!pad_host_window_focused()) { +- /* Release everything on focus loss, or a key held while alt-tabbing +- * would stay down forever. */ +- hs->buttons = 0; +- hs->analog_lx = hs->analog_ly = 128; +- hs->analog_rx = hs->analog_ry = 128; +- hs->connected = 1; +- return; +- } +- +- static const struct { int vk; u16 btn; } map[] = { +- { VK_UP, CELL_PAD_CTRL_UP }, { VK_DOWN, CELL_PAD_CTRL_DOWN }, +- { VK_LEFT, CELL_PAD_CTRL_LEFT }, { VK_RIGHT, CELL_PAD_CTRL_RIGHT }, +- { 'Z', CELL_PAD_CTRL_CROSS }, { 'X', CELL_PAD_CTRL_CIRCLE }, +- { 'A', CELL_PAD_CTRL_SQUARE }, { 'S', CELL_PAD_CTRL_TRIANGLE }, +- { 'Q', CELL_PAD_CTRL_L1 }, { 'W', CELL_PAD_CTRL_R1 }, +- { '1', CELL_PAD_CTRL_L2 }, { '2', CELL_PAD_CTRL_R2 }, +- { VK_RETURN, CELL_PAD_CTRL_START }, { VK_TAB, CELL_PAD_CTRL_SELECT }, +- }; +- +- u16 btns = 0; +- for (unsigned i = 0; i < sizeof map / sizeof map[0]; i++) +- if (GetAsyncKeyState(map[i].vk) & 0x8000) btns |= map[i].btn; +- +- hs->buttons = btns; +- hs->connected = 1; +- hs->analog_lx = (u8)((btns & CELL_PAD_CTRL_LEFT) ? 0 : +- (btns & CELL_PAD_CTRL_RIGHT) ? 255 : 128); +- hs->analog_ly = (u8)((btns & CELL_PAD_CTRL_UP) ? 0 : +- (btns & CELL_PAD_CTRL_DOWN) ? 255 : 128); +- hs->analog_rx = hs->analog_ry = 128; +- hs->trigger_l2 = (u8)((btns & CELL_PAD_CTRL_L2) ? 255 : 0); +- hs->trigger_r2 = (u8)((btns & CELL_PAD_CTRL_R2) ? 255 : 0); +- +- { static int said = 0; +- if (!said && btns) { said = 1; +- printf("[cellPad] keyboard fallback active on port 0 (no XInput device)\n"); +- fflush(stdout); } } +-} +-#endif +- + /* XInputGetState on a slot with nothing plugged in costs about 140 us (2 us on + * a connected one), and the backend is polled at least once a frame: three + * empty slots beside one pad were 0.6 ms of every frame on God of War HD's +@@ -710,9 +793,7 @@ static void pad_poll_backend(void) + #elif PAD_BACKEND_SDL2 + pad_poll_sdl2(); + #endif +-#ifdef _WIN32 + if (!s_host_state[0].connected) pad_poll_keyboard(); +-#endif + pad_track_assign(); + pad_unlock(); + } +diff --git a/libs/input/tests/test_pad_keyboard.c b/libs/input/tests/test_pad_keyboard.c +new file mode 100644 +index 00000000..ca65aa38 +--- /dev/null ++++ b/libs/input/tests/test_pad_keyboard.c +@@ -0,0 +1,144 @@ ++/* cellPad's keyboard fallback on port 0 (the SDL source): with no controller ++ * plugged in the keyboard plays the pad -- arrows = d-pad, Z/X/A/S = cross/ ++ * circle/square/triangle, Q/W = L1/R1, 1/2 = L2/R2, Return = START, Tab = ++ * SELECT, the left stick mirrors the d-pad -- while a window of the process has ++ * the keyboard focus, and releases everything when it loses it. ++ * ++ * clang -std=gnu17 -DPS3RECOMP_PAD_KEYBOARD_SDL -I include $(sdl2-config --cflags) \ ++ * -I "$(sdl2-config --prefix)/include" libs/input/tests/test_pad_keyboard.c \ ++ * $(sdl2-config --libs) -o /tmp/test_pad_keyboard && /tmp/test_pad_keyboard ++ * ++ * PS3RECOMP_PAD_KEYBOARD_SDL makes macOS read the keyboard through SDL like ++ * every other host that is not Windows, so the same table is tested everywhere. ++ * No controller exists and no window either: the test defines the SDL calls the ++ * backend makes (they take precedence over libSDL2's), with a keyboard state ++ * and a focus flag it sets itself. ++ */ ++#include "../cellPad.c" ++#include ++#include ++#include ++uint8_t* vm_base; ++uint32_t ppu_vm_size; ++int g_resv_store_active; ++uint32_t g_ww_lo, g_ww_hi; ++void ppu_resv_break_store(uint64_t ea) { (void)ea; } ++void ps3_ww_report_inline(uint32_t a, uint64_t v, int w) { (void)a; (void)v; (void)w; } ++int spu_coh_is_reserved(uint32_t a) { (void)a; return 0; } ++u32 cellGcm_flip_request_count(void) { return 0; } /* PAD_CLOCK=flips */ ++void spu_coh_notify_write(uint32_t a) { (void)a; } ++void spu_lockline_lock(void) {} ++void spu_lockline_unlock(void) {} ++ ++/* ---- the fake SDL: no controller, a keyboard the test drives ----------------- */ ++static Uint8 s_keys[SDL_NUM_SCANCODES]; ++static int s_focus; ++ ++int SDL_NumJoysticks(void) { return 0; } ++int SDL_PeepEvents(SDL_Event* ev, int n, SDL_eventaction action, Uint32 lo, Uint32 hi) ++{ ++ (void)ev; (void)n; (void)action; (void)lo; (void)hi; ++ return 0; ++} ++Uint32 SDL_WasInit(Uint32 flags) { (void)flags; return flags; } ++int SDL_InitSubSystem(Uint32 flags) { (void)flags; return 0; } ++const char* SDL_GetError(void) { return "fake"; } ++void SDL_GameControllerUpdate(void) {} ++const Uint8* SDL_GetKeyboardState(int* numkeys) { if (numkeys) *numkeys = SDL_NUM_SCANCODES; return s_keys; } ++SDL_Window* SDL_GetKeyboardFocus(void) { return s_focus ? (SDL_Window*)&s_keys : NULL; } ++ ++/* ---- helpers ---------------------------------------------------------------- */ ++/* One 16-bit word of cellPadGetData(0) (0 if it reported nothing new). */ ++static unsigned data_word(int offset) ++{ ++ const uint32_t ea = 0x2000; ++ usleep((PAD_POLL_INTERVAL_MS + 2) * 1000); ++ assert(cellPadGetData(0, (CellPadData*)(uintptr_t)ea) == CELL_OK); ++ assert(vm_base[ea + 3] != 0); /* len > 0: a report was handed out */ ++ const uint8_t* b = vm_base + ea + 4 + offset * 2; ++ return (unsigned)b[0] << 8 | b[1]; ++} ++#define D1() data_word(CELL_PAD_BTN_OFFSET_DIGITAL1) ++#define D2() data_word(CELL_PAD_BTN_OFFSET_DIGITAL2) ++static void keys(int a, int b, int c) ++{ ++ memset(s_keys, 0, sizeof s_keys); ++ if (a) s_keys[a] = 1; ++ if (b) s_keys[b] = 1; ++ if (c) s_keys[c] = 1; ++} ++/* DIGITAL1 / DIGITAL2 bits */ ++#define SELECT 0x01u ++#define START 0x08u ++#define UP 0x10u ++#define RIGHT 0x20u ++#define DOWN 0x40u ++#define LEFT 0x80u ++#define L2 0x01u ++#define R2 0x02u ++#define L1 0x04u ++#define R1 0x08u ++#define TRI 0x10u ++#define CIRCLE 0x20u ++#define CROSS 0x40u ++#define SQUARE 0x80u ++ ++int main(void) ++{ ++ vm_base = mmap(NULL, 0x10000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); ++ assert(vm_base != MAP_FAILED); ++ assert(cellPadInit(4) == CELL_OK); ++ s_focus = 1; ++ ++ /* Nothing pressed: neutral, sticks centred (0 would be full deflection). */ ++ keys(0, 0, 0); ++ assert(D1() == 0 && D2() == 0); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_X) == 128); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_Y) == 128); ++ ++ /* The face and shoulder buttons. */ ++ static const struct { int key; unsigned bit; } d2[] = { ++ { SDL_SCANCODE_Z, CROSS }, { SDL_SCANCODE_X, CIRCLE }, { SDL_SCANCODE_A, SQUARE }, ++ { SDL_SCANCODE_S, TRI }, { SDL_SCANCODE_Q, L1 }, { SDL_SCANCODE_W, R1 }, ++ { SDL_SCANCODE_1, L2 }, { SDL_SCANCODE_2, R2 }, ++ }; ++ for (unsigned i = 0; i < sizeof d2 / sizeof d2[0]; i++) { ++ keys(d2[i].key, 0, 0); ++ const unsigned v = D2(); ++ assert(v == d2[i].bit); ++ keys(0, 0, 0); ++ assert(D2() == 0); ++ } ++ keys(SDL_SCANCODE_RETURN, 0, 0); ++ assert(D1() == START); ++ keys(SDL_SCANCODE_TAB, 0, 0); ++ assert(D1() == SELECT); ++ ++ /* The d-pad, and the left stick that mirrors it. */ ++ keys(SDL_SCANCODE_LEFT, SDL_SCANCODE_UP, 0); ++ assert(D1() == (LEFT | UP)); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_X) == 0); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_Y) == 0); ++ keys(SDL_SCANCODE_RIGHT, SDL_SCANCODE_DOWN, 0); ++ assert(D1() == (RIGHT | DOWN)); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_X) == 255); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_Y) == 255); ++ ++ /* Several keys at once. */ ++ keys(SDL_SCANCODE_Z, SDL_SCANCODE_RIGHT, SDL_SCANCODE_RETURN); ++ assert((D2() & CROSS) && (D1() == (RIGHT | START))); ++ ++ /* The window loses the keyboard focus with keys still down: everything is ++ * released, or a key held while switching to another program would stay ++ * pressed for good. */ ++ keys(SDL_SCANCODE_Z, SDL_SCANCODE_LEFT, 0); ++ s_focus = 0; ++ assert(D1() == 0 && D2() == 0); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_X) == 128); ++ s_focus = 1; ++ assert(D2() == CROSS); ++ ++ assert(cellPadEnd() == CELL_OK); ++ printf("test_pad_keyboard: ok\n"); ++ return 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-612/solution/solve.sh b/tasks/sp00nznet__ps3recomp-612/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-612/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-612/task.toml b/tasks/sp00nznet__ps3recomp-612/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7371abe7c5efbf81d60be35bd96847fd3397181d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-612/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-612" +description = "cellPad: the keyboard fallback on port 0 on macOS and with SDL" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/612" +source_access = "auto" +built_at = "2026-11-16T16:09:59.681658+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2ca53692af4e53fb4e1c428035e11f4d61838766b348511a17d23ffc343ac980" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + ".github/workflows/linux.yml", + ".github/workflows/macos.yml", + "CMakeLists.txt", + "libs/input/cellPad.c", + "libs/input/tests/test_pad_keyboard.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 391 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.127501+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-612/tests/capture.py b/tasks/sp00nznet__ps3recomp-612/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-612/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-612/tests/instruction.md b/tasks/sp00nznet__ps3recomp-612/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4a1db6d7146a70889c10a1ce75b2dad34f4dc811 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-612/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** cellPad: the keyboard fallback on port 0 on macOS and with SDL + +## Description + +With no controller plugged in, a title gets a pad on port 0 that is reported present and never presses anything: it can be watched but not played. The keyboard fallback for that case (arrows = d-pad, Z/X/A/S = cross/circle/square/triangle, Q/W = L1/R1, 1/2 = L2/R2, Return = START, Tab = SELECT, the left stick mirrors the d-pad, only while a window of the process has the focus, `PAD_NO_KEYBOARD=1` turns it off) existed for the XInput backend only. This makes it the same code on every host, and takes the keys from where the host has them: + +- XInput backend (Windows): `GetAsyncKeyState`, as before. +- macOS: `CGEventSourceKeyState` with the `kVK_*` codes, which needs no event tap and no window; "focused" is `NSApplication.isActive`, asked through the Objective-C runtime so the file stays plain C. The three entry points are declared by hand (the system headers clash with this project's `bool` and `GetCurrentThread`/`GetCurrentProcess`); the build links `ApplicationServices`. +- everywhere else, and SDL on Windows: `SDL_GetKeyboardState` and `SDL_GetKeyboardFocus`. The state is kept current by whoever pumps SDL's events (the Vulkan window); with no video subsystem nothing is ever pressed. + +The mapping table and the polling are one function now; the Windows block moved out of the XInput section (a move more than a rewrite: `git diff --histogram` shows 17 added and 15 removed lines in `cellPad.c` besides the new source variants). + +`libs/input/tests/test_pad_keyboard.c` drives the table through a fake SDL keyboard and focus: every key, the d-pad and the stick, several keys at once, and the release of everything when the focus is lost. `PS3RECOMP_PAD_KEYBOARD_SDL` selects the SDL source on macOS too so that one test covers the same logic everywhere. It fails on v0.18.0 (first key assert) and passes here; it is added to the Linux and macOS workflows next to the hot-plug test (YAML parses; I could not run the workflows). + +Checked: macOS (clang) for the test and the build; `-fsyntax-only` for the Linux branch (`-U__APPLE__`), for MinGW GCC with XInput and with `PS3RECOMP_PAD_USE_SDL2`. The macOS source I checked only in part: posting a key with `CGEventPost` and reading `CGEventSourceKeyState(…, 6)` goes 0 → 1 → 0 for Z, as the table assumes; the `isActive` focus query I did not test on its own. Linux and Windows were not run. + +No open PR touches this code (#213 and #447 change `cellPad.c` elsewhere, with no overlapping hunks). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-612/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-612/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5891862a8103bf776056d961f3257f4e34606ccd --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-612/tests/oracle.patch @@ -0,0 +1,456 @@ +diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml +index 99c0b20c..2a550355 100644 +--- a/.github/workflows/linux.yml ++++ b/.github/workflows/linux.yml +@@ -225,6 +225,12 @@ jobs: + ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} -std=gnu17 -I include $(sdl2-config --cflags) -o /tmp/test_pad_hotplug libs/input/tests/test_pad_hotplug.c $(sdl2-config --libs) -lm + /tmp/test_pad_hotplug + ++ # cellPad keyboard fallback on port 0 (SDL source, fake keyboard and focus). ++ - name: Run the pad keyboard test ++ run: | ++ ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} -std=gnu17 -DPS3RECOMP_PAD_KEYBOARD_SDL -I include $(sdl2-config --cflags) -o /tmp/test_pad_keyboard libs/input/tests/test_pad_keyboard.c $(sdl2-config --libs) -lm ++ /tmp/test_pad_keyboard ++ + + # Guest vertex and fragment programs through the decompilers, glslang + # and spirv-cross: asserts the MSL carries the buffer, texture, sampler +diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml +index aeb9e948..08b5d08d 100644 +--- a/.github/workflows/macos.yml ++++ b/.github/workflows/macos.yml +@@ -200,6 +200,13 @@ jobs: + clang -std=gnu17 -I include $(sdl2-config --cflags) -I "$(sdl2-config --prefix)/include" -o /tmp/test_pad_hotplug libs/input/tests/test_pad_hotplug.c $(sdl2-config --libs) + /tmp/test_pad_hotplug + ++ # cellPad keyboard fallback on port 0 (read through SDL here too, with a ++ # fake keyboard and focus; the real macOS source is CGEventSourceKeyState). ++ - name: Run the pad keyboard test ++ run: | ++ clang -std=gnu17 -DPS3RECOMP_PAD_KEYBOARD_SDL -I include $(sdl2-config --cflags) -I "$(sdl2-config --prefix)/include" -o /tmp/test_pad_keyboard libs/input/tests/test_pad_keyboard.c $(sdl2-config --libs) ++ /tmp/test_pad_keyboard ++ + # Drives a real NV4097 command buffer through cellGcm -> RSX -> the Metal + # backend and asserts the presented pixel matches the guest clear colour. + # Headless, so it needs no display: exit 0 means the whole graphics bridge +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..c333473c 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -168,6 +168,7 @@ if(APPLE) + "-framework QuartzCore" + "-framework Foundation" + "-framework AppKit" ++ "-framework ApplicationServices" + ) + set_source_files_properties( + "${CMAKE_CURRENT_SOURCE_DIR}/libs/video/rsx_metal_backend.m" +diff --git a/libs/input/cellPad.c b/libs/input/cellPad.c +index afdd93de..5f8a2fa2 100644 +--- a/libs/input/cellPad.c ++++ b/libs/input/cellPad.c +@@ -191,6 +191,163 @@ static void pad_rumble_levels(u8 small_on, u8 large, u16* lo, u16* hi) + *hi = small_on ? 0xFFFFu : 0u; + } + ++/* Keyboard fallback for port 0. ++ * ++ * On a machine with no controller plugged in a title gets a pad that is reported ++ * present and never presses anything -- it can be watched but not played. That is ++ * what The Simpsons Arcade Game hit: it reached its attract loop and no input ++ * existed to start a game. ++ * ++ * Only fills in for port 0, only when the backend found no controller there, so a ++ * real controller always wins and nothing changes for a port that has one. Keys ++ * are read only while a window of THIS process is in the foreground, so typing in ++ * another application does not drive the game. Set PAD_NO_KEYBOARD=1 to ++ * disable it entirely. ++ * ++ * Arrows = d-pad, Z/X/A/S = cross/circle/square/triangle, Q/W = L1/R1, ++ * 1/2 = L2/R2, Enter = START, Tab = SELECT. The left stick mirrors the d-pad ++ * so a title that reads the stick instead is playable too. ++ * ++ * Where the keys come from: GetAsyncKeyState with the XInput backend; on macOS ++ * CGEventSourceKeyState, which needs no event tap and no window; elsewhere SDL's ++ * keyboard state, which is kept current by whoever pumps SDL's events (in ++ * practice the window of the video backend). PS3RECOMP_PAD_KEYBOARD_SDL selects ++ * the SDL source on macOS too, which is how the keyboard test is built. */ ++#if PAD_BACKEND_XINPUT ++static int pad_host_window_focused(void) ++{ ++ HWND fg = GetForegroundWindow(); ++ if (!fg) return 0; ++ DWORD pid = 0; ++ GetWindowThreadProcessId(fg, &pid); ++ return pid == GetCurrentProcessId(); ++} ++static int pad_key_down(int key) { return (GetAsyncKeyState(key) & 0x8000) != 0; } ++#define PADKEY_UP VK_UP ++#define PADKEY_DOWN VK_DOWN ++#define PADKEY_LEFT VK_LEFT ++#define PADKEY_RIGHT VK_RIGHT ++#define PADKEY_Z 'Z' ++#define PADKEY_X 'X' ++#define PADKEY_A 'A' ++#define PADKEY_S 'S' ++#define PADKEY_Q 'Q' ++#define PADKEY_W 'W' ++#define PADKEY_1 '1' ++#define PADKEY_2 '2' ++#define PADKEY_RETURN VK_RETURN ++#define PADKEY_TAB VK_TAB ++#elif defined(__APPLE__) && !defined(PS3RECOMP_PAD_KEYBOARD_SDL) ++/* macOS: virtual key codes (Carbon HIToolbox/Events.h kVK_*), polled with CGEventSourceKeyState, ++ * which needs no event tap and no window. "Focused" is NSApplication.isActive of this process, ++ * queried through the Objective-C runtime so this file stays plain C. */ ++/* The system headers are not included on purpose: ApplicationServices / objc.h clash with this ++ * project's own `bool` and GetCurrentThread/GetCurrentProcess names, so the three entry points ++ * are declared by hand (CGKeyCode is uint16_t, kCGEventSourceStateCombinedSessionState is 0). */ ++extern unsigned char CGEventSourceKeyState(int stateID, unsigned short key); ++extern void* objc_getClass(const char* name); ++extern void* sel_registerName(const char* name); ++extern void objc_msgSend(void); ++static int pad_host_window_focused(void) ++{ ++ void* cls = objc_getClass("NSApplication"); ++ if (!cls) return 0; ++ void* app = ((void* (*)(void*, void*))objc_msgSend)(cls, sel_registerName("sharedApplication")); ++ return app && ((signed char (*)(void*, void*))objc_msgSend)(app, sel_registerName("isActive")); ++} ++static int pad_key_down(int key) ++{ ++ return CGEventSourceKeyState(0, (unsigned short)key) != 0; ++} ++#define PADKEY_UP 126 ++#define PADKEY_DOWN 125 ++#define PADKEY_LEFT 123 ++#define PADKEY_RIGHT 124 ++#define PADKEY_Z 6 ++#define PADKEY_X 7 ++#define PADKEY_A 0 ++#define PADKEY_S 1 ++#define PADKEY_Q 12 ++#define PADKEY_W 13 ++#define PADKEY_1 18 ++#define PADKEY_2 19 ++#define PADKEY_RETURN 36 ++#define PADKEY_TAB 48 ++#elif PAD_BACKEND_SDL2 ++/* Everywhere else the keyboard is SDL's: scancodes are physical keys, like the macOS codes above. The state is kept ++ * current by whoever pumps SDL's events (the window of the RSX backend); without a video subsystem nothing is ever ++ * pressed. "Focused" is that some window of this process has the keyboard focus. */ ++static int pad_host_window_focused(void) ++{ ++ return SDL_GetKeyboardFocus() != NULL; ++} ++static int pad_key_down(int key) ++{ ++ return SDL_GetKeyboardState(NULL)[key] != 0; ++} ++#define PADKEY_UP SDL_SCANCODE_UP ++#define PADKEY_DOWN SDL_SCANCODE_DOWN ++#define PADKEY_LEFT SDL_SCANCODE_LEFT ++#define PADKEY_RIGHT SDL_SCANCODE_RIGHT ++#define PADKEY_Z SDL_SCANCODE_Z ++#define PADKEY_X SDL_SCANCODE_X ++#define PADKEY_A SDL_SCANCODE_A ++#define PADKEY_S SDL_SCANCODE_S ++#define PADKEY_Q SDL_SCANCODE_Q ++#define PADKEY_W SDL_SCANCODE_W ++#define PADKEY_1 SDL_SCANCODE_1 ++#define PADKEY_2 SDL_SCANCODE_2 ++#define PADKEY_RETURN SDL_SCANCODE_RETURN ++#define PADKEY_TAB SDL_SCANCODE_TAB ++#endif ++ ++static void pad_poll_keyboard(void) ++{ ++ static int off = -1; ++ if (off < 0) off = getenv("PAD_NO_KEYBOARD") ? 1 : 0; ++ if (off) return; ++ ++ PadHostState* hs = &s_host_state[0]; ++ if (!pad_host_window_focused()) { ++ /* Release everything on focus loss, or a key held while alt-tabbing ++ * would stay down forever. */ ++ hs->buttons = 0; ++ hs->analog_lx = hs->analog_ly = 128; ++ hs->analog_rx = hs->analog_ry = 128; ++ hs->connected = 1; ++ return; ++ } ++ ++ static const struct { int vk; u16 btn; } map[] = { ++ { PADKEY_UP, CELL_PAD_CTRL_UP }, { PADKEY_DOWN, CELL_PAD_CTRL_DOWN }, ++ { PADKEY_LEFT, CELL_PAD_CTRL_LEFT }, { PADKEY_RIGHT, CELL_PAD_CTRL_RIGHT }, ++ { PADKEY_Z, CELL_PAD_CTRL_CROSS }, { PADKEY_X, CELL_PAD_CTRL_CIRCLE }, ++ { PADKEY_A, CELL_PAD_CTRL_SQUARE }, { PADKEY_S, CELL_PAD_CTRL_TRIANGLE }, ++ { PADKEY_Q, CELL_PAD_CTRL_L1 }, { PADKEY_W, CELL_PAD_CTRL_R1 }, ++ { PADKEY_1, CELL_PAD_CTRL_L2 }, { PADKEY_2, CELL_PAD_CTRL_R2 }, ++ { PADKEY_RETURN, CELL_PAD_CTRL_START }, { PADKEY_TAB, CELL_PAD_CTRL_SELECT }, ++ }; ++ ++ u16 btns = 0; ++ for (unsigned i = 0; i < sizeof map / sizeof map[0]; i++) ++ if (pad_key_down(map[i].vk)) btns |= map[i].btn; ++ ++ hs->buttons = btns; ++ hs->connected = 1; ++ hs->analog_lx = (u8)((btns & CELL_PAD_CTRL_LEFT) ? 0 : ++ (btns & CELL_PAD_CTRL_RIGHT) ? 255 : 128); ++ hs->analog_ly = (u8)((btns & CELL_PAD_CTRL_UP) ? 0 : ++ (btns & CELL_PAD_CTRL_DOWN) ? 255 : 128); ++ hs->analog_rx = hs->analog_ry = 128; ++ hs->trigger_l2 = (u8)((btns & CELL_PAD_CTRL_L2) ? 255 : 0); ++ hs->trigger_r2 = (u8)((btns & CELL_PAD_CTRL_R2) ? 255 : 0); ++ ++ { static int said = 0; ++ if (!said && btns) { said = 1; ++ printf("[cellPad] keyboard fallback active on port 0 (no controller)\n"); ++ fflush(stdout); } } ++} ++ + /* --------------------------------------------------------------------------- + * XInput backend + * -----------------------------------------------------------------------*/ +@@ -251,80 +408,6 @@ static u8 pad_xinput_stick_to_u8(short raw, short deadzone) + return (u8)val; + } + +-/* Keyboard fallback for port 0. +- * +- * The only backend here is XInput, so on a machine with no controller plugged +- * in a title gets a pad that is reported present and never presses anything -- +- * it can be watched but not played. That is what The Simpsons Arcade Game hit: +- * it reached its attract loop and no input existed to start a game. +- * +- * Only fills in for port 0, only when XInput found nothing there, so a real +- * controller always wins and nothing changes for a port that has one. Keys are +- * read only while a window of THIS process is in the foreground, so typing in +- * another application does not drive the game. Set PAD_NO_KEYBOARD=1 to +- * disable it entirely. +- * +- * Arrows = d-pad, Z/X/A/S = cross/circle/square/triangle, Q/W = L1/R1, +- * 1/2 = L2/R2, Enter = START, Tab = SELECT. The left stick mirrors the d-pad +- * so a title that reads the stick instead is playable too. */ +-#ifdef _WIN32 +-static int pad_host_window_focused(void) +-{ +- HWND fg = GetForegroundWindow(); +- if (!fg) return 0; +- DWORD pid = 0; +- GetWindowThreadProcessId(fg, &pid); +- return pid == GetCurrentProcessId(); +-} +- +-static void pad_poll_keyboard(void) +-{ +- static int off = -1; +- if (off < 0) off = getenv("PAD_NO_KEYBOARD") ? 1 : 0; +- if (off) return; +- +- PadHostState* hs = &s_host_state[0]; +- if (!pad_host_window_focused()) { +- /* Release everything on focus loss, or a key held while alt-tabbing +- * would stay down forever. */ +- hs->buttons = 0; +- hs->analog_lx = hs->analog_ly = 128; +- hs->analog_rx = hs->analog_ry = 128; +- hs->connected = 1; +- return; +- } +- +- static const struct { int vk; u16 btn; } map[] = { +- { VK_UP, CELL_PAD_CTRL_UP }, { VK_DOWN, CELL_PAD_CTRL_DOWN }, +- { VK_LEFT, CELL_PAD_CTRL_LEFT }, { VK_RIGHT, CELL_PAD_CTRL_RIGHT }, +- { 'Z', CELL_PAD_CTRL_CROSS }, { 'X', CELL_PAD_CTRL_CIRCLE }, +- { 'A', CELL_PAD_CTRL_SQUARE }, { 'S', CELL_PAD_CTRL_TRIANGLE }, +- { 'Q', CELL_PAD_CTRL_L1 }, { 'W', CELL_PAD_CTRL_R1 }, +- { '1', CELL_PAD_CTRL_L2 }, { '2', CELL_PAD_CTRL_R2 }, +- { VK_RETURN, CELL_PAD_CTRL_START }, { VK_TAB, CELL_PAD_CTRL_SELECT }, +- }; +- +- u16 btns = 0; +- for (unsigned i = 0; i < sizeof map / sizeof map[0]; i++) +- if (GetAsyncKeyState(map[i].vk) & 0x8000) btns |= map[i].btn; +- +- hs->buttons = btns; +- hs->connected = 1; +- hs->analog_lx = (u8)((btns & CELL_PAD_CTRL_LEFT) ? 0 : +- (btns & CELL_PAD_CTRL_RIGHT) ? 255 : 128); +- hs->analog_ly = (u8)((btns & CELL_PAD_CTRL_UP) ? 0 : +- (btns & CELL_PAD_CTRL_DOWN) ? 255 : 128); +- hs->analog_rx = hs->analog_ry = 128; +- hs->trigger_l2 = (u8)((btns & CELL_PAD_CTRL_L2) ? 255 : 0); +- hs->trigger_r2 = (u8)((btns & CELL_PAD_CTRL_R2) ? 255 : 0); +- +- { static int said = 0; +- if (!said && btns) { said = 1; +- printf("[cellPad] keyboard fallback active on port 0 (no XInput device)\n"); +- fflush(stdout); } } +-} +-#endif +- + /* XInputGetState on a slot with nothing plugged in costs about 140 us (2 us on + * a connected one), and the backend is polled at least once a frame: three + * empty slots beside one pad were 0.6 ms of every frame on God of War HD's +@@ -710,9 +793,7 @@ static void pad_poll_backend(void) + #elif PAD_BACKEND_SDL2 + pad_poll_sdl2(); + #endif +-#ifdef _WIN32 + if (!s_host_state[0].connected) pad_poll_keyboard(); +-#endif + pad_track_assign(); + pad_unlock(); + } +diff --git a/libs/input/tests/test_pad_keyboard.c b/libs/input/tests/test_pad_keyboard.c +new file mode 100644 +index 00000000..ca65aa38 +--- /dev/null ++++ b/libs/input/tests/test_pad_keyboard.c +@@ -0,0 +1,144 @@ ++/* cellPad's keyboard fallback on port 0 (the SDL source): with no controller ++ * plugged in the keyboard plays the pad -- arrows = d-pad, Z/X/A/S = cross/ ++ * circle/square/triangle, Q/W = L1/R1, 1/2 = L2/R2, Return = START, Tab = ++ * SELECT, the left stick mirrors the d-pad -- while a window of the process has ++ * the keyboard focus, and releases everything when it loses it. ++ * ++ * clang -std=gnu17 -DPS3RECOMP_PAD_KEYBOARD_SDL -I include $(sdl2-config --cflags) \ ++ * -I "$(sdl2-config --prefix)/include" libs/input/tests/test_pad_keyboard.c \ ++ * $(sdl2-config --libs) -o /tmp/test_pad_keyboard && /tmp/test_pad_keyboard ++ * ++ * PS3RECOMP_PAD_KEYBOARD_SDL makes macOS read the keyboard through SDL like ++ * every other host that is not Windows, so the same table is tested everywhere. ++ * No controller exists and no window either: the test defines the SDL calls the ++ * backend makes (they take precedence over libSDL2's), with a keyboard state ++ * and a focus flag it sets itself. ++ */ ++#include "../cellPad.c" ++#include ++#include ++#include ++uint8_t* vm_base; ++uint32_t ppu_vm_size; ++int g_resv_store_active; ++uint32_t g_ww_lo, g_ww_hi; ++void ppu_resv_break_store(uint64_t ea) { (void)ea; } ++void ps3_ww_report_inline(uint32_t a, uint64_t v, int w) { (void)a; (void)v; (void)w; } ++int spu_coh_is_reserved(uint32_t a) { (void)a; return 0; } ++u32 cellGcm_flip_request_count(void) { return 0; } /* PAD_CLOCK=flips */ ++void spu_coh_notify_write(uint32_t a) { (void)a; } ++void spu_lockline_lock(void) {} ++void spu_lockline_unlock(void) {} ++ ++/* ---- the fake SDL: no controller, a keyboard the test drives ----------------- */ ++static Uint8 s_keys[SDL_NUM_SCANCODES]; ++static int s_focus; ++ ++int SDL_NumJoysticks(void) { return 0; } ++int SDL_PeepEvents(SDL_Event* ev, int n, SDL_eventaction action, Uint32 lo, Uint32 hi) ++{ ++ (void)ev; (void)n; (void)action; (void)lo; (void)hi; ++ return 0; ++} ++Uint32 SDL_WasInit(Uint32 flags) { (void)flags; return flags; } ++int SDL_InitSubSystem(Uint32 flags) { (void)flags; return 0; } ++const char* SDL_GetError(void) { return "fake"; } ++void SDL_GameControllerUpdate(void) {} ++const Uint8* SDL_GetKeyboardState(int* numkeys) { if (numkeys) *numkeys = SDL_NUM_SCANCODES; return s_keys; } ++SDL_Window* SDL_GetKeyboardFocus(void) { return s_focus ? (SDL_Window*)&s_keys : NULL; } ++ ++/* ---- helpers ---------------------------------------------------------------- */ ++/* One 16-bit word of cellPadGetData(0) (0 if it reported nothing new). */ ++static unsigned data_word(int offset) ++{ ++ const uint32_t ea = 0x2000; ++ usleep((PAD_POLL_INTERVAL_MS + 2) * 1000); ++ assert(cellPadGetData(0, (CellPadData*)(uintptr_t)ea) == CELL_OK); ++ assert(vm_base[ea + 3] != 0); /* len > 0: a report was handed out */ ++ const uint8_t* b = vm_base + ea + 4 + offset * 2; ++ return (unsigned)b[0] << 8 | b[1]; ++} ++#define D1() data_word(CELL_PAD_BTN_OFFSET_DIGITAL1) ++#define D2() data_word(CELL_PAD_BTN_OFFSET_DIGITAL2) ++static void keys(int a, int b, int c) ++{ ++ memset(s_keys, 0, sizeof s_keys); ++ if (a) s_keys[a] = 1; ++ if (b) s_keys[b] = 1; ++ if (c) s_keys[c] = 1; ++} ++/* DIGITAL1 / DIGITAL2 bits */ ++#define SELECT 0x01u ++#define START 0x08u ++#define UP 0x10u ++#define RIGHT 0x20u ++#define DOWN 0x40u ++#define LEFT 0x80u ++#define L2 0x01u ++#define R2 0x02u ++#define L1 0x04u ++#define R1 0x08u ++#define TRI 0x10u ++#define CIRCLE 0x20u ++#define CROSS 0x40u ++#define SQUARE 0x80u ++ ++int main(void) ++{ ++ vm_base = mmap(NULL, 0x10000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); ++ assert(vm_base != MAP_FAILED); ++ assert(cellPadInit(4) == CELL_OK); ++ s_focus = 1; ++ ++ /* Nothing pressed: neutral, sticks centred (0 would be full deflection). */ ++ keys(0, 0, 0); ++ assert(D1() == 0 && D2() == 0); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_X) == 128); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_Y) == 128); ++ ++ /* The face and shoulder buttons. */ ++ static const struct { int key; unsigned bit; } d2[] = { ++ { SDL_SCANCODE_Z, CROSS }, { SDL_SCANCODE_X, CIRCLE }, { SDL_SCANCODE_A, SQUARE }, ++ { SDL_SCANCODE_S, TRI }, { SDL_SCANCODE_Q, L1 }, { SDL_SCANCODE_W, R1 }, ++ { SDL_SCANCODE_1, L2 }, { SDL_SCANCODE_2, R2 }, ++ }; ++ for (unsigned i = 0; i < sizeof d2 / sizeof d2[0]; i++) { ++ keys(d2[i].key, 0, 0); ++ const unsigned v = D2(); ++ assert(v == d2[i].bit); ++ keys(0, 0, 0); ++ assert(D2() == 0); ++ } ++ keys(SDL_SCANCODE_RETURN, 0, 0); ++ assert(D1() == START); ++ keys(SDL_SCANCODE_TAB, 0, 0); ++ assert(D1() == SELECT); ++ ++ /* The d-pad, and the left stick that mirrors it. */ ++ keys(SDL_SCANCODE_LEFT, SDL_SCANCODE_UP, 0); ++ assert(D1() == (LEFT | UP)); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_X) == 0); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_Y) == 0); ++ keys(SDL_SCANCODE_RIGHT, SDL_SCANCODE_DOWN, 0); ++ assert(D1() == (RIGHT | DOWN)); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_X) == 255); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_Y) == 255); ++ ++ /* Several keys at once. */ ++ keys(SDL_SCANCODE_Z, SDL_SCANCODE_RIGHT, SDL_SCANCODE_RETURN); ++ assert((D2() & CROSS) && (D1() == (RIGHT | START))); ++ ++ /* The window loses the keyboard focus with keys still down: everything is ++ * released, or a key held while switching to another program would stay ++ * pressed for good. */ ++ keys(SDL_SCANCODE_Z, SDL_SCANCODE_LEFT, 0); ++ s_focus = 0; ++ assert(D1() == 0 && D2() == 0); ++ assert(data_word(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_X) == 128); ++ s_focus = 1; ++ assert(D2() == CROSS); ++ ++ assert(cellPadEnd() == CELL_OK); ++ printf("test_pad_keyboard: ok\n"); ++ return 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-612/tests/test.sh b/tasks/sp00nznet__ps3recomp-612/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-612/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-612/tests/verifier.py b/tasks/sp00nznet__ps3recomp-612/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-612/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-613/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-613/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-613/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-613/instruction.md b/tasks/sp00nznet__ps3recomp-613/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef1a424bc3f208425a6c42766ab5bdb625b3274b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-613/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Metal: a Quit item in the app menu, and no alert sound on a key press + +## Description + +Two small things in the window the Metal backend opens, both found by running a port in it. + +- **No menu bar.** The window had none, so the app menu was empty. It now gets a "Quit " item. Cmd+Q is still taken by the event pump first (#544); the item calls `ps3_host_quit` as Cmd+Q does, so the guest sees `REQUEST_EXITGAME` whichever way the player leaves. (The comment at the Cmd+Q branch said there was no app menu; it is updated.) +- **Alert sound on every key press.** A game reads the keyboard by polling (the pad's keyboard fallback does), so key down and up events have no consumer in the window, and AppKit answered each with the system alert sound. The pump drops them after the Cmd+Q check. + +No automated test: this is window-system behaviour, and there is no test harness that opens an NSWindow. The code is what a game port on macOS ships; here it was compiled (`clang -fobjc-arc -fsyntax-only`) against v0.18.0. + +Open PRs: none touches these lines (#470 and #585 change other parts of `rsx_metal_backend.m`). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-613/solution/patch.diff b/tasks/sp00nznet__ps3recomp-613/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..763563a569cd325887b4dd89af3173a2ae6d1dd7 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-613/solution/patch.diff @@ -0,0 +1,74 @@ +diff --git a/libs/video/rsx_metal_backend.m b/libs/video/rsx_metal_backend.m +index ad8db0b5..f40aa969 100644 +--- a/libs/video/rsx_metal_backend.m ++++ b/libs/video/rsx_metal_backend.m +@@ -826,10 +826,41 @@ static void window_close_observer_start(NSWindow* window) + }]; + } + ++/* The menu's Quit item does what Cmd+Q does: it posts that key press, and the message pump (pump_messages_impl) turns it ++ * into ps3_host_quit. The one place that calls it is the pump, so a program that links the backend without the HLE ++ * modules (the Metal tests) needs no stub for it as long as it never pumps. */ ++@interface RsxQuitTarget : NSObject ++- (void)quit:(id)sender; ++@end ++@implementation RsxQuitTarget ++- (void)quit:(id)sender ++{ ++ (void)sender; ++ NSEvent* q = [NSEvent keyEventWithType:NSEventTypeKeyDown location:NSZeroPoint ++ modifierFlags:NSEventModifierFlagCommand timestamp:0 windowNumber:0 context:nil ++ characters:@"q" charactersIgnoringModifiers:@"q" isARepeat:NO keyCode:0x0C]; ++ [NSApp postEvent:q atStart:YES]; ++} ++@end ++static RsxQuitTarget* s_quit_target; ++ + static int create_window_impl(const char* title) + { + [NSApplication sharedApplication]; + [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; ++ { /* A plain run loop has no menu bar, so the app menu was empty: a "Quit <title>" item is all it gets. */ ++ s_quit_target = [RsxQuitTarget new]; ++ NSMenu* bar = [NSMenu new]; ++ NSMenuItem* appItem = [NSMenuItem new]; ++ [bar addItem:appItem]; ++ NSMenu* appMenu = [NSMenu new]; ++ NSString* quitTitle = [@"Quit " stringByAppendingString:[NSString stringWithUTF8String:(title ? title : "ps3recomp")]]; ++ NSMenuItem* quit = [[NSMenuItem alloc] initWithTitle:quitTitle action:@selector(quit:) keyEquivalent:@"q"]; ++ [quit setTarget:s_quit_target]; ++ [appMenu addItem:quit]; ++ [appItem setSubmenu:appMenu]; ++ [NSApp setMainMenu:bar]; ++ } + + NSRect frame = NSMakeRect(0, 0, (CGFloat)s_width, (CGFloat)s_height); + s_window = [[NSWindow alloc] +@@ -4670,10 +4701,11 @@ static int pump_messages_impl(void) + inMode:NSDefaultRunLoopMode + dequeue:YES]; + if (!ev) break; +- /* Cmd+Q quits. The host turns a plain run loop with no app menu, +- * so AppKit has no Quit item to send it to and nothing happened. +- * It ends the game the way the console's Quit Game does +- * (cellSysutil.c ps3_host_quit: REQUEST_EXITGAME, then exit 0). */ ++ /* Cmd+Q quits. A plain run loop has no app menu, so AppKit had no ++ * Quit item to send it to and nothing happened; it is taken here, before ++ * the menu's key equivalent could be, and ends the game the way the ++ * console's Quit Game does (cellSysutil.c ps3_host_quit: REQUEST_EXITGAME, ++ * then exit 0). The menu's Quit item (create_window_impl) does the same. */ + if ([ev type] == NSEventTypeKeyDown && ([ev keyCode] & 127u) == 0x0C /* Q */ && + ([ev modifierFlags] & NSEventModifierFlagCommand)) { + if (![ev isARepeat]) { +@@ -4682,6 +4714,11 @@ static int pump_messages_impl(void) + } + continue; + } ++ /* The pad reads the keyboard by polling (cellPad), so the other key events have no consumer here: the ++ * window would answer each with the system alert sound. */ ++ if ([ev type] == NSEventTypeKeyDown || [ev type] == NSEventTypeKeyUp) { ++ continue; ++ } + [NSApp sendEvent:ev]; + } + } diff --git a/tasks/sp00nznet__ps3recomp-613/solution/solve.sh b/tasks/sp00nznet__ps3recomp-613/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-613/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-613/task.toml b/tasks/sp00nznet__ps3recomp-613/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..50e965fd9e8a0b23bfdd1264f231f1724dcd39f3 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-613/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-613" +description = "Metal: a Quit item in the app menu, and no alert sound on a key press" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/613" +source_access = "auto" +built_at = "2026-11-16T16:09:59.679909+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:890310b255bbaef2f8da2ab444ef3343592b2e310507a39555d49bd91be118cf" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "libs/video/rsx_metal_backend.m", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 45 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.128166+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-613/tests/capture.py b/tasks/sp00nznet__ps3recomp-613/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-613/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-613/tests/instruction.md b/tasks/sp00nznet__ps3recomp-613/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef1a424bc3f208425a6c42766ab5bdb625b3274b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-613/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Metal: a Quit item in the app menu, and no alert sound on a key press + +## Description + +Two small things in the window the Metal backend opens, both found by running a port in it. + +- **No menu bar.** The window had none, so the app menu was empty. It now gets a "Quit <title>" item. Cmd+Q is still taken by the event pump first (#544); the item calls `ps3_host_quit` as Cmd+Q does, so the guest sees `REQUEST_EXITGAME` whichever way the player leaves. (The comment at the Cmd+Q branch said there was no app menu; it is updated.) +- **Alert sound on every key press.** A game reads the keyboard by polling (the pad's keyboard fallback does), so key down and up events have no consumer in the window, and AppKit answered each with the system alert sound. The pump drops them after the Cmd+Q check. + +No automated test: this is window-system behaviour, and there is no test harness that opens an NSWindow. The code is what a game port on macOS ships; here it was compiled (`clang -fobjc-arc -fsyntax-only`) against v0.18.0. + +Open PRs: none touches these lines (#470 and #585 change other parts of `rsx_metal_backend.m`). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-613/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-613/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..763563a569cd325887b4dd89af3173a2ae6d1dd7 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-613/tests/oracle.patch @@ -0,0 +1,74 @@ +diff --git a/libs/video/rsx_metal_backend.m b/libs/video/rsx_metal_backend.m +index ad8db0b5..f40aa969 100644 +--- a/libs/video/rsx_metal_backend.m ++++ b/libs/video/rsx_metal_backend.m +@@ -826,10 +826,41 @@ static void window_close_observer_start(NSWindow* window) + }]; + } + ++/* The menu's Quit item does what Cmd+Q does: it posts that key press, and the message pump (pump_messages_impl) turns it ++ * into ps3_host_quit. The one place that calls it is the pump, so a program that links the backend without the HLE ++ * modules (the Metal tests) needs no stub for it as long as it never pumps. */ ++@interface RsxQuitTarget : NSObject ++- (void)quit:(id)sender; ++@end ++@implementation RsxQuitTarget ++- (void)quit:(id)sender ++{ ++ (void)sender; ++ NSEvent* q = [NSEvent keyEventWithType:NSEventTypeKeyDown location:NSZeroPoint ++ modifierFlags:NSEventModifierFlagCommand timestamp:0 windowNumber:0 context:nil ++ characters:@"q" charactersIgnoringModifiers:@"q" isARepeat:NO keyCode:0x0C]; ++ [NSApp postEvent:q atStart:YES]; ++} ++@end ++static RsxQuitTarget* s_quit_target; ++ + static int create_window_impl(const char* title) + { + [NSApplication sharedApplication]; + [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; ++ { /* A plain run loop has no menu bar, so the app menu was empty: a "Quit <title>" item is all it gets. */ ++ s_quit_target = [RsxQuitTarget new]; ++ NSMenu* bar = [NSMenu new]; ++ NSMenuItem* appItem = [NSMenuItem new]; ++ [bar addItem:appItem]; ++ NSMenu* appMenu = [NSMenu new]; ++ NSString* quitTitle = [@"Quit " stringByAppendingString:[NSString stringWithUTF8String:(title ? title : "ps3recomp")]]; ++ NSMenuItem* quit = [[NSMenuItem alloc] initWithTitle:quitTitle action:@selector(quit:) keyEquivalent:@"q"]; ++ [quit setTarget:s_quit_target]; ++ [appMenu addItem:quit]; ++ [appItem setSubmenu:appMenu]; ++ [NSApp setMainMenu:bar]; ++ } + + NSRect frame = NSMakeRect(0, 0, (CGFloat)s_width, (CGFloat)s_height); + s_window = [[NSWindow alloc] +@@ -4670,10 +4701,11 @@ static int pump_messages_impl(void) + inMode:NSDefaultRunLoopMode + dequeue:YES]; + if (!ev) break; +- /* Cmd+Q quits. The host turns a plain run loop with no app menu, +- * so AppKit has no Quit item to send it to and nothing happened. +- * It ends the game the way the console's Quit Game does +- * (cellSysutil.c ps3_host_quit: REQUEST_EXITGAME, then exit 0). */ ++ /* Cmd+Q quits. A plain run loop has no app menu, so AppKit had no ++ * Quit item to send it to and nothing happened; it is taken here, before ++ * the menu's key equivalent could be, and ends the game the way the ++ * console's Quit Game does (cellSysutil.c ps3_host_quit: REQUEST_EXITGAME, ++ * then exit 0). The menu's Quit item (create_window_impl) does the same. */ + if ([ev type] == NSEventTypeKeyDown && ([ev keyCode] & 127u) == 0x0C /* Q */ && + ([ev modifierFlags] & NSEventModifierFlagCommand)) { + if (![ev isARepeat]) { +@@ -4682,6 +4714,11 @@ static int pump_messages_impl(void) + } + continue; + } ++ /* The pad reads the keyboard by polling (cellPad), so the other key events have no consumer here: the ++ * window would answer each with the system alert sound. */ ++ if ([ev type] == NSEventTypeKeyDown || [ev type] == NSEventTypeKeyUp) { ++ continue; ++ } + [NSApp sendEvent:ev]; + } + } diff --git a/tasks/sp00nznet__ps3recomp-613/tests/test.sh b/tasks/sp00nznet__ps3recomp-613/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-613/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-613/tests/verifier.py b/tasks/sp00nznet__ps3recomp-613/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-613/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-614/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-614/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-614/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-614/instruction.md b/tasks/sp00nznet__ps3recomp-614/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..419a7730467d1b36d8c24540b902b706f4d4d214 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-614/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** Resizable window: the picture keeps its aspect ratio, and PS3RECOMP_FULLSCREEN starts in fullscreen + +## Description + +A window can be resized (the Metal one always could; the Vulkan one was created fixed), but the picture did not follow: Metal stretched a drawable of the game's size over the window, so a window of another shape distorted it. This makes the picture keep its aspect ratio and adds a way to start in fullscreen. + +**Metal** +- The drawable follows the window in device pixels: the message pump records the content size, the present resizes the `CAMetalLayer` to it, and the display pass fits the picture into it, centred, black around it, with a linear filter when it is scaled (a 1:1 picture stays point-sampled). The headless and host-surface targets (#509) are the size the title asked for and are filled as before. +- `PS3RECOMP_METAL_WINDOW=WxH` sets the initial size, in points. +- The window is a fullscreen-primary one, so the green button works, and `PS3RECOMP_FULLSCREEN=1` starts in fullscreen (a window handed over from another executable keeps the state it had). + +**Vulkan** (Linux; the backend is not built on Windows in this tree) +- The SDL window is created resizable (minimum 320x180). F11 or Alt+Enter switches it to borderless fullscreen on its display and back, hiding the cursor meanwhile. `PS3RECOMP_FULLSCREEN=1` starts in fullscreen, as does the older `PS3RECOMP_VK_FULLSCREEN`. +- The frame is blitted into the largest centred rectangle of its aspect ratio and the rest of the swapchain image is cleared to black. +- The swapchain is recreated on the next present after a size, maximize, restore or fullscreen change, and presents are skipped while the window is minimized: with no drawable area the out-of-date swapchain could not be recreated at 0x0 and the window was dropped. + +**Checked** +- Metal on macOS, a game running in the window: with `PS3RECOMP_METAL_WINDOW=1000x400` the log reports `drawable 2000x800 (window)` and a screenshot of the window shows the 16:9 picture centred with black bars on both sides, undistorted; with `PS3RECOMP_FULLSCREEN=1` the window goes to native fullscreen (`drawable 2704x1698`) and the picture is letterboxed on that 16:10 display. Resizing the window by hand and the headless path (unchanged: `fill`) I did not run. +- Vulkan: compiles (`clang -fsyntax-only` with the Linux branch); I have no Vulkan device here, so none of it ran. The logic is the same arithmetic as the Metal one. +- No automated test: both are window-system behaviour with no harness that opens a window. + +A follow-up for after #613 (the Quit menu) is a "Toggle Full Screen" item on Ctrl+Cmd+F; this PR does not depend on a menu. + +Open PRs: I merged this branch with the head of every open PR (`git merge-tree`) and it adds no conflict that the PR did not already have with master. #470 changes the same display function (`eng_blit_to_display`) on other lines, and #536 the Vulkan engine draws elsewhere in `rsx_vulkan_backend.c`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-614/solution/patch.diff b/tasks/sp00nznet__ps3recomp-614/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ce296dc6d097e6e3fd99151baba0788e1d6a8f4a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-614/solution/patch.diff @@ -0,0 +1,245 @@ +diff --git a/libs/video/rsx_metal_backend.m b/libs/video/rsx_metal_backend.m +index ad8db0b5..a6788e08 100644 +--- a/libs/video/rsx_metal_backend.m ++++ b/libs/video/rsx_metal_backend.m +@@ -92,6 +92,9 @@ + #if !TARGET_OS_IPHONE + static id s_window_close_observer; + #endif ++/* The window's content size in device pixels, kept current by the message pump (main thread) and read ++ * by the present path, which sizes the drawable to it. 0 until the first pump. */ ++static volatile u32 s_win_px_w, s_win_px_h; + static int s_ready; + static u32 s_width = 1280; + static u32 s_height = 720; +@@ -831,7 +834,14 @@ static int create_window_impl(const char* title) + [NSApplication sharedApplication]; + [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; + ++ /* PS3RECOMP_METAL_WINDOW=<w>x<h>: initial content size in points (default: the game's size). */ + NSRect frame = NSMakeRect(0, 0, (CGFloat)s_width, (CGFloat)s_height); ++ { ++ unsigned ww = 0, wh = 0; ++ const char* ws = getenv("PS3RECOMP_METAL_WINDOW"); ++ if (ws && sscanf(ws, "%ux%u", &ww, &wh) == 2 && ww >= 160 && wh >= 90 && ww <= 16384 && wh <= 16384) ++ frame.size = NSMakeSize((CGFloat)ww, (CGFloat)wh); ++ } + s_window = [[NSWindow alloc] + initWithContentRect:frame + styleMask:(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | +@@ -864,10 +874,17 @@ static int create_window_impl(const char* title) + [view setWantsLayer:YES]; + [view setLayer:s_layer]; + ++ [s_window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary]; + [s_window makeKeyAndOrderFront:nil]; + [NSApp activateIgnoringOtherApps:YES]; + if (was_fullscreen) [s_window toggleFullScreen:nil]; + fps_start(); ++ /* PS3RECOMP_FULLSCREEN=1, the same for every backend: start in fullscreen (a window handed over from another ++ * executable keeps the state it had); the picture is letterboxed as in a resized window. */ ++ { ++ const char* fs = getenv("PS3RECOMP_FULLSCREEN"); ++ if (!was_fullscreen && fs && fs[0] && fs[0] != '0') [s_window toggleFullScreen:nil]; ++ } + return 0; + } + +@@ -4219,13 +4236,23 @@ static void eng_blit_to_display(id<MTLCommandBuffer> cb, id<MTLTexture> src, + } + MTLRenderPassDescriptor* rp = [MTLRenderPassDescriptor renderPassDescriptor]; + rp.colorAttachments[0].texture = dst; +- rp.colorAttachments[0].loadAction = MTLLoadActionDontCare; ++ rp.colorAttachments[0].loadAction = MTLLoadActionClear; ++ rp.colorAttachments[0].clearColor = MTLClearColorMake(0.0, 0.0, 0.0, 1.0); + rp.colorAttachments[0].storeAction = MTLStoreActionStore; + id<MTLRenderCommandEncoder> e = [cb renderCommandEncoderWithDescriptor:rp]; + if (!e) return; ++ /* In the window the picture keeps its aspect ratio: fitted into the drawable and centred, black around it. The ++ * headless and host-surface targets are the size the title asked for and are filled as before. */ ++ const double dw = (double)[dst width], dh = (double)[dst height]; ++ const double sw = (double)[src width], sh = (double)[src height]; ++ const int fill = s_headless || s_host; ++ const double fit = fmin(dw / sw, dh / sh); ++ const double vw = fill ? dw : floor(sw * fit + 0.5), vh = fill ? dh : floor(sh * fit + 0.5); ++ [e setViewport:(MTLViewport){floor((dw - vw) * 0.5), floor((dh - vh) * 0.5), vw, vh, 0.0, 1.0}]; + [e setRenderPipelineState:s_eng_blit_pso]; + [e setFragmentTexture:src atIndex:0]; +- [e setFragmentSamplerState:s_eng_point_sampler atIndex:0]; ++ const int scaled = !fill && (vw != sw || vh != sh); /* a resized window filters; 1:1 and the fixed targets stay point-sampled */ ++ [e setFragmentSamplerState:(scaled ? s_default_sampler : s_eng_point_sampler) atIndex:0]; + /* The video out's gamma (cellVideoOutSetGamma, the title's brightness + * setting): out = in^gamma, as RPCS3's calibration pass applies it. The + * sharpening taps are one source texel apart. */ +@@ -4272,6 +4299,14 @@ static void eng_encode_and_commit(id<MTLTexture> present_dst) + } + dst = s_host_tex[host_slot]; + } else { ++ /* The drawable is the window's size in device pixels, so the compositor does not ++ * stretch it; eng_blit_to_display fits the game picture into it. */ ++ const u32 ww = s_win_px_w, wh = s_win_px_h; ++ const CGSize cur = s_layer.drawableSize; ++ if (ww && wh && ((u32)cur.width != ww || (u32)cur.height != wh)) { ++ s_layer.drawableSize = CGSizeMake((CGFloat)ww, (CGFloat)wh); ++ fprintf(stderr, "[RSX metal] drawable %ux%u (window)\n", ww, wh); ++ } + drawable = [s_layer nextDrawable]; + if (!drawable) { /* compositor is busy; skip */ + dispatch_semaphore_signal(s_inflight); +@@ -4684,6 +4719,12 @@ static int pump_messages_impl(void) + } + [NSApp sendEvent:ev]; + } ++ if (s_window) { ++ NSView* v = [s_window contentView]; ++ const NSSize px = [v convertSizeToBacking:[v bounds].size]; ++ s_win_px_w = (u32)px.width; ++ s_win_px_h = (u32)px.height; ++ } + } + #endif + return atomic_load(&s_closed) ? -1 : 0; +diff --git a/libs/video/rsx_vulkan_backend.c b/libs/video/rsx_vulkan_backend.c +index db64302e..4c49ac96 100644 +--- a/libs/video/rsx_vulkan_backend.c ++++ b/libs/video/rsx_vulkan_backend.c +@@ -1749,8 +1749,11 @@ static void vk_window_open(const char* title) + VK_LOG("window disabled, continuing headless: SDL video init failed: %s\n", SDL_GetError()); + return; + } +- Uint32 flags = SDL_WINDOW_VULKAN | SDL_WINDOW_SHOWN; +- if (vk_env_on("PS3RECOMP_VK_FULLSCREEN")) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; ++ /* Resizable and maximizable; F11 or Alt+Enter switches to borderless fullscreen and back. The frame keeps its ++ * aspect ratio inside whatever size the window has (vk_window_fit). */ ++ Uint32 flags = SDL_WINDOW_VULKAN | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE; ++ /* PS3RECOMP_FULLSCREEN=1 (--fullscreen), the same for every backend; PS3RECOMP_VK_FULLSCREEN is the older name. */ ++ if (vk_env_on("PS3RECOMP_FULLSCREEN") || vk_env_on("PS3RECOMP_VK_FULLSCREEN")) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; + s_vk.window = SDL_CreateWindow(title && title[0] ? title : "ps3recomp", + SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, + (int)s_vk.width, (int)s_vk.height, flags); +@@ -1761,6 +1764,8 @@ static void vk_window_open(const char* title) + vk_window_drop(why); + return; + } ++ SDL_SetWindowMinimumSize(s_vk.window, 320, 180); ++ if (flags & SDL_WINDOW_FULLSCREEN_DESKTOP) SDL_ShowCursor(SDL_DISABLE); + unsigned n = 0; + if (!SDL_Vulkan_GetInstanceExtensions(s_vk.window, &n, NULL) || n == 0 || n > 16 || + !SDL_Vulkan_GetInstanceExtensions(s_vk.window, &n, s_vk.inst_exts)) { +@@ -1776,6 +1781,7 @@ static void vk_window_open(const char* title) + SDL_GetCurrentVideoDriver(), n); + } + ++/* 0 on success, 1 when the window has no drawable area right now (the old swapchain is kept), -1 on failure. */ + static int vk_create_swapchain(void) + { + VkSurfaceCapabilitiesKHR caps; +@@ -1820,7 +1826,7 @@ static int vk_create_swapchain(void) + if (ext.width > caps.maxImageExtent.width) ext.width = caps.maxImageExtent.width; + if (ext.height > caps.maxImageExtent.height) ext.height = caps.maxImageExtent.height; + } +- if (!ext.width || !ext.height) { VK_LOG("window has no drawable area\n"); return -1; } ++ if (!ext.width || !ext.height) return 1; /* minimized: no drawable area, try again once it is shown */ + + u32 count = caps.minImageCount + 1; + if (caps.maxImageCount && count > caps.maxImageCount) count = caps.maxImageCount; +@@ -1872,16 +1878,56 @@ static int vk_create_swapchain(void) + return 0; + } + ++/* The window changed size (or fullscreen state) since the swapchain was made: it is recreated before the next acquire. ++ * Also set while the window is minimized, when there is no drawable area to make one for. */ ++static int s_vk_resized; ++ ++/* Minimized, or no drawable area: nothing can be presented, and a swapchain cannot be created for it. */ ++static int vk_window_hidden(void) ++{ ++ int w = 0, h = 0; ++ if (SDL_GetWindowFlags(s_vk.window) & SDL_WINDOW_MINIMIZED) return 1; ++ SDL_Vulkan_GetDrawableSize(s_vk.window, &w, &h); ++ return w <= 0 || h <= 0; ++} ++ + static void vk_swapchain_lost(void) + { ++ if (vk_window_hidden()) { s_vk_resized = 1; return; } /* recreated once it is shown again */ + vk_device_idle(); +- if (vk_create_swapchain()) vk_window_drop("the swapchain could not be recreated"); ++ const int r = vk_create_swapchain(); ++ s_vk_resized = r > 0; /* the surface is 0x0 before SDL reports the window minimized */ ++ if (r < 0) vk_window_drop("the swapchain could not be recreated"); ++} ++ ++/* Where the frame goes in the swapchain image: the largest rectangle of the frame's aspect ratio, centred. The rest ++ * of the image is black (letterbox or pillarbox). */ ++typedef struct { u32 x, y, w, h; } vk_rect; ++ ++static vk_rect vk_window_fit(void) ++{ ++ const u32 dw = s_vk.sc_extent.width, dh = s_vk.sc_extent.height; ++ vk_rect r = { 0, 0, dw, dh }; ++ if (!s_vk.width || !s_vk.height) return r; ++ if ((u64)dw * s_vk.height > (u64)dh * s_vk.width) { ++ r.w = (u32)(((u64)dh * s_vk.width + s_vk.height / 2) / s_vk.height); ++ r.x = (dw - r.w) / 2; ++ } else { ++ r.h = (u32)(((u64)dw * s_vk.height + s_vk.width / 2) / s_vk.width); ++ r.y = (dh - r.h) / 2; ++ } ++ return r; + } + + /* Blit the offscreen target into the next swapchain image and present it. */ + static void vk_present_window(void) + { + if (!s_vk.windowed || !s_vk.swapchain) return; ++ if (vk_window_hidden()) return; ++ if (s_vk_resized) { ++ vk_swapchain_lost(); ++ if (!s_vk.windowed || s_vk_resized) return; ++ } + + u32 idx = 0; + VkResult r = pvkAcquireNextImageKHR(s_vk.device, s_vk.swapchain, UINT64_MAX, +@@ -1908,12 +1954,19 @@ static void vk_present_window(void) + }; + pvkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, NULL, 0, NULL, 1, &b); ++ const vk_rect fit = vk_window_fit(); ++ if (fit.w != s_vk.sc_extent.width || fit.h != s_vk.sc_extent.height) { ++ /* The bars. The clear and the blit write disjoint pixels, so they need no barrier between them. */ ++ static const VkClearColorValue black = { { 0.0f, 0.0f, 0.0f, 1.0f } }; ++ pvkCmdClearColorImage(cb, s_vk.sc_images[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &black, 1, ++ &b.subresourceRange); ++ } + VkImageBlit blit = { + .srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, + .srcOffsets = { { 0, 0, 0 }, { (int32_t)s_vk.width, (int32_t)s_vk.height, 1 } }, + .dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, +- .dstOffsets = { { 0, 0, 0 }, +- { (int32_t)s_vk.sc_extent.width, (int32_t)s_vk.sc_extent.height, 1 } }, ++ .dstOffsets = { { (int32_t)fit.x, (int32_t)fit.y, 0 }, ++ { (int32_t)(fit.x + fit.w), (int32_t)(fit.y + fit.h), 1 } }, + }; + pvkCmdBlitImage(cb, s_vk.color.img, VK_IMAGE_LAYOUT_GENERAL, + s_vk.sc_images[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, +@@ -4033,6 +4086,19 @@ int rsx_vulkan_backend_pump_messages(void) + while (SDL_PollEvent(&e)) { + if (e.type == SDL_QUIT) quit = 1; + else if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE) quit = 1; ++ else if (e.type == SDL_KEYDOWN && !e.key.repeat && s_vk.window && ++ (e.key.keysym.sym == SDLK_F11 || ++ (e.key.keysym.sym == SDLK_RETURN && (e.key.keysym.mod & KMOD_ALT)))) { ++ /* Borderless fullscreen on the window's display, and back. */ ++ const int full = (SDL_GetWindowFlags(s_vk.window) & SDL_WINDOW_FULLSCREEN_DESKTOP) != 0; ++ if (SDL_SetWindowFullscreen(s_vk.window, full ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP) == 0) ++ SDL_ShowCursor(full ? SDL_ENABLE : SDL_DISABLE); ++ s_vk_resized = 1; ++ } else if (e.type == SDL_WINDOWEVENT && ++ (e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED || e.window.event == SDL_WINDOWEVENT_RESTORED || ++ e.window.event == SDL_WINDOWEVENT_MAXIMIZED)) { ++ s_vk_resized = 1; ++ } + } + return quit ? -1 : 0; + } diff --git a/tasks/sp00nznet__ps3recomp-614/solution/solve.sh b/tasks/sp00nznet__ps3recomp-614/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-614/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-614/task.toml b/tasks/sp00nznet__ps3recomp-614/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b18f3eeaddf665c13fc3c6a0048f804da9065c8c --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-614/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-614" +description = "Resizable window: the picture keeps its aspect ratio, and PS3RECOMP_FULLSCREEN starts in fullscreen" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/614" +source_access = "auto" +built_at = "2026-11-16T16:09:59.678199+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:82aca397bf6280fe41fc38d61b37ea6c2013ef1f82d01117e0493235cdc39dd8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "libs/video/rsx_metal_backend.m", + "libs/video/rsx_vulkan_backend.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 123 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.129148+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-614/tests/capture.py b/tasks/sp00nznet__ps3recomp-614/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-614/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-614/tests/instruction.md b/tasks/sp00nznet__ps3recomp-614/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..419a7730467d1b36d8c24540b902b706f4d4d214 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-614/tests/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** Resizable window: the picture keeps its aspect ratio, and PS3RECOMP_FULLSCREEN starts in fullscreen + +## Description + +A window can be resized (the Metal one always could; the Vulkan one was created fixed), but the picture did not follow: Metal stretched a drawable of the game's size over the window, so a window of another shape distorted it. This makes the picture keep its aspect ratio and adds a way to start in fullscreen. + +**Metal** +- The drawable follows the window in device pixels: the message pump records the content size, the present resizes the `CAMetalLayer` to it, and the display pass fits the picture into it, centred, black around it, with a linear filter when it is scaled (a 1:1 picture stays point-sampled). The headless and host-surface targets (#509) are the size the title asked for and are filled as before. +- `PS3RECOMP_METAL_WINDOW=WxH` sets the initial size, in points. +- The window is a fullscreen-primary one, so the green button works, and `PS3RECOMP_FULLSCREEN=1` starts in fullscreen (a window handed over from another executable keeps the state it had). + +**Vulkan** (Linux; the backend is not built on Windows in this tree) +- The SDL window is created resizable (minimum 320x180). F11 or Alt+Enter switches it to borderless fullscreen on its display and back, hiding the cursor meanwhile. `PS3RECOMP_FULLSCREEN=1` starts in fullscreen, as does the older `PS3RECOMP_VK_FULLSCREEN`. +- The frame is blitted into the largest centred rectangle of its aspect ratio and the rest of the swapchain image is cleared to black. +- The swapchain is recreated on the next present after a size, maximize, restore or fullscreen change, and presents are skipped while the window is minimized: with no drawable area the out-of-date swapchain could not be recreated at 0x0 and the window was dropped. + +**Checked** +- Metal on macOS, a game running in the window: with `PS3RECOMP_METAL_WINDOW=1000x400` the log reports `drawable 2000x800 (window)` and a screenshot of the window shows the 16:9 picture centred with black bars on both sides, undistorted; with `PS3RECOMP_FULLSCREEN=1` the window goes to native fullscreen (`drawable 2704x1698`) and the picture is letterboxed on that 16:10 display. Resizing the window by hand and the headless path (unchanged: `fill`) I did not run. +- Vulkan: compiles (`clang -fsyntax-only` with the Linux branch); I have no Vulkan device here, so none of it ran. The logic is the same arithmetic as the Metal one. +- No automated test: both are window-system behaviour with no harness that opens a window. + +A follow-up for after #613 (the Quit menu) is a "Toggle Full Screen" item on Ctrl+Cmd+F; this PR does not depend on a menu. + +Open PRs: I merged this branch with the head of every open PR (`git merge-tree`) and it adds no conflict that the PR did not already have with master. #470 changes the same display function (`eng_blit_to_display`) on other lines, and #536 the Vulkan engine draws elsewhere in `rsx_vulkan_backend.c`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-614/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-614/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ce296dc6d097e6e3fd99151baba0788e1d6a8f4a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-614/tests/oracle.patch @@ -0,0 +1,245 @@ +diff --git a/libs/video/rsx_metal_backend.m b/libs/video/rsx_metal_backend.m +index ad8db0b5..a6788e08 100644 +--- a/libs/video/rsx_metal_backend.m ++++ b/libs/video/rsx_metal_backend.m +@@ -92,6 +92,9 @@ + #if !TARGET_OS_IPHONE + static id s_window_close_observer; + #endif ++/* The window's content size in device pixels, kept current by the message pump (main thread) and read ++ * by the present path, which sizes the drawable to it. 0 until the first pump. */ ++static volatile u32 s_win_px_w, s_win_px_h; + static int s_ready; + static u32 s_width = 1280; + static u32 s_height = 720; +@@ -831,7 +834,14 @@ static int create_window_impl(const char* title) + [NSApplication sharedApplication]; + [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; + ++ /* PS3RECOMP_METAL_WINDOW=<w>x<h>: initial content size in points (default: the game's size). */ + NSRect frame = NSMakeRect(0, 0, (CGFloat)s_width, (CGFloat)s_height); ++ { ++ unsigned ww = 0, wh = 0; ++ const char* ws = getenv("PS3RECOMP_METAL_WINDOW"); ++ if (ws && sscanf(ws, "%ux%u", &ww, &wh) == 2 && ww >= 160 && wh >= 90 && ww <= 16384 && wh <= 16384) ++ frame.size = NSMakeSize((CGFloat)ww, (CGFloat)wh); ++ } + s_window = [[NSWindow alloc] + initWithContentRect:frame + styleMask:(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | +@@ -864,10 +874,17 @@ static int create_window_impl(const char* title) + [view setWantsLayer:YES]; + [view setLayer:s_layer]; + ++ [s_window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary]; + [s_window makeKeyAndOrderFront:nil]; + [NSApp activateIgnoringOtherApps:YES]; + if (was_fullscreen) [s_window toggleFullScreen:nil]; + fps_start(); ++ /* PS3RECOMP_FULLSCREEN=1, the same for every backend: start in fullscreen (a window handed over from another ++ * executable keeps the state it had); the picture is letterboxed as in a resized window. */ ++ { ++ const char* fs = getenv("PS3RECOMP_FULLSCREEN"); ++ if (!was_fullscreen && fs && fs[0] && fs[0] != '0') [s_window toggleFullScreen:nil]; ++ } + return 0; + } + +@@ -4219,13 +4236,23 @@ static void eng_blit_to_display(id<MTLCommandBuffer> cb, id<MTLTexture> src, + } + MTLRenderPassDescriptor* rp = [MTLRenderPassDescriptor renderPassDescriptor]; + rp.colorAttachments[0].texture = dst; +- rp.colorAttachments[0].loadAction = MTLLoadActionDontCare; ++ rp.colorAttachments[0].loadAction = MTLLoadActionClear; ++ rp.colorAttachments[0].clearColor = MTLClearColorMake(0.0, 0.0, 0.0, 1.0); + rp.colorAttachments[0].storeAction = MTLStoreActionStore; + id<MTLRenderCommandEncoder> e = [cb renderCommandEncoderWithDescriptor:rp]; + if (!e) return; ++ /* In the window the picture keeps its aspect ratio: fitted into the drawable and centred, black around it. The ++ * headless and host-surface targets are the size the title asked for and are filled as before. */ ++ const double dw = (double)[dst width], dh = (double)[dst height]; ++ const double sw = (double)[src width], sh = (double)[src height]; ++ const int fill = s_headless || s_host; ++ const double fit = fmin(dw / sw, dh / sh); ++ const double vw = fill ? dw : floor(sw * fit + 0.5), vh = fill ? dh : floor(sh * fit + 0.5); ++ [e setViewport:(MTLViewport){floor((dw - vw) * 0.5), floor((dh - vh) * 0.5), vw, vh, 0.0, 1.0}]; + [e setRenderPipelineState:s_eng_blit_pso]; + [e setFragmentTexture:src atIndex:0]; +- [e setFragmentSamplerState:s_eng_point_sampler atIndex:0]; ++ const int scaled = !fill && (vw != sw || vh != sh); /* a resized window filters; 1:1 and the fixed targets stay point-sampled */ ++ [e setFragmentSamplerState:(scaled ? s_default_sampler : s_eng_point_sampler) atIndex:0]; + /* The video out's gamma (cellVideoOutSetGamma, the title's brightness + * setting): out = in^gamma, as RPCS3's calibration pass applies it. The + * sharpening taps are one source texel apart. */ +@@ -4272,6 +4299,14 @@ static void eng_encode_and_commit(id<MTLTexture> present_dst) + } + dst = s_host_tex[host_slot]; + } else { ++ /* The drawable is the window's size in device pixels, so the compositor does not ++ * stretch it; eng_blit_to_display fits the game picture into it. */ ++ const u32 ww = s_win_px_w, wh = s_win_px_h; ++ const CGSize cur = s_layer.drawableSize; ++ if (ww && wh && ((u32)cur.width != ww || (u32)cur.height != wh)) { ++ s_layer.drawableSize = CGSizeMake((CGFloat)ww, (CGFloat)wh); ++ fprintf(stderr, "[RSX metal] drawable %ux%u (window)\n", ww, wh); ++ } + drawable = [s_layer nextDrawable]; + if (!drawable) { /* compositor is busy; skip */ + dispatch_semaphore_signal(s_inflight); +@@ -4684,6 +4719,12 @@ static int pump_messages_impl(void) + } + [NSApp sendEvent:ev]; + } ++ if (s_window) { ++ NSView* v = [s_window contentView]; ++ const NSSize px = [v convertSizeToBacking:[v bounds].size]; ++ s_win_px_w = (u32)px.width; ++ s_win_px_h = (u32)px.height; ++ } + } + #endif + return atomic_load(&s_closed) ? -1 : 0; +diff --git a/libs/video/rsx_vulkan_backend.c b/libs/video/rsx_vulkan_backend.c +index db64302e..4c49ac96 100644 +--- a/libs/video/rsx_vulkan_backend.c ++++ b/libs/video/rsx_vulkan_backend.c +@@ -1749,8 +1749,11 @@ static void vk_window_open(const char* title) + VK_LOG("window disabled, continuing headless: SDL video init failed: %s\n", SDL_GetError()); + return; + } +- Uint32 flags = SDL_WINDOW_VULKAN | SDL_WINDOW_SHOWN; +- if (vk_env_on("PS3RECOMP_VK_FULLSCREEN")) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; ++ /* Resizable and maximizable; F11 or Alt+Enter switches to borderless fullscreen and back. The frame keeps its ++ * aspect ratio inside whatever size the window has (vk_window_fit). */ ++ Uint32 flags = SDL_WINDOW_VULKAN | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE; ++ /* PS3RECOMP_FULLSCREEN=1 (--fullscreen), the same for every backend; PS3RECOMP_VK_FULLSCREEN is the older name. */ ++ if (vk_env_on("PS3RECOMP_FULLSCREEN") || vk_env_on("PS3RECOMP_VK_FULLSCREEN")) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; + s_vk.window = SDL_CreateWindow(title && title[0] ? title : "ps3recomp", + SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, + (int)s_vk.width, (int)s_vk.height, flags); +@@ -1761,6 +1764,8 @@ static void vk_window_open(const char* title) + vk_window_drop(why); + return; + } ++ SDL_SetWindowMinimumSize(s_vk.window, 320, 180); ++ if (flags & SDL_WINDOW_FULLSCREEN_DESKTOP) SDL_ShowCursor(SDL_DISABLE); + unsigned n = 0; + if (!SDL_Vulkan_GetInstanceExtensions(s_vk.window, &n, NULL) || n == 0 || n > 16 || + !SDL_Vulkan_GetInstanceExtensions(s_vk.window, &n, s_vk.inst_exts)) { +@@ -1776,6 +1781,7 @@ static void vk_window_open(const char* title) + SDL_GetCurrentVideoDriver(), n); + } + ++/* 0 on success, 1 when the window has no drawable area right now (the old swapchain is kept), -1 on failure. */ + static int vk_create_swapchain(void) + { + VkSurfaceCapabilitiesKHR caps; +@@ -1820,7 +1826,7 @@ static int vk_create_swapchain(void) + if (ext.width > caps.maxImageExtent.width) ext.width = caps.maxImageExtent.width; + if (ext.height > caps.maxImageExtent.height) ext.height = caps.maxImageExtent.height; + } +- if (!ext.width || !ext.height) { VK_LOG("window has no drawable area\n"); return -1; } ++ if (!ext.width || !ext.height) return 1; /* minimized: no drawable area, try again once it is shown */ + + u32 count = caps.minImageCount + 1; + if (caps.maxImageCount && count > caps.maxImageCount) count = caps.maxImageCount; +@@ -1872,16 +1878,56 @@ static int vk_create_swapchain(void) + return 0; + } + ++/* The window changed size (or fullscreen state) since the swapchain was made: it is recreated before the next acquire. ++ * Also set while the window is minimized, when there is no drawable area to make one for. */ ++static int s_vk_resized; ++ ++/* Minimized, or no drawable area: nothing can be presented, and a swapchain cannot be created for it. */ ++static int vk_window_hidden(void) ++{ ++ int w = 0, h = 0; ++ if (SDL_GetWindowFlags(s_vk.window) & SDL_WINDOW_MINIMIZED) return 1; ++ SDL_Vulkan_GetDrawableSize(s_vk.window, &w, &h); ++ return w <= 0 || h <= 0; ++} ++ + static void vk_swapchain_lost(void) + { ++ if (vk_window_hidden()) { s_vk_resized = 1; return; } /* recreated once it is shown again */ + vk_device_idle(); +- if (vk_create_swapchain()) vk_window_drop("the swapchain could not be recreated"); ++ const int r = vk_create_swapchain(); ++ s_vk_resized = r > 0; /* the surface is 0x0 before SDL reports the window minimized */ ++ if (r < 0) vk_window_drop("the swapchain could not be recreated"); ++} ++ ++/* Where the frame goes in the swapchain image: the largest rectangle of the frame's aspect ratio, centred. The rest ++ * of the image is black (letterbox or pillarbox). */ ++typedef struct { u32 x, y, w, h; } vk_rect; ++ ++static vk_rect vk_window_fit(void) ++{ ++ const u32 dw = s_vk.sc_extent.width, dh = s_vk.sc_extent.height; ++ vk_rect r = { 0, 0, dw, dh }; ++ if (!s_vk.width || !s_vk.height) return r; ++ if ((u64)dw * s_vk.height > (u64)dh * s_vk.width) { ++ r.w = (u32)(((u64)dh * s_vk.width + s_vk.height / 2) / s_vk.height); ++ r.x = (dw - r.w) / 2; ++ } else { ++ r.h = (u32)(((u64)dw * s_vk.height + s_vk.width / 2) / s_vk.width); ++ r.y = (dh - r.h) / 2; ++ } ++ return r; + } + + /* Blit the offscreen target into the next swapchain image and present it. */ + static void vk_present_window(void) + { + if (!s_vk.windowed || !s_vk.swapchain) return; ++ if (vk_window_hidden()) return; ++ if (s_vk_resized) { ++ vk_swapchain_lost(); ++ if (!s_vk.windowed || s_vk_resized) return; ++ } + + u32 idx = 0; + VkResult r = pvkAcquireNextImageKHR(s_vk.device, s_vk.swapchain, UINT64_MAX, +@@ -1908,12 +1954,19 @@ static void vk_present_window(void) + }; + pvkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, 0, NULL, 0, NULL, 1, &b); ++ const vk_rect fit = vk_window_fit(); ++ if (fit.w != s_vk.sc_extent.width || fit.h != s_vk.sc_extent.height) { ++ /* The bars. The clear and the blit write disjoint pixels, so they need no barrier between them. */ ++ static const VkClearColorValue black = { { 0.0f, 0.0f, 0.0f, 1.0f } }; ++ pvkCmdClearColorImage(cb, s_vk.sc_images[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &black, 1, ++ &b.subresourceRange); ++ } + VkImageBlit blit = { + .srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, + .srcOffsets = { { 0, 0, 0 }, { (int32_t)s_vk.width, (int32_t)s_vk.height, 1 } }, + .dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, +- .dstOffsets = { { 0, 0, 0 }, +- { (int32_t)s_vk.sc_extent.width, (int32_t)s_vk.sc_extent.height, 1 } }, ++ .dstOffsets = { { (int32_t)fit.x, (int32_t)fit.y, 0 }, ++ { (int32_t)(fit.x + fit.w), (int32_t)(fit.y + fit.h), 1 } }, + }; + pvkCmdBlitImage(cb, s_vk.color.img, VK_IMAGE_LAYOUT_GENERAL, + s_vk.sc_images[idx], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, +@@ -4033,6 +4086,19 @@ int rsx_vulkan_backend_pump_messages(void) + while (SDL_PollEvent(&e)) { + if (e.type == SDL_QUIT) quit = 1; + else if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE) quit = 1; ++ else if (e.type == SDL_KEYDOWN && !e.key.repeat && s_vk.window && ++ (e.key.keysym.sym == SDLK_F11 || ++ (e.key.keysym.sym == SDLK_RETURN && (e.key.keysym.mod & KMOD_ALT)))) { ++ /* Borderless fullscreen on the window's display, and back. */ ++ const int full = (SDL_GetWindowFlags(s_vk.window) & SDL_WINDOW_FULLSCREEN_DESKTOP) != 0; ++ if (SDL_SetWindowFullscreen(s_vk.window, full ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP) == 0) ++ SDL_ShowCursor(full ? SDL_ENABLE : SDL_DISABLE); ++ s_vk_resized = 1; ++ } else if (e.type == SDL_WINDOWEVENT && ++ (e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED || e.window.event == SDL_WINDOWEVENT_RESTORED || ++ e.window.event == SDL_WINDOWEVENT_MAXIMIZED)) { ++ s_vk_resized = 1; ++ } + } + return quit ? -1 : 0; + } diff --git a/tasks/sp00nznet__ps3recomp-614/tests/test.sh b/tasks/sp00nznet__ps3recomp-614/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-614/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-614/tests/verifier.py b/tasks/sp00nznet__ps3recomp-614/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-614/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-616/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-616/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-616/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-616/instruction.md b/tasks/sp00nznet__ps3recomp-616/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ac840de43369dc1c0ccbb12bad25dcfb7a069ceb --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-616/instruction.md @@ -0,0 +1,54 @@ +# Issue + +**Title:** cellSysutilNpEula: provide cellSysutilNpEulaCheck legacy compatibility stub + +## Description + +## Why + +In commit `6404ecfe` ("cellSysutilNpEula: answer the PSN terms check through its callback"), the previous dummy function `cellSysutilNpEulaCheck` was replaced with the formal exports `sceNpEulaCheckEulaStatus`, `sceNpEulaAbort`, and `sceNpEulaShowCurrentEula`. + +However, existing game ports and recompiled binaries generated against previous versions of the `ps3recomp` runtime contain direct references to `cellSysutilNpEulaCheck` in their generated `ppu_hle_nids.cpp` or user PRX shims. When attempting to link against the updated runtime library `ps3recomp_runtime.lib`, the link step fails with: + +``` +lld-link: error: undefined symbol: cellSysutilNpEulaCheck +>>> referenced by ppu_hle_nids.cpp:482 +``` + +--- + +## Change + +- In `libs/system/cellSysutilNpEula.h` and `libs/system/cellSysutilNpEula.c`: + - Retain `cellSysutilNpEulaCheck(void* cb, void* arg)` as an exported backward-compatibility stub returning `1` (`CELL_OK` / accepted). + - Preserves binary and source compatibility for titles generated with earlier toolchain headers without conflicting with the new `sceNpEula*` subsystem. + +--- + +## Factual Citations & Hardware References + +1. **System Utility API Compatibility & HLE Shim Conventions:** + - In Cell OS Lv-2 HLE runtimes, deprecated or previously synthesized module symbols are aliased or retained as compatibility entry points to maintain backwards compatibility with existing recompiled game source trees and generated NID dispatch tables. + +--- + +## Evidence + +### Before vs. With this change + +| State | Linker / Runtime Result | +|---|---| +| Before (`6404ecfe`) | `lld-link: error: undefined symbol: cellSysutilNpEulaCheck` | +| With this change | Clean link and execution; stub logs acceptance and returns `1` (`CELL_OK`) | + +--- + +## AI Assistance & Clean-Room Compliance + +In accordance with upstream guidelines ([`CONTRIBUTORS.md#a-note-on-ai-assisted-contributions`](CONTRIBUTORS.md#a-note-on-ai-assisted-contributions)): +- Authored with AI assistance (Antigravity), directed and verified against link compatibility requirements. +- Clean-room implementation: trivial compatibility stub; zero code copied from RPCS3 or other GPL emulators. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-616/solution/patch.diff b/tasks/sp00nznet__ps3recomp-616/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ca8e54da948e5cf342b4b7b33948faa83ae84ec6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-616/solution/patch.diff @@ -0,0 +1,27 @@ +diff --git a/libs/system/cellSysutilNpEula.c b/libs/system/cellSysutilNpEula.c +index 73fd6a40..8839fc56 100644 +--- a/libs/system/cellSysutilNpEula.c ++++ b/libs/system/cellSysutilNpEula.c +@@ -122,3 +122,10 @@ void ps3_np_eula_tick(void) + if (kind == EULA_CHECK) + printf("[cellSysutilNpEula] callback status=%u delivered\n", status); + } ++ ++s32 cellSysutilNpEulaCheck(void* cb, void* arg) ++{ ++ (void)cb; (void)arg; ++ printf("[cellSysutilNpEula] cellSysutilNpEulaCheck (compat stub) -> accepted\n"); ++ return 1; ++} +diff --git a/libs/system/cellSysutilNpEula.h b/libs/system/cellSysutilNpEula.h +index 70546adf..17bb5c7a 100644 +--- a/libs/system/cellSysutilNpEula.h ++++ b/libs/system/cellSysutilNpEula.h +@@ -39,6 +39,7 @@ s32 sceNpEulaCheckEulaStatus(u32 communicationId, u32 arg2, u64 arg3, + s32 sceNpEulaAbort(void); /* NID 0x5EC05AD8 */ + s32 sceNpEulaShowCurrentEula(u32 communicationId, u64 arg2, + u32 cbFunc, u32 cbFuncArg); /* NID 0x6599500D */ ++s32 cellSysutilNpEulaCheck(void* cb, void* arg); /* Legacy compatibility stub */ + + /* Called by cellSysutilCheckCallback: moves a pending answer to the guest + * callback queue, which that same poll drains (RPCS3's sysutil_register_cb). */ diff --git a/tasks/sp00nznet__ps3recomp-616/solution/solve.sh b/tasks/sp00nznet__ps3recomp-616/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-616/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-616/task.toml b/tasks/sp00nznet__ps3recomp-616/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9e106b7704951dfd3bbdd284a398d490f1122ea5 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-616/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-616" +description = "cellSysutilNpEula: provide cellSysutilNpEulaCheck legacy compatibility stub" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/616" +source_access = "auto" +built_at = "2026-11-16T16:09:59.637061+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:be1e8b3b7dce90b2930d78a0ae387ec9f27c717fd62420ece60d78ce42dabd3f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "libs/system/cellSysutilNpEula.c", + "libs/system/cellSysutilNpEula.h", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.129988+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-616/tests/capture.py b/tasks/sp00nznet__ps3recomp-616/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-616/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-616/tests/instruction.md b/tasks/sp00nznet__ps3recomp-616/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ac840de43369dc1c0ccbb12bad25dcfb7a069ceb --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-616/tests/instruction.md @@ -0,0 +1,54 @@ +# Issue + +**Title:** cellSysutilNpEula: provide cellSysutilNpEulaCheck legacy compatibility stub + +## Description + +## Why + +In commit `6404ecfe` ("cellSysutilNpEula: answer the PSN terms check through its callback"), the previous dummy function `cellSysutilNpEulaCheck` was replaced with the formal exports `sceNpEulaCheckEulaStatus`, `sceNpEulaAbort`, and `sceNpEulaShowCurrentEula`. + +However, existing game ports and recompiled binaries generated against previous versions of the `ps3recomp` runtime contain direct references to `cellSysutilNpEulaCheck` in their generated `ppu_hle_nids.cpp` or user PRX shims. When attempting to link against the updated runtime library `ps3recomp_runtime.lib`, the link step fails with: + +``` +lld-link: error: undefined symbol: cellSysutilNpEulaCheck +>>> referenced by ppu_hle_nids.cpp:482 +``` + +--- + +## Change + +- In `libs/system/cellSysutilNpEula.h` and `libs/system/cellSysutilNpEula.c`: + - Retain `cellSysutilNpEulaCheck(void* cb, void* arg)` as an exported backward-compatibility stub returning `1` (`CELL_OK` / accepted). + - Preserves binary and source compatibility for titles generated with earlier toolchain headers without conflicting with the new `sceNpEula*` subsystem. + +--- + +## Factual Citations & Hardware References + +1. **System Utility API Compatibility & HLE Shim Conventions:** + - In Cell OS Lv-2 HLE runtimes, deprecated or previously synthesized module symbols are aliased or retained as compatibility entry points to maintain backwards compatibility with existing recompiled game source trees and generated NID dispatch tables. + +--- + +## Evidence + +### Before vs. With this change + +| State | Linker / Runtime Result | +|---|---| +| Before (`6404ecfe`) | `lld-link: error: undefined symbol: cellSysutilNpEulaCheck` | +| With this change | Clean link and execution; stub logs acceptance and returns `1` (`CELL_OK`) | + +--- + +## AI Assistance & Clean-Room Compliance + +In accordance with upstream guidelines ([`CONTRIBUTORS.md#a-note-on-ai-assisted-contributions`](CONTRIBUTORS.md#a-note-on-ai-assisted-contributions)): +- Authored with AI assistance (Antigravity), directed and verified against link compatibility requirements. +- Clean-room implementation: trivial compatibility stub; zero code copied from RPCS3 or other GPL emulators. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-616/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-616/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ca8e54da948e5cf342b4b7b33948faa83ae84ec6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-616/tests/oracle.patch @@ -0,0 +1,27 @@ +diff --git a/libs/system/cellSysutilNpEula.c b/libs/system/cellSysutilNpEula.c +index 73fd6a40..8839fc56 100644 +--- a/libs/system/cellSysutilNpEula.c ++++ b/libs/system/cellSysutilNpEula.c +@@ -122,3 +122,10 @@ void ps3_np_eula_tick(void) + if (kind == EULA_CHECK) + printf("[cellSysutilNpEula] callback status=%u delivered\n", status); + } ++ ++s32 cellSysutilNpEulaCheck(void* cb, void* arg) ++{ ++ (void)cb; (void)arg; ++ printf("[cellSysutilNpEula] cellSysutilNpEulaCheck (compat stub) -> accepted\n"); ++ return 1; ++} +diff --git a/libs/system/cellSysutilNpEula.h b/libs/system/cellSysutilNpEula.h +index 70546adf..17bb5c7a 100644 +--- a/libs/system/cellSysutilNpEula.h ++++ b/libs/system/cellSysutilNpEula.h +@@ -39,6 +39,7 @@ s32 sceNpEulaCheckEulaStatus(u32 communicationId, u32 arg2, u64 arg3, + s32 sceNpEulaAbort(void); /* NID 0x5EC05AD8 */ + s32 sceNpEulaShowCurrentEula(u32 communicationId, u64 arg2, + u32 cbFunc, u32 cbFuncArg); /* NID 0x6599500D */ ++s32 cellSysutilNpEulaCheck(void* cb, void* arg); /* Legacy compatibility stub */ + + /* Called by cellSysutilCheckCallback: moves a pending answer to the guest + * callback queue, which that same poll drains (RPCS3's sysutil_register_cb). */ diff --git a/tasks/sp00nznet__ps3recomp-616/tests/test.sh b/tasks/sp00nznet__ps3recomp-616/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-616/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-616/tests/verifier.py b/tasks/sp00nznet__ps3recomp-616/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-616/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-617/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-617/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-617/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-617/instruction.md b/tasks/sp00nznet__ps3recomp-617/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e776d2ad78df594ac4721a74f399f90158e8c164 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-617/instruction.md @@ -0,0 +1,58 @@ +# Issue + +**Title:** rsx_d3d12: implement upload_quad_strip_vp and support QUAD_STRIP and POLYGON primitives + +## Description + +## Why + +In `libs/video/rsx_d3d12_backend.c`, draw dispatches using primitive topologies `RSX_PRIMITIVE_QUAD_STRIP` (opcode `9`) and `RSX_PRIMITIVE_POLYGON` (opcode `10`) were completely unhandled in the Direct3D 12 vertex path. When encountered in either `d3d12_draw_arrays` or `d3d12_draw_indexed`, these draws were dropped with: + +``` +[D3D12] draw_indexed: skipping prim=9 (not wired) +[D3D12] draw_indexed: skipping prim=10 (not wired) +``` + +In titles utilizing quad strips for ribbon geometry (e.g. tire skid tracks, motion blur trails, roadway kerbs, and particle streamers) and convex polygons for HUD elements or shadow volume caps, this caused missing geometry, invisible surface details, or dropped particle effects. + +--- + +## Change + +- In `libs/video/rsx_d3d12_backend.c`: + - Implemented `upload_quad_strip_vp`: Assembles non-indexed quad strips into triangle lists. For each quad $q \in [0, (N-2)/2)$, emits two triangles $(v_{2q}, v_{2q+1}, v_{2q+3})$ and $(v_{2q}, v_{2q+3}, v_{2q+2})$ to preserve consistent vertex winding and face orientation. + - Implemented `upload_quad_strip_vp_indexed`: Evaluates guest indices via `read_guest_index` and expands into triangle list vertex buffers. + - Extended `d3d12_draw_arrays` and `d3d12_draw_indexed` to dispatch `RSX_PRIMITIVE_QUAD_STRIP` to `upload_quad_strip_vp` / `upload_quad_strip_vp_indexed`, and route `RSX_PRIMITIVE_POLYGON` to fan emulation (`upload_strip_vp` / `upload_strip_vp_indexed` with `fan = 1`). + +--- + +## Factual Citations & Hardware References + +1. **NVIDIA NV40 / G70 Hardware Primitive Assembly Specification:** + - *Reference:* [Khronos OpenGL 2.1 Specification, Section 2.6.1: "Primitive Types – Quad Strips & Polygons"](https://registry.khronos.org/OpenGL/specs/gl/glspec21.pdf) + - *Hardware Rule:* + - A quad strip with $2n+2$ vertices defines $n$ consecutive quadrilaterals. For quad $i$, the vertices are $2i, 2i+1, 2i+3, 2i+2$. In host Direct3D 12 (which natively lacks quad topologies), this decomposes into triangles $(2i, 2i+1, 2i+3)$ and $(2i, 2i+3, 2i+2)$. + - A polygon with $n$ vertices is a convex polygon assembled identically to a triangle fan: $(0, 1, 2), (0, 2, 3), \dots, (0, n-2, n-1)$. + +--- + +## Evidence + +### Before vs. With this change + +| Primitive Opcode | Before | With this change | +|---|---|---| +| `RSX_PRIMITIVE_QUAD_STRIP` (9) | Dropped (`skipping prim=9 (not wired)`) | Assembled into triangle list with correct winding | +| `RSX_PRIMITIVE_POLYGON` (10) | Dropped (`skipping prim=10 (not wired)`) | Dispatched to fan emulation (`fan = 1`) | + +--- + +## AI Assistance & Clean-Room Compliance + +In accordance with upstream guidelines ([`CONTRIBUTORS.md#a-note-on-ai-assisted-contributions`](CONTRIBUTORS.md#a-note-on-ai-assisted-contributions)): +- Authored with AI assistance (Antigravity), directed and verified against Khronos OpenGL 2.1 / NV40 primitive assembly specifications. +- Clean-room implementation: independent vertex assembly algorithms written directly from hardware topology definitions; zero code copied or adapted from RPCS3 or other GPL emulators. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-617/solution/patch.diff b/tasks/sp00nznet__ps3recomp-617/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d788cb0e59bb0c0cdcf7a6ee2cc8fff4d618bd34 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-617/solution/patch.diff @@ -0,0 +1,115 @@ +diff --git a/libs/video/rsx_d3d12_backend.c b/libs/video/rsx_d3d12_backend.c +index bc05a308..52320d88 100644 +--- a/libs/video/rsx_d3d12_backend.c ++++ b/libs/video/rsx_d3d12_backend.c +@@ -6624,6 +6624,37 @@ static u32 upload_strip_vp(const rsx_state* state, u32 first, u32 count, int fan + return o; + } + ++static u32 upload_quad_strip_vp(const rsx_state* state, u32 first, u32 count) ++{ ++ extern uint8_t* vm_base; ++ if (!state || !vm_base || !s_d3d.vp_vb_mapped) return 0; ++ if (!state->vertex_attribs[0].enabled) return 0; ++ if (count < 4) return 0; ++ u32 quads = (count - 2) / 2; ++ u32 maxv = (MAX_VERTICES * VP_VERT_STRIDE - s_d3d.vp_vb_offset) / VP_VERT_STRIDE; ++ if (quads * 6 > maxv) quads = maxv / 6; ++ VPSlot* out = (VPSlot*)((u8*)s_d3d.vp_vb_mapped ++ + (u64)s_d3d.vp_parity * MAX_VERTICES * VP_VERT_STRIDE + s_d3d.vp_vb_offset); ++ u32 o = 0; ++ for (u32 q = 0; q < quads; q++) { ++ u32 b = first + q * 2; ++ VPSlot v0[16], v1[16], v2[16], v3[16]; ++ read_vp_vertex(state, b + 0, v0); ++ read_vp_vertex(state, b + 1, v1); ++ read_vp_vertex(state, b + 2, v2); ++ read_vp_vertex(state, b + 3, v3); ++ memcpy(&out[(o + 0)*16], v0, sizeof(v0)); ++ memcpy(&out[(o + 1)*16], v1, sizeof(v1)); ++ memcpy(&out[(o + 2)*16], v3, sizeof(v3)); ++ memcpy(&out[(o + 3)*16], v0, sizeof(v0)); ++ memcpy(&out[(o + 4)*16], v3, sizeof(v3)); ++ memcpy(&out[(o + 5)*16], v2, sizeof(v2)); ++ o += 6; ++ } ++ s_d3d.vp_vb_offset += o * VP_VERT_STRIDE; ++ return o; ++} ++ + /* Fetch index k from the guest index array (SET_INDEX_ARRAY_ADDRESS/_DMA: + * dma [3:0] = location (0 local, 1 main), [7:4] = type (0 u32, 1 u16)). + * Indices are big-endian in guest memory. */ +@@ -7014,6 +7045,37 @@ static u32 upload_strip_vp_indexed(const rsx_state* state, u32 first, u32 count, + return o; + } + ++static u32 upload_quad_strip_vp_indexed(const rsx_state* state, u32 first, u32 count) ++{ ++ extern uint8_t* vm_base; ++ if (!state || !vm_base || !s_d3d.vp_vb_mapped) return 0; ++ if (!state->vertex_attribs[0].enabled) return 0; ++ if (count < 4) return 0; ++ u32 quads = (count - 2) / 2; ++ u32 maxv = (MAX_VERTICES * VP_VERT_STRIDE - s_d3d.vp_vb_offset) / VP_VERT_STRIDE; ++ if (quads * 6 > maxv) quads = maxv / 6; ++ VPSlot* out = (VPSlot*)((u8*)s_d3d.vp_vb_mapped ++ + (u64)s_d3d.vp_parity * MAX_VERTICES * VP_VERT_STRIDE + s_d3d.vp_vb_offset); ++ u32 o = 0; ++ for (u32 q = 0; q < quads; q++) { ++ u32 b = first + q * 2; ++ VPSlot v0[16], v1[16], v2[16], v3[16]; ++ read_vp_vertex(state, read_guest_index(state, b + 0), v0); ++ read_vp_vertex(state, read_guest_index(state, b + 1), v1); ++ read_vp_vertex(state, read_guest_index(state, b + 2), v2); ++ read_vp_vertex(state, read_guest_index(state, b + 3), v3); ++ memcpy(&out[(o + 0)*16], v0, sizeof(v0)); ++ memcpy(&out[(o + 1)*16], v1, sizeof(v1)); ++ memcpy(&out[(o + 2)*16], v3, sizeof(v3)); ++ memcpy(&out[(o + 3)*16], v0, sizeof(v0)); ++ memcpy(&out[(o + 4)*16], v3, sizeof(v3)); ++ memcpy(&out[(o + 5)*16], v2, sizeof(v2)); ++ o += 6; ++ } ++ s_d3d.vp_vb_offset += o * VP_VERT_STRIDE; ++ return o; ++} ++ + static void d3d12_draw_arrays(void* ud, u32 primitive, u32 first, u32 count) + { + /* RSX_LIVE_FEED_DBG=1: pair with the [feed] method counts so "the FIFO +@@ -7141,13 +7203,19 @@ static void d3d12_draw_arrays(void* ud, u32 primitive, u32 first, u32 count) + * Geometry already in clip space with no VP -- flOw's injected scene -- must + * go down the fixed-function passthrough below instead. */ + if ((primitive == RSX_PRIMITIVE_TRIANGLES || primitive == RSX_PRIMITIVE_TRIANGLE_STRIP +- || primitive == RSX_PRIMITIVE_TRIANGLE_FAN) && ++ || primitive == RSX_PRIMITIVE_TRIANGLE_FAN || primitive == RSX_PRIMITIVE_POLYGON ++ || primitive == RSX_PRIMITIVE_QUAD_STRIP) && + s_d3d.vp_vb_mapped && s_d3d.vp_root_sig && + s_d3d.current_rsx_state && s_d3d.current_rsx_state->vp_ucode_bytes >= 16) { + u32 rec = s_d3d.vp_vb_offset; +- u32 emitted = (primitive == RSX_PRIMITIVE_TRIANGLES) +- ? upload_tris_vp(s_d3d.current_rsx_state, first, count) +- : upload_strip_vp(s_d3d.current_rsx_state, first, count, primitive == RSX_PRIMITIVE_TRIANGLE_FAN); ++ u32 emitted = 0; ++ if (primitive == RSX_PRIMITIVE_TRIANGLES) ++ emitted = upload_tris_vp(s_d3d.current_rsx_state, first, count); ++ else if (primitive == RSX_PRIMITIVE_QUAD_STRIP) ++ emitted = upload_quad_strip_vp(s_d3d.current_rsx_state, first, count); ++ else ++ emitted = upload_strip_vp(s_d3d.current_rsx_state, first, count, ++ primitive == RSX_PRIMITIVE_TRIANGLE_FAN || primitive == RSX_PRIMITIVE_POLYGON); + /* RSX splits one primitive stream across several DRAW_ARRAYS entries + * inside a single BEGIN/END (each carries at most 256 vertices), and the + * hardware concatenates them before assembling primitives. Recording a +@@ -7299,7 +7367,9 @@ static void d3d12_draw_indexed(void* ud, u32 primitive, u32 first, u32 count) + else if (primitive == RSX_PRIMITIVE_QUADS) emitted = upload_quads_vp_indexed(s_d3d.current_rsx_state, first, count); + else if (primitive == RSX_PRIMITIVE_TRIANGLES) emitted = upload_tris_vp_indexed(s_d3d.current_rsx_state, first, count); + else if (primitive == RSX_PRIMITIVE_TRIANGLE_STRIP) emitted = upload_strip_vp_indexed(s_d3d.current_rsx_state, first, count, 0); +- else if (primitive == RSX_PRIMITIVE_TRIANGLE_FAN) emitted = upload_strip_vp_indexed(s_d3d.current_rsx_state, first, count, 1); ++ else if (primitive == RSX_PRIMITIVE_TRIANGLE_FAN || ++ primitive == RSX_PRIMITIVE_POLYGON) emitted = upload_strip_vp_indexed(s_d3d.current_rsx_state, first, count, 1); ++ else if (primitive == RSX_PRIMITIVE_QUAD_STRIP) emitted = upload_quad_strip_vp_indexed(s_d3d.current_rsx_state, first, count); + else { + static int _skip = 0; + if (PS3_LOG_FIRST(_skip, 3)) diff --git a/tasks/sp00nznet__ps3recomp-617/solution/solve.sh b/tasks/sp00nznet__ps3recomp-617/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-617/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-617/task.toml b/tasks/sp00nznet__ps3recomp-617/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3c5486b3ba75da15b940c11487b6b78d7435b7cc --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-617/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-617" +description = "rsx_d3d12: implement upload_quad_strip_vp and support QUAD_STRIP and POLYGON primitives" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/617" +source_access = "auto" +built_at = "2026-11-16T16:09:59.676257+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:646f713eb1e0e4ed0935b1e02b1fdcda335481073f26a3d3ef6fb079f869a4ed" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "libs/video/rsx_d3d12_backend.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 80 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.130668+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-617/tests/capture.py b/tasks/sp00nznet__ps3recomp-617/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-617/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-617/tests/instruction.md b/tasks/sp00nznet__ps3recomp-617/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e776d2ad78df594ac4721a74f399f90158e8c164 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-617/tests/instruction.md @@ -0,0 +1,58 @@ +# Issue + +**Title:** rsx_d3d12: implement upload_quad_strip_vp and support QUAD_STRIP and POLYGON primitives + +## Description + +## Why + +In `libs/video/rsx_d3d12_backend.c`, draw dispatches using primitive topologies `RSX_PRIMITIVE_QUAD_STRIP` (opcode `9`) and `RSX_PRIMITIVE_POLYGON` (opcode `10`) were completely unhandled in the Direct3D 12 vertex path. When encountered in either `d3d12_draw_arrays` or `d3d12_draw_indexed`, these draws were dropped with: + +``` +[D3D12] draw_indexed: skipping prim=9 (not wired) +[D3D12] draw_indexed: skipping prim=10 (not wired) +``` + +In titles utilizing quad strips for ribbon geometry (e.g. tire skid tracks, motion blur trails, roadway kerbs, and particle streamers) and convex polygons for HUD elements or shadow volume caps, this caused missing geometry, invisible surface details, or dropped particle effects. + +--- + +## Change + +- In `libs/video/rsx_d3d12_backend.c`: + - Implemented `upload_quad_strip_vp`: Assembles non-indexed quad strips into triangle lists. For each quad $q \in [0, (N-2)/2)$, emits two triangles $(v_{2q}, v_{2q+1}, v_{2q+3})$ and $(v_{2q}, v_{2q+3}, v_{2q+2})$ to preserve consistent vertex winding and face orientation. + - Implemented `upload_quad_strip_vp_indexed`: Evaluates guest indices via `read_guest_index` and expands into triangle list vertex buffers. + - Extended `d3d12_draw_arrays` and `d3d12_draw_indexed` to dispatch `RSX_PRIMITIVE_QUAD_STRIP` to `upload_quad_strip_vp` / `upload_quad_strip_vp_indexed`, and route `RSX_PRIMITIVE_POLYGON` to fan emulation (`upload_strip_vp` / `upload_strip_vp_indexed` with `fan = 1`). + +--- + +## Factual Citations & Hardware References + +1. **NVIDIA NV40 / G70 Hardware Primitive Assembly Specification:** + - *Reference:* [Khronos OpenGL 2.1 Specification, Section 2.6.1: "Primitive Types – Quad Strips & Polygons"](https://registry.khronos.org/OpenGL/specs/gl/glspec21.pdf) + - *Hardware Rule:* + - A quad strip with $2n+2$ vertices defines $n$ consecutive quadrilaterals. For quad $i$, the vertices are $2i, 2i+1, 2i+3, 2i+2$. In host Direct3D 12 (which natively lacks quad topologies), this decomposes into triangles $(2i, 2i+1, 2i+3)$ and $(2i, 2i+3, 2i+2)$. + - A polygon with $n$ vertices is a convex polygon assembled identically to a triangle fan: $(0, 1, 2), (0, 2, 3), \dots, (0, n-2, n-1)$. + +--- + +## Evidence + +### Before vs. With this change + +| Primitive Opcode | Before | With this change | +|---|---|---| +| `RSX_PRIMITIVE_QUAD_STRIP` (9) | Dropped (`skipping prim=9 (not wired)`) | Assembled into triangle list with correct winding | +| `RSX_PRIMITIVE_POLYGON` (10) | Dropped (`skipping prim=10 (not wired)`) | Dispatched to fan emulation (`fan = 1`) | + +--- + +## AI Assistance & Clean-Room Compliance + +In accordance with upstream guidelines ([`CONTRIBUTORS.md#a-note-on-ai-assisted-contributions`](CONTRIBUTORS.md#a-note-on-ai-assisted-contributions)): +- Authored with AI assistance (Antigravity), directed and verified against Khronos OpenGL 2.1 / NV40 primitive assembly specifications. +- Clean-room implementation: independent vertex assembly algorithms written directly from hardware topology definitions; zero code copied or adapted from RPCS3 or other GPL emulators. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-617/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-617/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d788cb0e59bb0c0cdcf7a6ee2cc8fff4d618bd34 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-617/tests/oracle.patch @@ -0,0 +1,115 @@ +diff --git a/libs/video/rsx_d3d12_backend.c b/libs/video/rsx_d3d12_backend.c +index bc05a308..52320d88 100644 +--- a/libs/video/rsx_d3d12_backend.c ++++ b/libs/video/rsx_d3d12_backend.c +@@ -6624,6 +6624,37 @@ static u32 upload_strip_vp(const rsx_state* state, u32 first, u32 count, int fan + return o; + } + ++static u32 upload_quad_strip_vp(const rsx_state* state, u32 first, u32 count) ++{ ++ extern uint8_t* vm_base; ++ if (!state || !vm_base || !s_d3d.vp_vb_mapped) return 0; ++ if (!state->vertex_attribs[0].enabled) return 0; ++ if (count < 4) return 0; ++ u32 quads = (count - 2) / 2; ++ u32 maxv = (MAX_VERTICES * VP_VERT_STRIDE - s_d3d.vp_vb_offset) / VP_VERT_STRIDE; ++ if (quads * 6 > maxv) quads = maxv / 6; ++ VPSlot* out = (VPSlot*)((u8*)s_d3d.vp_vb_mapped ++ + (u64)s_d3d.vp_parity * MAX_VERTICES * VP_VERT_STRIDE + s_d3d.vp_vb_offset); ++ u32 o = 0; ++ for (u32 q = 0; q < quads; q++) { ++ u32 b = first + q * 2; ++ VPSlot v0[16], v1[16], v2[16], v3[16]; ++ read_vp_vertex(state, b + 0, v0); ++ read_vp_vertex(state, b + 1, v1); ++ read_vp_vertex(state, b + 2, v2); ++ read_vp_vertex(state, b + 3, v3); ++ memcpy(&out[(o + 0)*16], v0, sizeof(v0)); ++ memcpy(&out[(o + 1)*16], v1, sizeof(v1)); ++ memcpy(&out[(o + 2)*16], v3, sizeof(v3)); ++ memcpy(&out[(o + 3)*16], v0, sizeof(v0)); ++ memcpy(&out[(o + 4)*16], v3, sizeof(v3)); ++ memcpy(&out[(o + 5)*16], v2, sizeof(v2)); ++ o += 6; ++ } ++ s_d3d.vp_vb_offset += o * VP_VERT_STRIDE; ++ return o; ++} ++ + /* Fetch index k from the guest index array (SET_INDEX_ARRAY_ADDRESS/_DMA: + * dma [3:0] = location (0 local, 1 main), [7:4] = type (0 u32, 1 u16)). + * Indices are big-endian in guest memory. */ +@@ -7014,6 +7045,37 @@ static u32 upload_strip_vp_indexed(const rsx_state* state, u32 first, u32 count, + return o; + } + ++static u32 upload_quad_strip_vp_indexed(const rsx_state* state, u32 first, u32 count) ++{ ++ extern uint8_t* vm_base; ++ if (!state || !vm_base || !s_d3d.vp_vb_mapped) return 0; ++ if (!state->vertex_attribs[0].enabled) return 0; ++ if (count < 4) return 0; ++ u32 quads = (count - 2) / 2; ++ u32 maxv = (MAX_VERTICES * VP_VERT_STRIDE - s_d3d.vp_vb_offset) / VP_VERT_STRIDE; ++ if (quads * 6 > maxv) quads = maxv / 6; ++ VPSlot* out = (VPSlot*)((u8*)s_d3d.vp_vb_mapped ++ + (u64)s_d3d.vp_parity * MAX_VERTICES * VP_VERT_STRIDE + s_d3d.vp_vb_offset); ++ u32 o = 0; ++ for (u32 q = 0; q < quads; q++) { ++ u32 b = first + q * 2; ++ VPSlot v0[16], v1[16], v2[16], v3[16]; ++ read_vp_vertex(state, read_guest_index(state, b + 0), v0); ++ read_vp_vertex(state, read_guest_index(state, b + 1), v1); ++ read_vp_vertex(state, read_guest_index(state, b + 2), v2); ++ read_vp_vertex(state, read_guest_index(state, b + 3), v3); ++ memcpy(&out[(o + 0)*16], v0, sizeof(v0)); ++ memcpy(&out[(o + 1)*16], v1, sizeof(v1)); ++ memcpy(&out[(o + 2)*16], v3, sizeof(v3)); ++ memcpy(&out[(o + 3)*16], v0, sizeof(v0)); ++ memcpy(&out[(o + 4)*16], v3, sizeof(v3)); ++ memcpy(&out[(o + 5)*16], v2, sizeof(v2)); ++ o += 6; ++ } ++ s_d3d.vp_vb_offset += o * VP_VERT_STRIDE; ++ return o; ++} ++ + static void d3d12_draw_arrays(void* ud, u32 primitive, u32 first, u32 count) + { + /* RSX_LIVE_FEED_DBG=1: pair with the [feed] method counts so "the FIFO +@@ -7141,13 +7203,19 @@ static void d3d12_draw_arrays(void* ud, u32 primitive, u32 first, u32 count) + * Geometry already in clip space with no VP -- flOw's injected scene -- must + * go down the fixed-function passthrough below instead. */ + if ((primitive == RSX_PRIMITIVE_TRIANGLES || primitive == RSX_PRIMITIVE_TRIANGLE_STRIP +- || primitive == RSX_PRIMITIVE_TRIANGLE_FAN) && ++ || primitive == RSX_PRIMITIVE_TRIANGLE_FAN || primitive == RSX_PRIMITIVE_POLYGON ++ || primitive == RSX_PRIMITIVE_QUAD_STRIP) && + s_d3d.vp_vb_mapped && s_d3d.vp_root_sig && + s_d3d.current_rsx_state && s_d3d.current_rsx_state->vp_ucode_bytes >= 16) { + u32 rec = s_d3d.vp_vb_offset; +- u32 emitted = (primitive == RSX_PRIMITIVE_TRIANGLES) +- ? upload_tris_vp(s_d3d.current_rsx_state, first, count) +- : upload_strip_vp(s_d3d.current_rsx_state, first, count, primitive == RSX_PRIMITIVE_TRIANGLE_FAN); ++ u32 emitted = 0; ++ if (primitive == RSX_PRIMITIVE_TRIANGLES) ++ emitted = upload_tris_vp(s_d3d.current_rsx_state, first, count); ++ else if (primitive == RSX_PRIMITIVE_QUAD_STRIP) ++ emitted = upload_quad_strip_vp(s_d3d.current_rsx_state, first, count); ++ else ++ emitted = upload_strip_vp(s_d3d.current_rsx_state, first, count, ++ primitive == RSX_PRIMITIVE_TRIANGLE_FAN || primitive == RSX_PRIMITIVE_POLYGON); + /* RSX splits one primitive stream across several DRAW_ARRAYS entries + * inside a single BEGIN/END (each carries at most 256 vertices), and the + * hardware concatenates them before assembling primitives. Recording a +@@ -7299,7 +7367,9 @@ static void d3d12_draw_indexed(void* ud, u32 primitive, u32 first, u32 count) + else if (primitive == RSX_PRIMITIVE_QUADS) emitted = upload_quads_vp_indexed(s_d3d.current_rsx_state, first, count); + else if (primitive == RSX_PRIMITIVE_TRIANGLES) emitted = upload_tris_vp_indexed(s_d3d.current_rsx_state, first, count); + else if (primitive == RSX_PRIMITIVE_TRIANGLE_STRIP) emitted = upload_strip_vp_indexed(s_d3d.current_rsx_state, first, count, 0); +- else if (primitive == RSX_PRIMITIVE_TRIANGLE_FAN) emitted = upload_strip_vp_indexed(s_d3d.current_rsx_state, first, count, 1); ++ else if (primitive == RSX_PRIMITIVE_TRIANGLE_FAN || ++ primitive == RSX_PRIMITIVE_POLYGON) emitted = upload_strip_vp_indexed(s_d3d.current_rsx_state, first, count, 1); ++ else if (primitive == RSX_PRIMITIVE_QUAD_STRIP) emitted = upload_quad_strip_vp_indexed(s_d3d.current_rsx_state, first, count); + else { + static int _skip = 0; + if (PS3_LOG_FIRST(_skip, 3)) diff --git a/tasks/sp00nznet__ps3recomp-617/tests/test.sh b/tasks/sp00nznet__ps3recomp-617/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-617/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-617/tests/verifier.py b/tasks/sp00nznet__ps3recomp-617/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-617/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-618/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-618/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-618/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-618/instruction.md b/tasks/sp00nznet__ps3recomp-618/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0391acbce8e7722eb70ba98b435f02928e048365 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-618/instruction.md @@ -0,0 +1,52 @@ +# Issue + +**Title:** rsx_d3d12: apply unnormalized texture scaling in fragment program PSO pipeline + +## Description + +## Why + +In the RSX Reality Synthesizer (and NV40 hardware), textures can be sampled with unnormalized texel coordinates $[0, w) \times [0, h)$ indicated by bit 6 (`0x40`) of the texture format word (`NV4097_SET_TEXTURE_FORMAT`). This addressing mode is frequently used for rectangular lookups, post-processing kernel taps, procedural font glyphs, and screen-space blits. + +Direct3D 12 and HLSL `Texture2D.Sample()` only support normalized UV coordinates $[0.0, 1.0]$. In the `rsx_d3d12_backend.c` vertex-program pipeline, texture format bit `0x40` was never tracked or converted. As a result, fragment programs sampling unnormalized textures were passed integer texel indices directly into `Texture2D.Sample()`. Because indices exceeded $1.0$, texture addressing clamped or wrapped to borders, causing blown-out or completely black sampled textures in post-processing passes. + +--- + +## Change + +- In `libs/video/rsx_d3d12_backend.c`: + - **`dr_unnorm_units`**: Introduced helper extracting the bitmask of texture units with `fmt & 0x40` along with their $\{w, h, 1\}$ dimensions. + - **`VPFPEntry` Pipeline Cache Keys**: Extended the PSO cache struct `VPFPEntry` to store `unnorm_mask` and `unnorm_dim[16][3]`. Pipeline cache lookups now check `unnorm_mask` and dimensions to ensure specialized shaders are never aliased with normalized shaders. + - **Shader Specialization via `rsx_fp_apply_unnorm_scale`**: Wired `rsx_fp_apply_unnorm_scale` into `vp_get_fp_pso` so coordinates for unnormalized units are scaled by $(1.0 / w, 1.0 / h)$ prior to shader compilation. + - **Pre-pass and Draw Binding**: Updated `render_frame` pre-pass and per-draw PSO invocations to calculate `unnorm_mask` and pass it to `vp_get_fp_pso`. + +--- + +## Factual Citations & Hardware References + +1. **NVIDIA NV40 Architecture – Unnormalized Texture Coordinate Addressing:** + - *Reference:* [Khronos OpenGL ARB_texture_rectangle Extension Specification](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_texture_rectangle.txt) + - *Hardware Semantics:* On NV40/RSX hardware, textures configured with unnormalized coordinates (`0x40`) interpret $(s, t)$ in integer texel space $[0, w) \times [0, h)$. In host APIs without hardware rectangle samplers (such as D3D12 `Texture2D`), shader coordinates must be divided by $(w, h)$ to convert into standard normalized $[0, 1]$ coordinates. + +--- + +## Evidence + +### Before vs. With this change + +| Scenario | Before | With this change | +|---|---|---| +| Textures with format bit `0x40` | Integer coordinates passed directly to D3D12 `Sample()` -> clamped/black | Scaled by $(1/w, 1/h)$ via `rsx_fp_apply_unnorm_scale` -> sampled accurately | +| Pipeline Cache Key | Unnorm state ignored -> wrong PSO reused across passes | Keyed on `unnorm_mask` and dimensions in `VPFPEntry` | + +--- + +## AI Assistance & Clean-Room Compliance + +In accordance with upstream guidelines ([`CONTRIBUTORS.md#a-note-on-ai-assisted-contributions`](CONTRIBUTORS.md#a-note-on-ai-assisted-contributions)): +- Authored with AI assistance (Antigravity), directed and verified against NV40 texture addressing specifications and runtime shader telemetry. +- Clean-room implementation: independent coordinate scaling integration; zero code copied or adapted from RPCS3 or other GPL emulators. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-618/solution/patch.diff b/tasks/sp00nznet__ps3recomp-618/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e13f6b00a1051dcef74b31c40a9b258f02ac260a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-618/solution/patch.diff @@ -0,0 +1,107 @@ +diff --git a/libs/video/rsx_d3d12_backend.c b/libs/video/rsx_d3d12_backend.c +index bc05a308..4a5787dc 100644 +--- a/libs/video/rsx_d3d12_backend.c ++++ b/libs/video/rsx_d3d12_backend.c +@@ -260,6 +260,8 @@ typedef struct { + * declares those samplers as TextureCube, so a cube + * and a 2D variant of the same program are different + * pipelines and must not share a cache entry. */ ++ u32 unnorm_mask; /* unnormalized textures mask (PSO key) */ ++ u32 unnorm_dim[16][3]; /* unnormalized dimensions for scaling */ + u64 zs; /* depth/stencil state, rsx_zs_key (PSO key) */ + ID3D12PipelineState* pso; + } VPFPEntry; +@@ -2324,9 +2326,25 @@ static u32 dr_cube_mask(const D3D12DrawRecord* dr) + return m; + } + ++/* Which of a draw's texture units use unnormalized coordinates, with dimensions. */ ++static u32 dr_unnorm_units(const D3D12DrawRecord* dr, u32 dim[16][3]) ++{ ++ u32 mask = 0; ++ for (int u = 0; u < (int)(sizeof(dr->tex) / sizeof(dr->tex[0])); u++) { ++ dim[u][0] = dim[u][1] = dim[u][2] = 0; ++ if (!dr->tex[u].set || !(dr->tex[u].fmt & 0x40) || !dr->tex[u].w || !dr->tex[u].h) ++ continue; ++ mask |= 1u << u; ++ dim[u][0] = dr->tex[u].w; ++ dim[u][1] = dr->tex[u].h; ++ dim[u][2] = 1; ++ } ++ return mask; ++} ++ + static ID3D12PipelineState* vp_get_fp_pso(int vs_idx, u32 fp_addr, u32 blend, int nrt, + DXGI_FORMAT rtfmt, u32 ctrl, u32 cmask, u32 cull, +- u32 cube_mask, u64 zs) ++ u32 cube_mask, u32 unnorm_mask, const u32 unnorm_dim[16][3], u64 zs) + { + if (nrt < 0) nrt = 0; if (nrt > 4) nrt = 4; /* 0: a depth-only pass */ + if (rtfmt == 0) rtfmt = DXGI_FORMAT_R8G8B8A8_UNORM; +@@ -2385,7 +2403,9 @@ static ID3D12PipelineState* vp_get_fp_pso(int vs_idx, u32 fp_addr, u32 blend, in + s_d3d.vp_fp[i].rtfmt == (u32)rtfmt && s_d3d.vp_fp[i].ctrl == ctrl && + s_d3d.vp_fp[i].ucode_hash == uhash && s_d3d.vp_fp[i].cmask == cmask && + s_d3d.vp_fp[i].cull == cull && +- s_d3d.vp_fp[i].cube_mask == cube_mask && s_d3d.vp_fp[i].zs == zs) ++ s_d3d.vp_fp[i].cube_mask == cube_mask && s_d3d.vp_fp[i].zs == zs && ++ s_d3d.vp_fp[i].unnorm_mask == unnorm_mask && ++ (!unnorm_mask || memcmp(s_d3d.vp_fp[i].unnorm_dim, unnorm_dim, sizeof(s_d3d.vp_fp[i].unnorm_dim)) == 0)) + return s_d3d.vp_fp[i].pso; + s_perf_pso_miss++; /* falls through to a full decompile + D3DCompile */ + /* PSOMISSDBG=1: on a miss, name the key field that differs from an existing +@@ -2451,6 +2471,9 @@ static ID3D12PipelineState* vp_get_fp_pso(int vs_idx, u32 fp_addr, u32 blend, in + u32 fp_ctrl = ctrl_auto ? RSX_FP_CTRL_AUTO : ctrl; + int n = rsx_fp_decompile(vm_base + off, 4096, fp_ctrl, hlsl, sizeof(hlsl)); + if (n <= 0) { static int _e=0; if(PS3_LOG_FIRST(_e, 16)) printf("[FP] decompile fail (fp=0x%08X)\n", fp_addr); return NULL; } ++ if (unnorm_mask) { ++ rsx_fp_apply_unnorm_scale(hlsl, sizeof(hlsl), unnorm_mask, (const u32 (*)[3])unnorm_dim, cube_mask, 0); ++ } + /* FP_LIST=1: every program the title actually compiles, with its size. A + * fragment program that hangs the GPU shows up here as an implausible + * instruction count long before it shows up as a TDR. */ +@@ -2782,6 +2805,11 @@ static ID3D12PipelineState* vp_get_fp_pso(int vs_idx, u32 fp_addr, u32 blend, in + s_d3d.vp_fp[s_d3d.vp_fp_n].cmask = cmask; + s_d3d.vp_fp[s_d3d.vp_fp_n].cull = cull; + s_d3d.vp_fp[s_d3d.vp_fp_n].cube_mask = cube_mask; ++ s_d3d.vp_fp[s_d3d.vp_fp_n].unnorm_mask = unnorm_mask; ++ if (unnorm_mask) ++ memcpy(s_d3d.vp_fp[s_d3d.vp_fp_n].unnorm_dim, unnorm_dim, sizeof(s_d3d.vp_fp[s_d3d.vp_fp_n].unnorm_dim)); ++ else ++ memset(s_d3d.vp_fp[s_d3d.vp_fp_n].unnorm_dim, 0, sizeof(s_d3d.vp_fp[s_d3d.vp_fp_n].unnorm_dim)); + s_d3d.vp_fp[s_d3d.vp_fp_n].zs = zs; + s_d3d.vp_fp[s_d3d.vp_fp_n].pso = pso; + s_d3d.vp_fp_n++; +@@ -4913,12 +4941,14 @@ static void render_frame(void) + } + if (perf_on()) s_perf_srv += perf_now() - _sv0; + double _ps0 = perf_on() ? perf_now() : 0.0; ++ u32 unnorm_dim[16][3]; ++ u32 unnorm_mask = dr_unnorm_units(dr, unnorm_dim); + if (dr->fp_addr) vp_get_fp_pso(dr->vs_idx, dr->fp_addr, dr->blend_key, + dr_num_rts(dr), + dr->rt_off ? rsx_surface_dxgi(dr->rt_fmt) + : DXGI_FORMAT_R8G8B8A8_UNORM, + dr->fp_ctrl, dr->cmask, dr->cull, dr_cube_mask(dr), +- dr->zs_key); ++ unnorm_mask, unnorm_dim, dr->zs_key); + if (perf_on()) s_perf_pso += perf_now() - _ps0; + } + +@@ -5294,13 +5324,16 @@ static void render_frame(void) + } + /* Per-draw pipeline: prefer the guest's own compiled FP; fall + * back to the hardcoded atlas/colour PS pair. */ ++ u32 unnorm_dim[16][3]; ++ u32 unnorm_mask = dr_unnorm_units(dr, unnorm_dim); + ID3D12PipelineState* dpso = + dr->fp_addr ? vp_get_fp_pso(dr->vs_idx, dr->fp_addr, dr->blend_key, + dr_num_rts(dr), + dr->rt_off ? rsx_surface_dxgi(dr->rt_fmt) + : DXGI_FORMAT_R8G8B8A8_UNORM, + dr->fp_ctrl, dr->cmask, dr->cull, +- dr_cube_mask(dr), dr->zs_key) : NULL; ++ dr_cube_mask(dr), ++ unnorm_mask, unnorm_dim, dr->zs_key) : NULL; + s_d3d.cmd_list->lpVtbl->SetPipelineState(s_d3d.cmd_list, + dpso ? dpso : vpso); + s_d3d.cmd_list->lpVtbl->OMSetStencilRef(s_d3d.cmd_list, dr->stencil_ref & 0xFFu); diff --git a/tasks/sp00nznet__ps3recomp-618/solution/solve.sh b/tasks/sp00nznet__ps3recomp-618/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-618/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-618/task.toml b/tasks/sp00nznet__ps3recomp-618/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9663fa57b7017225004089be858c00cbc4988d3b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-618/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-618" +description = "rsx_d3d12: apply unnormalized texture scaling in fragment program PSO pipeline" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/618" +source_access = "auto" +built_at = "2026-11-16T16:09:59.674067+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:eb0c53fa1b8fd85f3ad86e0a74775865ff395cefc5bb8ea387b13d95c0314115" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "libs/video/rsx_d3d12_backend.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 41 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.131372+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-618/tests/capture.py b/tasks/sp00nznet__ps3recomp-618/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-618/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-618/tests/instruction.md b/tasks/sp00nznet__ps3recomp-618/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0391acbce8e7722eb70ba98b435f02928e048365 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-618/tests/instruction.md @@ -0,0 +1,52 @@ +# Issue + +**Title:** rsx_d3d12: apply unnormalized texture scaling in fragment program PSO pipeline + +## Description + +## Why + +In the RSX Reality Synthesizer (and NV40 hardware), textures can be sampled with unnormalized texel coordinates $[0, w) \times [0, h)$ indicated by bit 6 (`0x40`) of the texture format word (`NV4097_SET_TEXTURE_FORMAT`). This addressing mode is frequently used for rectangular lookups, post-processing kernel taps, procedural font glyphs, and screen-space blits. + +Direct3D 12 and HLSL `Texture2D.Sample()` only support normalized UV coordinates $[0.0, 1.0]$. In the `rsx_d3d12_backend.c` vertex-program pipeline, texture format bit `0x40` was never tracked or converted. As a result, fragment programs sampling unnormalized textures were passed integer texel indices directly into `Texture2D.Sample()`. Because indices exceeded $1.0$, texture addressing clamped or wrapped to borders, causing blown-out or completely black sampled textures in post-processing passes. + +--- + +## Change + +- In `libs/video/rsx_d3d12_backend.c`: + - **`dr_unnorm_units`**: Introduced helper extracting the bitmask of texture units with `fmt & 0x40` along with their $\{w, h, 1\}$ dimensions. + - **`VPFPEntry` Pipeline Cache Keys**: Extended the PSO cache struct `VPFPEntry` to store `unnorm_mask` and `unnorm_dim[16][3]`. Pipeline cache lookups now check `unnorm_mask` and dimensions to ensure specialized shaders are never aliased with normalized shaders. + - **Shader Specialization via `rsx_fp_apply_unnorm_scale`**: Wired `rsx_fp_apply_unnorm_scale` into `vp_get_fp_pso` so coordinates for unnormalized units are scaled by $(1.0 / w, 1.0 / h)$ prior to shader compilation. + - **Pre-pass and Draw Binding**: Updated `render_frame` pre-pass and per-draw PSO invocations to calculate `unnorm_mask` and pass it to `vp_get_fp_pso`. + +--- + +## Factual Citations & Hardware References + +1. **NVIDIA NV40 Architecture – Unnormalized Texture Coordinate Addressing:** + - *Reference:* [Khronos OpenGL ARB_texture_rectangle Extension Specification](https://registry.khronos.org/OpenGL/extensions/ARB/ARB_texture_rectangle.txt) + - *Hardware Semantics:* On NV40/RSX hardware, textures configured with unnormalized coordinates (`0x40`) interpret $(s, t)$ in integer texel space $[0, w) \times [0, h)$. In host APIs without hardware rectangle samplers (such as D3D12 `Texture2D`), shader coordinates must be divided by $(w, h)$ to convert into standard normalized $[0, 1]$ coordinates. + +--- + +## Evidence + +### Before vs. With this change + +| Scenario | Before | With this change | +|---|---|---| +| Textures with format bit `0x40` | Integer coordinates passed directly to D3D12 `Sample()` -> clamped/black | Scaled by $(1/w, 1/h)$ via `rsx_fp_apply_unnorm_scale` -> sampled accurately | +| Pipeline Cache Key | Unnorm state ignored -> wrong PSO reused across passes | Keyed on `unnorm_mask` and dimensions in `VPFPEntry` | + +--- + +## AI Assistance & Clean-Room Compliance + +In accordance with upstream guidelines ([`CONTRIBUTORS.md#a-note-on-ai-assisted-contributions`](CONTRIBUTORS.md#a-note-on-ai-assisted-contributions)): +- Authored with AI assistance (Antigravity), directed and verified against NV40 texture addressing specifications and runtime shader telemetry. +- Clean-room implementation: independent coordinate scaling integration; zero code copied or adapted from RPCS3 or other GPL emulators. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-618/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-618/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e13f6b00a1051dcef74b31c40a9b258f02ac260a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-618/tests/oracle.patch @@ -0,0 +1,107 @@ +diff --git a/libs/video/rsx_d3d12_backend.c b/libs/video/rsx_d3d12_backend.c +index bc05a308..4a5787dc 100644 +--- a/libs/video/rsx_d3d12_backend.c ++++ b/libs/video/rsx_d3d12_backend.c +@@ -260,6 +260,8 @@ typedef struct { + * declares those samplers as TextureCube, so a cube + * and a 2D variant of the same program are different + * pipelines and must not share a cache entry. */ ++ u32 unnorm_mask; /* unnormalized textures mask (PSO key) */ ++ u32 unnorm_dim[16][3]; /* unnormalized dimensions for scaling */ + u64 zs; /* depth/stencil state, rsx_zs_key (PSO key) */ + ID3D12PipelineState* pso; + } VPFPEntry; +@@ -2324,9 +2326,25 @@ static u32 dr_cube_mask(const D3D12DrawRecord* dr) + return m; + } + ++/* Which of a draw's texture units use unnormalized coordinates, with dimensions. */ ++static u32 dr_unnorm_units(const D3D12DrawRecord* dr, u32 dim[16][3]) ++{ ++ u32 mask = 0; ++ for (int u = 0; u < (int)(sizeof(dr->tex) / sizeof(dr->tex[0])); u++) { ++ dim[u][0] = dim[u][1] = dim[u][2] = 0; ++ if (!dr->tex[u].set || !(dr->tex[u].fmt & 0x40) || !dr->tex[u].w || !dr->tex[u].h) ++ continue; ++ mask |= 1u << u; ++ dim[u][0] = dr->tex[u].w; ++ dim[u][1] = dr->tex[u].h; ++ dim[u][2] = 1; ++ } ++ return mask; ++} ++ + static ID3D12PipelineState* vp_get_fp_pso(int vs_idx, u32 fp_addr, u32 blend, int nrt, + DXGI_FORMAT rtfmt, u32 ctrl, u32 cmask, u32 cull, +- u32 cube_mask, u64 zs) ++ u32 cube_mask, u32 unnorm_mask, const u32 unnorm_dim[16][3], u64 zs) + { + if (nrt < 0) nrt = 0; if (nrt > 4) nrt = 4; /* 0: a depth-only pass */ + if (rtfmt == 0) rtfmt = DXGI_FORMAT_R8G8B8A8_UNORM; +@@ -2385,7 +2403,9 @@ static ID3D12PipelineState* vp_get_fp_pso(int vs_idx, u32 fp_addr, u32 blend, in + s_d3d.vp_fp[i].rtfmt == (u32)rtfmt && s_d3d.vp_fp[i].ctrl == ctrl && + s_d3d.vp_fp[i].ucode_hash == uhash && s_d3d.vp_fp[i].cmask == cmask && + s_d3d.vp_fp[i].cull == cull && +- s_d3d.vp_fp[i].cube_mask == cube_mask && s_d3d.vp_fp[i].zs == zs) ++ s_d3d.vp_fp[i].cube_mask == cube_mask && s_d3d.vp_fp[i].zs == zs && ++ s_d3d.vp_fp[i].unnorm_mask == unnorm_mask && ++ (!unnorm_mask || memcmp(s_d3d.vp_fp[i].unnorm_dim, unnorm_dim, sizeof(s_d3d.vp_fp[i].unnorm_dim)) == 0)) + return s_d3d.vp_fp[i].pso; + s_perf_pso_miss++; /* falls through to a full decompile + D3DCompile */ + /* PSOMISSDBG=1: on a miss, name the key field that differs from an existing +@@ -2451,6 +2471,9 @@ static ID3D12PipelineState* vp_get_fp_pso(int vs_idx, u32 fp_addr, u32 blend, in + u32 fp_ctrl = ctrl_auto ? RSX_FP_CTRL_AUTO : ctrl; + int n = rsx_fp_decompile(vm_base + off, 4096, fp_ctrl, hlsl, sizeof(hlsl)); + if (n <= 0) { static int _e=0; if(PS3_LOG_FIRST(_e, 16)) printf("[FP] decompile fail (fp=0x%08X)\n", fp_addr); return NULL; } ++ if (unnorm_mask) { ++ rsx_fp_apply_unnorm_scale(hlsl, sizeof(hlsl), unnorm_mask, (const u32 (*)[3])unnorm_dim, cube_mask, 0); ++ } + /* FP_LIST=1: every program the title actually compiles, with its size. A + * fragment program that hangs the GPU shows up here as an implausible + * instruction count long before it shows up as a TDR. */ +@@ -2782,6 +2805,11 @@ static ID3D12PipelineState* vp_get_fp_pso(int vs_idx, u32 fp_addr, u32 blend, in + s_d3d.vp_fp[s_d3d.vp_fp_n].cmask = cmask; + s_d3d.vp_fp[s_d3d.vp_fp_n].cull = cull; + s_d3d.vp_fp[s_d3d.vp_fp_n].cube_mask = cube_mask; ++ s_d3d.vp_fp[s_d3d.vp_fp_n].unnorm_mask = unnorm_mask; ++ if (unnorm_mask) ++ memcpy(s_d3d.vp_fp[s_d3d.vp_fp_n].unnorm_dim, unnorm_dim, sizeof(s_d3d.vp_fp[s_d3d.vp_fp_n].unnorm_dim)); ++ else ++ memset(s_d3d.vp_fp[s_d3d.vp_fp_n].unnorm_dim, 0, sizeof(s_d3d.vp_fp[s_d3d.vp_fp_n].unnorm_dim)); + s_d3d.vp_fp[s_d3d.vp_fp_n].zs = zs; + s_d3d.vp_fp[s_d3d.vp_fp_n].pso = pso; + s_d3d.vp_fp_n++; +@@ -4913,12 +4941,14 @@ static void render_frame(void) + } + if (perf_on()) s_perf_srv += perf_now() - _sv0; + double _ps0 = perf_on() ? perf_now() : 0.0; ++ u32 unnorm_dim[16][3]; ++ u32 unnorm_mask = dr_unnorm_units(dr, unnorm_dim); + if (dr->fp_addr) vp_get_fp_pso(dr->vs_idx, dr->fp_addr, dr->blend_key, + dr_num_rts(dr), + dr->rt_off ? rsx_surface_dxgi(dr->rt_fmt) + : DXGI_FORMAT_R8G8B8A8_UNORM, + dr->fp_ctrl, dr->cmask, dr->cull, dr_cube_mask(dr), +- dr->zs_key); ++ unnorm_mask, unnorm_dim, dr->zs_key); + if (perf_on()) s_perf_pso += perf_now() - _ps0; + } + +@@ -5294,13 +5324,16 @@ static void render_frame(void) + } + /* Per-draw pipeline: prefer the guest's own compiled FP; fall + * back to the hardcoded atlas/colour PS pair. */ ++ u32 unnorm_dim[16][3]; ++ u32 unnorm_mask = dr_unnorm_units(dr, unnorm_dim); + ID3D12PipelineState* dpso = + dr->fp_addr ? vp_get_fp_pso(dr->vs_idx, dr->fp_addr, dr->blend_key, + dr_num_rts(dr), + dr->rt_off ? rsx_surface_dxgi(dr->rt_fmt) + : DXGI_FORMAT_R8G8B8A8_UNORM, + dr->fp_ctrl, dr->cmask, dr->cull, +- dr_cube_mask(dr), dr->zs_key) : NULL; ++ dr_cube_mask(dr), ++ unnorm_mask, unnorm_dim, dr->zs_key) : NULL; + s_d3d.cmd_list->lpVtbl->SetPipelineState(s_d3d.cmd_list, + dpso ? dpso : vpso); + s_d3d.cmd_list->lpVtbl->OMSetStencilRef(s_d3d.cmd_list, dr->stencil_ref & 0xFFu); diff --git a/tasks/sp00nznet__ps3recomp-618/tests/test.sh b/tasks/sp00nznet__ps3recomp-618/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-618/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-618/tests/verifier.py b/tasks/sp00nznet__ps3recomp-618/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-618/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-619/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-619/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-619/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-619/instruction.md b/tasks/sp00nznet__ps3recomp-619/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3138c5c247142b68e9cfb29ee4718b0fe0fc73a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-619/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** spu channels: ordered wakeups, masked RdEventStat, word SRR0, aligned atomic LSA + +## Description + +Four small fixes in `runtime/spu/spu_channels.c`, with a regression test. + +1. Lost wakeups on blocking channel reads. `spu_ch_wait` tests and sleeps under `ch_wait_lock`, but producers called `spu_ch_wake` without it, so a wake landing between the test and the sleep was lost and the read waited for the 10 ms re-poll. `spu_ch_wake` now takes and releases `ch_wait_lock` before waking. No caller holds that lock, so there's no deadlock risk. +2. `SPU_RdEventStat` returned every pending event. It now returns pending & enabled, the same condition `rchcnt` and the blocking wait already use. +3. `SPU_WrSRR0` kept all 32 bits. It now keeps `v & 0x3FFFC`. +4. GETLLAR/PUTLLC/PUTLLUC used `MFC_LSA` unaligned. They now use the 128-byte-aligned LSA, like the EA side. An LSA in the last 128 bytes of local store used to copy the line past the end of `ls_store` into the context. + +New test: `runtime/spu/tests/test_spu_channel_semantics.c`, run by `tools/test_spu_channel_semantics.py`, built like `test_spu_decrementer`. It has 18 checks. +- Master's `spu_channels.c`: 10 checks fail, and the last-128-bytes LSA case crashes. +- Reverting only the wake change: the deterministic lock-ordering check fails. +- A 20,000-handoff mailbox ping-pong, 6 runs each, which only prints its counts: without the wake fix there were 0–6 handoffs per run over 5 ms (about 15 ms each, the re-poll). With it there were none (slowest 0.08 ms). + +ctest is 21/21 on Windows 11 with clang-cl, the same as master. The SPU fixtures that touch `spu_channels.c` (machine_status, decrementer, sdcrz, event_atomic, event_ack_sn, dma_repeat) pass when built with `zig cc -target x86_64-windows-gnu`. I haven't run the POSIX build. The same lost-wake window exists in the `ps3__cv_sleep` shim, so the fix applies there too. + +Already fixed on master, so not included: the decrementer past 231 s (#313) and `RdMachStat` (6cf4ef40). + +This is original code. For items 2–4 the expected values were checked against RPCS3's behaviour; no code was copied. It comes from the [Project 8 Plus](https://github.com/MaxLeiter/project-8-plus) port and was developed with AI assistance (Claude). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-619/solution/patch.diff b/tasks/sp00nznet__ps3recomp-619/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6939a77c8e1868c6e4a22b751bca4be2e84b80d1 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-619/solution/patch.diff @@ -0,0 +1,359 @@ +diff --git a/runtime/spu/spu_channels.c b/runtime/spu/spu_channels.c +index 5fc50208..2f910c76 100644 +--- a/runtime/spu/spu_channels.c ++++ b/runtime/spu/spu_channels.c +@@ -589,7 +589,12 @@ static int spu_mfc_atomic(spu_context* ctx, uint32_t cmd) + return 0; + + uint32_t ea = ctx->mfc_eal & ~(uint32_t)(MFC_ATOMIC_LINE - 1); +- uint32_t lsa = ctx->mfc_lsa & SPU_LS_MASK; ++ /* The line moves to and from a 128-byte aligned local-store address: the ++ * low seven bits of MFC_LSA are ignored, as those of the EA are. Used ++ * unmasked, an unaligned LSA put the line at the wrong place, and one in ++ * the last 128 bytes of local store carried the copy past the end of the ++ * store and over the context behind it. */ ++ uint32_t lsa = ctx->mfc_lsa & SPU_LS_MASK & ~(uint32_t)(MFC_ATOMIC_LINE - 1); + uint8_t* ls = &ctx->ls[lsa]; + uint8_t* mem = vm_base + ea; + +@@ -1073,7 +1078,7 @@ void spu_wrch(spu_context* ctx, uint32_t channel, u128 value) + SPU_EVENT_SET(ctx, 0x2u); + spu_lockline_unlock(); + break; +- case SPU_WrSRR0: ctx->srr0 = v; break; ++ case SPU_WrSRR0: ctx->srr0 = v & 0x3FFFCu; /* a word-aligned LS address */ break; + default: + /* Unknown / unhandled channel write -- ignore (matches a no-op SPU). */ + break; +@@ -1152,6 +1157,17 @@ static int spu_ch_ready(spu_context* ctx, uint32_t channel) + void spu_ch_wake(spu_context* ctx) + { + if (!ctx) return; ++ /* Pass through the waiter's lock first. spu_ch_wait tests its predicate and ++ * goes to sleep under ch_wait_lock, but a producer makes the predicate true ++ * outside it. A wake issued between the waiter's test and its sleep found ++ * nobody on the condition variable and was lost (on POSIX the shim's ++ * generation count is read when the sleep begins, so it misses it too); ++ * the read then completed only at the 10 ms re-poll. Taking the lock orders ++ * this wake after the waiter is either asleep or has not yet tested. ++ * Uncontended it is one lock/unlock pair. No caller holds ch_wait_lock, and ++ * the waiter takes no other lock while it does. */ ++ AcquireSRWLockExclusive((SRWLOCK*)&ctx->ch_wait_lock); ++ ReleaseSRWLockExclusive((SRWLOCK*)&ctx->ch_wait_lock); + WakeAllConditionVariable((CONDITION_VARIABLE*)&ctx->ch_wait_cv); + } + +@@ -1298,7 +1314,11 @@ u128 spu_rdch(spu_context* ctx, uint32_t channel) + break; + } + case SPU_RdEventMask: v = ctx->event_mask; break; +- case SPU_RdEventStat: spu_resv_lost_poll(ctx); v = ctx->event_status; break; ++ /* The events that are pending AND enabled. A pending event the SPU has ++ * not unmasked (an Lr left by a lost reservation, an Sn) must not show up ++ * in a read that is waiting on a different set; this is the condition ++ * spu_ch_ready and rchcnt already use. */ ++ case SPU_RdEventStat: spu_resv_lost_poll(ctx); v = ctx->event_status & ctx->event_mask; break; + /* CBEA 9.8: numeric bit 0 is interrupt-enable, independent of run status. + * This runtime models nonisolated SPUs, so the isolation bit stays clear. */ + case SPU_RdMachStat: v = ctx->int_enable & 1u; break; +diff --git a/runtime/spu/tests/test_spu_channel_semantics.c b/runtime/spu/tests/test_spu_channel_semantics.c +new file mode 100644 +index 00000000..a5e75948 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_channel_semantics.c +@@ -0,0 +1,256 @@ ++/* ++ * SPU channel and atomic-command semantics that guest code relies on ++ * (runtime/spu/spu_channels.c): ++ * ++ * - a producer's spu_ch_wake is ordered after a reader that has tested its ++ * predicate but not yet gone to sleep, so a blocking read is never left to ++ * the 10 ms re-poll; ++ * - SPU_RdEventStat returns the events that are pending AND enabled; ++ * - SPU_WrSRR0 keeps a word-aligned local-store address; ++ * - GETLLAR / PUTLLC / PUTLLUC move the 128-byte line to and from a 128-byte ++ * aligned local-store address, whatever the low bits of MFC_LSA say. ++ * ++ * spu_channels.c is compiled in rather than linked, as in ++ * test_spu_decrementer.c, whose build line this test shares; tools/ ++ * test_spu_channel_semantics.py runs it. Pass a handoff count as the first ++ * argument to run the blocking-read handoff more times (default 2000) and ++ * print how many were left to the re-poll. ++ * ++ * Exit code: 0 if all passed, 1 if any failed. ++ */ ++ ++#include <pthread.h> ++#include <stddef.h> ++#include <stdint.h> ++#include <stdio.h> ++#include <stdlib.h> ++#include <string.h> ++#include <time.h> ++ ++static uint8_t g_guest_mem[1u << 20]; ++uint8_t* vm_base = g_guest_mem; ++uint32_t ppu_vm_size = 0; ++ ++#include "../spu_channels.c" ++ ++static int g_pass, g_fail; ++#define CHECK(cond) do { \ ++ if (cond) g_pass++; \ ++ else { g_fail++; fprintf(stderr, "FAIL at %s:%d: %s\n", __FILE__, __LINE__, #cond); } \ ++} while (0) ++ ++static spu_context g_spu; ++ ++static uint64_t now_ns(void) ++{ ++ struct timespec ts; ++ clock_gettime(CLOCK_MONOTONIC, &ts); ++ return (uint64_t)ts.tv_sec * 1000000000u + (uint64_t)ts.tv_nsec; ++} ++ ++/* --------------------------------------------------------------------------- ++ * Blocking reads and the wake that ends them ++ * -----------------------------------------------------------------------*/ ++static int g_prod_done; ++ ++static void* wake_producer(void* arg) ++{ ++ (void)arg; ++ spu_channel_write(&g_spu.ch_in_mbox, 0x5A5A5A5Au); ++ spu_ch_wake(&g_spu); ++ __atomic_store_n(&g_prod_done, 1, __ATOMIC_SEQ_CST); ++ return NULL; ++} ++ ++/* A reader tests its predicate and sleeps under ch_wait_lock. Holding that ++ * lock stands in for a reader that has just found the mailbox empty: the ++ * producer's wake has to come after the reader is asleep (and so can see it), ++ * which means it cannot complete while the lock is held. */ ++static void test_wake_is_ordered_after_the_waiter(void) ++{ ++ pthread_t t; ++ g_prod_done = 0; ++ AcquireSRWLockExclusive((SRWLOCK*)&g_spu.ch_wait_lock); ++ pthread_create(&t, NULL, wake_producer, NULL); ++ Sleep(100); ++ CHECK(!__atomic_load_n(&g_prod_done, __ATOMIC_SEQ_CST)); ++ ReleaseSRWLockExclusive((SRWLOCK*)&g_spu.ch_wait_lock); ++ pthread_join(t, NULL); ++ CHECK(__atomic_load_n(&g_prod_done, __ATOMIC_SEQ_CST)); ++ (void)spu_channel_read(&g_spu.ch_in_mbox); ++} ++ ++/* Ping-pong a mailbox word through a reader that blocks in rdch, writing at ++ * the moment the reader is about to find the mailbox empty. Returns how many ++ * handoffs took longer than the 10 ms re-poll could explain. */ ++static spu_context g_hs_spu; ++static int g_hs_ready, g_hs_got, g_hs_total; ++static uint64_t g_hs_stamp, g_hs_slowest; ++static int g_hs_late; ++ ++static void* handoff_reader(void* arg) ++{ ++ (void)arg; ++ for (int i = 0; i < g_hs_total; i++) { ++ __atomic_store_n(&g_hs_ready, i + 1, __ATOMIC_SEQ_CST); ++ const uint32_t v = spu_rdch(&g_hs_spu, SPU_RdInMbox)._u32[0]; ++ const uint64_t dt = now_ns() - __atomic_load_n(&g_hs_stamp, __ATOMIC_SEQ_CST); ++ if (v != 0xC0DE0000u + (uint32_t)i) g_hs_late = -1000000; ++ if (dt > 5000000u) g_hs_late++; ++ if (dt > g_hs_slowest) g_hs_slowest = dt; ++ __atomic_store_n(&g_hs_got, i + 1, __ATOMIC_SEQ_CST); ++ } ++ return NULL; ++} ++ ++static void test_blocking_read_handoff(int n) ++{ ++ pthread_t t; ++ spu_context_init(&g_hs_spu, 1); ++ g_hs_total = n; g_hs_ready = g_hs_got = g_hs_late = 0; g_hs_slowest = 0; ++ pthread_create(&t, NULL, handoff_reader, NULL); ++ for (int i = 0; i < n; i++) { ++ while (__atomic_load_n(&g_hs_ready, __ATOMIC_SEQ_CST) != i + 1) Sleep(0); ++ for (volatile int k = 0; k < (i * 7) % 300; k++) { } /* vary where the write lands */ ++ __atomic_store_n(&g_hs_stamp, now_ns(), __ATOMIC_SEQ_CST); ++ spu_channel_write(&g_hs_spu.ch_in_mbox, 0xC0DE0000u + (uint32_t)i); ++ spu_ch_wake(&g_hs_spu); ++ while (__atomic_load_n(&g_hs_got, __ATOMIC_SEQ_CST) != i + 1) Sleep(0); ++ } ++ pthread_join(t, NULL); ++ CHECK(g_hs_late >= 0); /* every word arrived, in order */ ++ printf("%d blocking mailbox handoffs: %d slower than 5 ms, slowest %.3f ms\n", ++ n, g_hs_late < 0 ? 0 : g_hs_late, (double)g_hs_slowest / 1e6); ++} ++ ++/* --------------------------------------------------------------------------- ++ * Event status, SRR0 ++ * -----------------------------------------------------------------------*/ ++static uint32_t rdch(uint32_t ch) { return spu_rdch(&g_spu, ch)._u32[0]; } ++static void wrch(uint32_t ch, uint32_t v) { spu_wrch(&g_spu, ch, spu_splat_u32(v)); } ++ ++static void test_event_status_is_pending_and_enabled(void) ++{ ++ g_spu.event_status = 0; ++ wrch(SPU_WrEventMask, 0x0002u); ++ SPU_EVENT_SET(&g_spu, 0x0002u | 0x0010u); /* one enabled, one not */ ++ CHECK(rdch(SPU_RdEventStat) == 0x0002u); ++ ++ wrch(SPU_WrEventMask, 0x0010u | 0x0002u); ++ CHECK(rdch(SPU_RdEventStat) == (0x0002u | 0x0010u)); ++ ++ wrch(SPU_WrEventMask, 0x0004u); /* only a disabled event is pending */ ++ g_spu.event_status = 0x0002u; ++ CHECK(spu_rchcnt(&g_spu, SPU_RdEventStat) == 0); /* what the count already said */ ++ wrch(SPU_WrEventMask, 0); /* nothing enabled: nothing reads */ ++ CHECK(rdch(SPU_RdEventStat) == 0); ++ g_spu.event_status = 0; ++} ++ ++static void test_srr0_is_a_word_local_store_address(void) ++{ ++ wrch(SPU_WrSRR0, 0x12345678u); ++ CHECK(rdch(SPU_RdSRR0) == (0x12345678u & 0x3FFFCu)); ++ wrch(SPU_WrSRR0, 0xFFFFFFFFu); ++ CHECK(rdch(SPU_RdSRR0) == 0x3FFFCu); ++ wrch(SPU_WrSRR0, 0x2040u); ++ CHECK(rdch(SPU_RdSRR0) == 0x2040u); ++} ++ ++/* --------------------------------------------------------------------------- ++ * Atomic commands and the local-store address ++ * -----------------------------------------------------------------------*/ ++static void atomic_cmd(spu_context* c, uint32_t ea, uint32_t lsa, uint32_t cmd) ++{ ++ c->mfc_eah = 0; c->mfc_eal = ea; c->mfc_lsa = lsa; ++ (void)spu_mfc_atomic(c, cmd); ++} ++ ++static void test_atomic_commands_use_an_aligned_lsa(void) ++{ ++ static spu_context c; ++ const uint32_t ea = 0x40000; ++ uint8_t line[128], other[128]; ++ for (int i = 0; i < 128; i++) { line[i] = (uint8_t)(0x10 + i); other[i] = (uint8_t)(0xA0 ^ i); } ++ spu_context_init(&c, 2); ++ c.image_id = -1; ++ ++ /* GETLLAR with the low seven bits of the LSA set fills the aligned line. */ ++ memcpy(g_guest_mem + ea, line, 128); ++ memset(c.ls, 0xEE, SPU_LS_SIZE); ++ atomic_cmd(&c, ea, 0x2000 + 0x4C, MFC_GETLLAR_CMD); ++ CHECK(memcmp(c.ls + 0x2000, line, 128) == 0); ++ CHECK(c.ls[0x1FFF] == 0xEE && c.ls[0x2080] == 0xEE); ++ CHECK(c.resv_valid); ++ ++ /* PUTLLC from an unaligned LSA stores the aligned line and succeeds. */ ++ memcpy(c.ls + 0x2000, other, 128); ++ atomic_cmd(&c, ea, 0x2000 + 0x7F, MFC_PUTLLC_CMD); ++ CHECK(c.atomic_stat == 0); ++ CHECK(memcmp(g_guest_mem + ea, other, 128) == 0); ++ ++ /* PUTLLUC likewise. */ ++ memcpy(c.ls + 0x3000, line, 128); ++ atomic_cmd(&c, ea + 0x80, 0x3000 + 0x01, MFC_PUTLLUC_CMD); ++ CHECK(memcmp(g_guest_mem + ea + 0x80, line, 128) == 0); ++ ++ /* The last 128 bytes of local store: an unaligned LSA used to carry the ++ * copy past the end of the store and over the context behind it. */ ++ { ++ const size_t after = offsetof(spu_context, ls_store) + SPU_LS_SIZE; ++ uint8_t tail[128], tail_before[128]; ++ memcpy(tail_before, (uint8_t*)&c + after, sizeof tail_before); ++ memcpy(g_guest_mem + ea, line, 128); ++ atomic_cmd(&c, ea, SPU_LS_SIZE - 16, MFC_GETLLAR_CMD); ++ memcpy(tail, (uint8_t*)&c + after, sizeof tail); ++ CHECK(memcmp(tail, tail_before, sizeof tail) == 0); ++ CHECK(memcmp(c.ls + SPU_LS_SIZE - 128, line, 128) == 0); ++ } ++} ++ ++int main(int argc, char** argv) ++{ ++ const int handoffs = argc > 1 ? atoi(argv[1]) : 2000; ++ ++ spu_context_init(&g_spu, 0); ++ g_spu.image_id = -1; ++ g_spu_force_ch_block = 1; /* blocking reads, as for a raw SPU */ ++ ++ test_wake_is_ordered_after_the_waiter(); ++ test_blocking_read_handoff(handoffs); ++ test_event_status_is_pending_and_enabled(); ++ test_srr0_is_a_word_local_store_address(); ++ test_atomic_commands_use_an_aligned_lsa(); ++ ++ printf("SPU channel semantics: %d passed, %d failed\n", g_pass, g_fail); ++ return g_fail ? 1 : 0; ++} ++ ++/* --------------------------------------------------------------------------- ++ * The runtime beyond the SPU channel layer, stubbed as in ++ * test_spu_decrementer.c. None of it is on the path this test drives. ++ * -----------------------------------------------------------------------*/ ++void ppu_resv_break_store(uint64_t ea) { (void)ea; } ++void ps3_ww_report_inline(uint32_t a, uint64_t v, int w) ++{ ++ (void)a; (void)v; (void)w; ++} ++unsigned long long ps3_ms_now(void) { return now_ns() / 1000000u; } ++uint32_t g_ww_lo = 0xFFFFFFFFu, g_ww_hi = 0; ++int g_resv_store_active = 0; ++uint32_t g_barrier_sync_watch = 0; ++ ++void (*g_spurs_kernel_hook)(uint32_t) = 0; ++uint32_t g_ydkj_spurs_ctx_ea = 0; ++uint32_t g_ydkj_real_spurs_ea = 0; ++uint32_t g_ydkj_real_taskset_ea = 0; ++uint32_t g_ydkj_real_taskid = 0; ++void spurs_ef_set_from_spu(uint32_t ea, uint16_t bits) { (void)ea; (void)bits; } ++void ydkj_wake_all_event_flags(void) { } ++void spurs_pm_build_context(spu_context* c, uint32_t a, uint32_t b, uint32_t d) ++{ ++ (void)c; (void)a; (void)b; (void)d; ++} ++ ++uint32_t g_spu_image_src_ea, g_spu_image_ls_start, g_spu_image_span; ++void spu_thread_publish_ctx(uint32_t tid, void* ctx) { (void)tid; (void)ctx; } +diff --git a/tools/test_spu_channel_semantics.py b/tools/test_spu_channel_semantics.py +new file mode 100644 +index 00000000..0002a566 +--- /dev/null ++++ b/tools/test_spu_channel_semantics.py +@@ -0,0 +1,33 @@ ++#!/usr/bin/env python3 ++"""SPU channels and atomics: wake ordering, RdEventStat, SRR0, aligned LSA. ++ ++Builds runtime/spu/tests/test_spu_channel_semantics.c against the SPU channel ++layer (the build line of test_spu_decrementer.c) and runs it. ++""" ++import os ++from pathlib import Path ++import subprocess ++import sys ++import tempfile ++ ++if os.name == 'nt': ++ print('SKIP: fixture currently requires a POSIX C compiler') ++ raise SystemExit(0) ++root = Path(__file__).resolve().parents[1] ++sources = ['runtime/spu/tests/test_spu_channel_semantics.c', ++ 'runtime/spu/spu_drain.c', 'runtime/spu/spu_lockstep.c', ++ 'runtime/spu/spu_coherency.c', 'runtime/spu/spu_workload.c', ++ 'runtime/spu/spurs_policy.c', 'runtime/spu/spurs_job.c', ++ 'runtime/spu/spu_tsp_weak.c', 'runtime/spu/spu_vm_pagemap.c', ++ 'runtime/spu/spurs_policy_blob_weak.c', 'runtime/spu/spu_interp.c', ++ 'runtime/platform/win32_compat.c'] ++env = {k: v for k, v in os.environ.items() ++ if not k.startswith(('SPU_', 'SPURS_', 'YDKJ_', 'LBP_', 'GH3_'))} ++with tempfile.TemporaryDirectory(prefix='spu-channel-semantics-') as tmp: ++ binary = Path(tmp) / 'test' ++ subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu17', '-O1', '-w', ++ '-I', str(root / 'include'), '-I', str(root / 'runtime/spu'), ++ '-I', str(root / 'runtime/platform'), ++ *[str(root / s) for s in sources], ++ '-o', str(binary), '-lpthread', '-lm'], check=True) ++ subprocess.run([str(binary)], check=True, timeout=60, env=env, cwd=tmp) diff --git a/tasks/sp00nznet__ps3recomp-619/solution/solve.sh b/tasks/sp00nznet__ps3recomp-619/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-619/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-619/task.toml b/tasks/sp00nznet__ps3recomp-619/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d7a845790936fa71c672fd6d0faa6701551362d9 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-619/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-619" +description = "spu channels: ordered wakeups, masked RdEventStat, word SRR0, aligned atomic LSA" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/619" +source_access = "auto" +built_at = "2026-11-16T16:09:59.671975+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c01b8993a8fc1b98d18813edf93b261f336afc51702ebdcd8f8cea246daf6b94" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "runtime/spu/spu_channels.c", + "runtime/spu/tests/test_spu_channel_semantics.c", + "tools/test_spu_channel_semantics.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 315 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.132050+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-619/tests/capture.py b/tasks/sp00nznet__ps3recomp-619/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-619/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-619/tests/instruction.md b/tasks/sp00nznet__ps3recomp-619/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3138c5c247142b68e9cfb29ee4718b0fe0fc73a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-619/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** spu channels: ordered wakeups, masked RdEventStat, word SRR0, aligned atomic LSA + +## Description + +Four small fixes in `runtime/spu/spu_channels.c`, with a regression test. + +1. Lost wakeups on blocking channel reads. `spu_ch_wait` tests and sleeps under `ch_wait_lock`, but producers called `spu_ch_wake` without it, so a wake landing between the test and the sleep was lost and the read waited for the 10 ms re-poll. `spu_ch_wake` now takes and releases `ch_wait_lock` before waking. No caller holds that lock, so there's no deadlock risk. +2. `SPU_RdEventStat` returned every pending event. It now returns pending & enabled, the same condition `rchcnt` and the blocking wait already use. +3. `SPU_WrSRR0` kept all 32 bits. It now keeps `v & 0x3FFFC`. +4. GETLLAR/PUTLLC/PUTLLUC used `MFC_LSA` unaligned. They now use the 128-byte-aligned LSA, like the EA side. An LSA in the last 128 bytes of local store used to copy the line past the end of `ls_store` into the context. + +New test: `runtime/spu/tests/test_spu_channel_semantics.c`, run by `tools/test_spu_channel_semantics.py`, built like `test_spu_decrementer`. It has 18 checks. +- Master's `spu_channels.c`: 10 checks fail, and the last-128-bytes LSA case crashes. +- Reverting only the wake change: the deterministic lock-ordering check fails. +- A 20,000-handoff mailbox ping-pong, 6 runs each, which only prints its counts: without the wake fix there were 0–6 handoffs per run over 5 ms (about 15 ms each, the re-poll). With it there were none (slowest 0.08 ms). + +ctest is 21/21 on Windows 11 with clang-cl, the same as master. The SPU fixtures that touch `spu_channels.c` (machine_status, decrementer, sdcrz, event_atomic, event_ack_sn, dma_repeat) pass when built with `zig cc -target x86_64-windows-gnu`. I haven't run the POSIX build. The same lost-wake window exists in the `ps3__cv_sleep` shim, so the fix applies there too. + +Already fixed on master, so not included: the decrementer past 231 s (#313) and `RdMachStat` (6cf4ef40). + +This is original code. For items 2–4 the expected values were checked against RPCS3's behaviour; no code was copied. It comes from the [Project 8 Plus](https://github.com/MaxLeiter/project-8-plus) port and was developed with AI assistance (Claude). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-619/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-619/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6939a77c8e1868c6e4a22b751bca4be2e84b80d1 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-619/tests/oracle.patch @@ -0,0 +1,359 @@ +diff --git a/runtime/spu/spu_channels.c b/runtime/spu/spu_channels.c +index 5fc50208..2f910c76 100644 +--- a/runtime/spu/spu_channels.c ++++ b/runtime/spu/spu_channels.c +@@ -589,7 +589,12 @@ static int spu_mfc_atomic(spu_context* ctx, uint32_t cmd) + return 0; + + uint32_t ea = ctx->mfc_eal & ~(uint32_t)(MFC_ATOMIC_LINE - 1); +- uint32_t lsa = ctx->mfc_lsa & SPU_LS_MASK; ++ /* The line moves to and from a 128-byte aligned local-store address: the ++ * low seven bits of MFC_LSA are ignored, as those of the EA are. Used ++ * unmasked, an unaligned LSA put the line at the wrong place, and one in ++ * the last 128 bytes of local store carried the copy past the end of the ++ * store and over the context behind it. */ ++ uint32_t lsa = ctx->mfc_lsa & SPU_LS_MASK & ~(uint32_t)(MFC_ATOMIC_LINE - 1); + uint8_t* ls = &ctx->ls[lsa]; + uint8_t* mem = vm_base + ea; + +@@ -1073,7 +1078,7 @@ void spu_wrch(spu_context* ctx, uint32_t channel, u128 value) + SPU_EVENT_SET(ctx, 0x2u); + spu_lockline_unlock(); + break; +- case SPU_WrSRR0: ctx->srr0 = v; break; ++ case SPU_WrSRR0: ctx->srr0 = v & 0x3FFFCu; /* a word-aligned LS address */ break; + default: + /* Unknown / unhandled channel write -- ignore (matches a no-op SPU). */ + break; +@@ -1152,6 +1157,17 @@ static int spu_ch_ready(spu_context* ctx, uint32_t channel) + void spu_ch_wake(spu_context* ctx) + { + if (!ctx) return; ++ /* Pass through the waiter's lock first. spu_ch_wait tests its predicate and ++ * goes to sleep under ch_wait_lock, but a producer makes the predicate true ++ * outside it. A wake issued between the waiter's test and its sleep found ++ * nobody on the condition variable and was lost (on POSIX the shim's ++ * generation count is read when the sleep begins, so it misses it too); ++ * the read then completed only at the 10 ms re-poll. Taking the lock orders ++ * this wake after the waiter is either asleep or has not yet tested. ++ * Uncontended it is one lock/unlock pair. No caller holds ch_wait_lock, and ++ * the waiter takes no other lock while it does. */ ++ AcquireSRWLockExclusive((SRWLOCK*)&ctx->ch_wait_lock); ++ ReleaseSRWLockExclusive((SRWLOCK*)&ctx->ch_wait_lock); + WakeAllConditionVariable((CONDITION_VARIABLE*)&ctx->ch_wait_cv); + } + +@@ -1298,7 +1314,11 @@ u128 spu_rdch(spu_context* ctx, uint32_t channel) + break; + } + case SPU_RdEventMask: v = ctx->event_mask; break; +- case SPU_RdEventStat: spu_resv_lost_poll(ctx); v = ctx->event_status; break; ++ /* The events that are pending AND enabled. A pending event the SPU has ++ * not unmasked (an Lr left by a lost reservation, an Sn) must not show up ++ * in a read that is waiting on a different set; this is the condition ++ * spu_ch_ready and rchcnt already use. */ ++ case SPU_RdEventStat: spu_resv_lost_poll(ctx); v = ctx->event_status & ctx->event_mask; break; + /* CBEA 9.8: numeric bit 0 is interrupt-enable, independent of run status. + * This runtime models nonisolated SPUs, so the isolation bit stays clear. */ + case SPU_RdMachStat: v = ctx->int_enable & 1u; break; +diff --git a/runtime/spu/tests/test_spu_channel_semantics.c b/runtime/spu/tests/test_spu_channel_semantics.c +new file mode 100644 +index 00000000..a5e75948 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_channel_semantics.c +@@ -0,0 +1,256 @@ ++/* ++ * SPU channel and atomic-command semantics that guest code relies on ++ * (runtime/spu/spu_channels.c): ++ * ++ * - a producer's spu_ch_wake is ordered after a reader that has tested its ++ * predicate but not yet gone to sleep, so a blocking read is never left to ++ * the 10 ms re-poll; ++ * - SPU_RdEventStat returns the events that are pending AND enabled; ++ * - SPU_WrSRR0 keeps a word-aligned local-store address; ++ * - GETLLAR / PUTLLC / PUTLLUC move the 128-byte line to and from a 128-byte ++ * aligned local-store address, whatever the low bits of MFC_LSA say. ++ * ++ * spu_channels.c is compiled in rather than linked, as in ++ * test_spu_decrementer.c, whose build line this test shares; tools/ ++ * test_spu_channel_semantics.py runs it. Pass a handoff count as the first ++ * argument to run the blocking-read handoff more times (default 2000) and ++ * print how many were left to the re-poll. ++ * ++ * Exit code: 0 if all passed, 1 if any failed. ++ */ ++ ++#include <pthread.h> ++#include <stddef.h> ++#include <stdint.h> ++#include <stdio.h> ++#include <stdlib.h> ++#include <string.h> ++#include <time.h> ++ ++static uint8_t g_guest_mem[1u << 20]; ++uint8_t* vm_base = g_guest_mem; ++uint32_t ppu_vm_size = 0; ++ ++#include "../spu_channels.c" ++ ++static int g_pass, g_fail; ++#define CHECK(cond) do { \ ++ if (cond) g_pass++; \ ++ else { g_fail++; fprintf(stderr, "FAIL at %s:%d: %s\n", __FILE__, __LINE__, #cond); } \ ++} while (0) ++ ++static spu_context g_spu; ++ ++static uint64_t now_ns(void) ++{ ++ struct timespec ts; ++ clock_gettime(CLOCK_MONOTONIC, &ts); ++ return (uint64_t)ts.tv_sec * 1000000000u + (uint64_t)ts.tv_nsec; ++} ++ ++/* --------------------------------------------------------------------------- ++ * Blocking reads and the wake that ends them ++ * -----------------------------------------------------------------------*/ ++static int g_prod_done; ++ ++static void* wake_producer(void* arg) ++{ ++ (void)arg; ++ spu_channel_write(&g_spu.ch_in_mbox, 0x5A5A5A5Au); ++ spu_ch_wake(&g_spu); ++ __atomic_store_n(&g_prod_done, 1, __ATOMIC_SEQ_CST); ++ return NULL; ++} ++ ++/* A reader tests its predicate and sleeps under ch_wait_lock. Holding that ++ * lock stands in for a reader that has just found the mailbox empty: the ++ * producer's wake has to come after the reader is asleep (and so can see it), ++ * which means it cannot complete while the lock is held. */ ++static void test_wake_is_ordered_after_the_waiter(void) ++{ ++ pthread_t t; ++ g_prod_done = 0; ++ AcquireSRWLockExclusive((SRWLOCK*)&g_spu.ch_wait_lock); ++ pthread_create(&t, NULL, wake_producer, NULL); ++ Sleep(100); ++ CHECK(!__atomic_load_n(&g_prod_done, __ATOMIC_SEQ_CST)); ++ ReleaseSRWLockExclusive((SRWLOCK*)&g_spu.ch_wait_lock); ++ pthread_join(t, NULL); ++ CHECK(__atomic_load_n(&g_prod_done, __ATOMIC_SEQ_CST)); ++ (void)spu_channel_read(&g_spu.ch_in_mbox); ++} ++ ++/* Ping-pong a mailbox word through a reader that blocks in rdch, writing at ++ * the moment the reader is about to find the mailbox empty. Returns how many ++ * handoffs took longer than the 10 ms re-poll could explain. */ ++static spu_context g_hs_spu; ++static int g_hs_ready, g_hs_got, g_hs_total; ++static uint64_t g_hs_stamp, g_hs_slowest; ++static int g_hs_late; ++ ++static void* handoff_reader(void* arg) ++{ ++ (void)arg; ++ for (int i = 0; i < g_hs_total; i++) { ++ __atomic_store_n(&g_hs_ready, i + 1, __ATOMIC_SEQ_CST); ++ const uint32_t v = spu_rdch(&g_hs_spu, SPU_RdInMbox)._u32[0]; ++ const uint64_t dt = now_ns() - __atomic_load_n(&g_hs_stamp, __ATOMIC_SEQ_CST); ++ if (v != 0xC0DE0000u + (uint32_t)i) g_hs_late = -1000000; ++ if (dt > 5000000u) g_hs_late++; ++ if (dt > g_hs_slowest) g_hs_slowest = dt; ++ __atomic_store_n(&g_hs_got, i + 1, __ATOMIC_SEQ_CST); ++ } ++ return NULL; ++} ++ ++static void test_blocking_read_handoff(int n) ++{ ++ pthread_t t; ++ spu_context_init(&g_hs_spu, 1); ++ g_hs_total = n; g_hs_ready = g_hs_got = g_hs_late = 0; g_hs_slowest = 0; ++ pthread_create(&t, NULL, handoff_reader, NULL); ++ for (int i = 0; i < n; i++) { ++ while (__atomic_load_n(&g_hs_ready, __ATOMIC_SEQ_CST) != i + 1) Sleep(0); ++ for (volatile int k = 0; k < (i * 7) % 300; k++) { } /* vary where the write lands */ ++ __atomic_store_n(&g_hs_stamp, now_ns(), __ATOMIC_SEQ_CST); ++ spu_channel_write(&g_hs_spu.ch_in_mbox, 0xC0DE0000u + (uint32_t)i); ++ spu_ch_wake(&g_hs_spu); ++ while (__atomic_load_n(&g_hs_got, __ATOMIC_SEQ_CST) != i + 1) Sleep(0); ++ } ++ pthread_join(t, NULL); ++ CHECK(g_hs_late >= 0); /* every word arrived, in order */ ++ printf("%d blocking mailbox handoffs: %d slower than 5 ms, slowest %.3f ms\n", ++ n, g_hs_late < 0 ? 0 : g_hs_late, (double)g_hs_slowest / 1e6); ++} ++ ++/* --------------------------------------------------------------------------- ++ * Event status, SRR0 ++ * -----------------------------------------------------------------------*/ ++static uint32_t rdch(uint32_t ch) { return spu_rdch(&g_spu, ch)._u32[0]; } ++static void wrch(uint32_t ch, uint32_t v) { spu_wrch(&g_spu, ch, spu_splat_u32(v)); } ++ ++static void test_event_status_is_pending_and_enabled(void) ++{ ++ g_spu.event_status = 0; ++ wrch(SPU_WrEventMask, 0x0002u); ++ SPU_EVENT_SET(&g_spu, 0x0002u | 0x0010u); /* one enabled, one not */ ++ CHECK(rdch(SPU_RdEventStat) == 0x0002u); ++ ++ wrch(SPU_WrEventMask, 0x0010u | 0x0002u); ++ CHECK(rdch(SPU_RdEventStat) == (0x0002u | 0x0010u)); ++ ++ wrch(SPU_WrEventMask, 0x0004u); /* only a disabled event is pending */ ++ g_spu.event_status = 0x0002u; ++ CHECK(spu_rchcnt(&g_spu, SPU_RdEventStat) == 0); /* what the count already said */ ++ wrch(SPU_WrEventMask, 0); /* nothing enabled: nothing reads */ ++ CHECK(rdch(SPU_RdEventStat) == 0); ++ g_spu.event_status = 0; ++} ++ ++static void test_srr0_is_a_word_local_store_address(void) ++{ ++ wrch(SPU_WrSRR0, 0x12345678u); ++ CHECK(rdch(SPU_RdSRR0) == (0x12345678u & 0x3FFFCu)); ++ wrch(SPU_WrSRR0, 0xFFFFFFFFu); ++ CHECK(rdch(SPU_RdSRR0) == 0x3FFFCu); ++ wrch(SPU_WrSRR0, 0x2040u); ++ CHECK(rdch(SPU_RdSRR0) == 0x2040u); ++} ++ ++/* --------------------------------------------------------------------------- ++ * Atomic commands and the local-store address ++ * -----------------------------------------------------------------------*/ ++static void atomic_cmd(spu_context* c, uint32_t ea, uint32_t lsa, uint32_t cmd) ++{ ++ c->mfc_eah = 0; c->mfc_eal = ea; c->mfc_lsa = lsa; ++ (void)spu_mfc_atomic(c, cmd); ++} ++ ++static void test_atomic_commands_use_an_aligned_lsa(void) ++{ ++ static spu_context c; ++ const uint32_t ea = 0x40000; ++ uint8_t line[128], other[128]; ++ for (int i = 0; i < 128; i++) { line[i] = (uint8_t)(0x10 + i); other[i] = (uint8_t)(0xA0 ^ i); } ++ spu_context_init(&c, 2); ++ c.image_id = -1; ++ ++ /* GETLLAR with the low seven bits of the LSA set fills the aligned line. */ ++ memcpy(g_guest_mem + ea, line, 128); ++ memset(c.ls, 0xEE, SPU_LS_SIZE); ++ atomic_cmd(&c, ea, 0x2000 + 0x4C, MFC_GETLLAR_CMD); ++ CHECK(memcmp(c.ls + 0x2000, line, 128) == 0); ++ CHECK(c.ls[0x1FFF] == 0xEE && c.ls[0x2080] == 0xEE); ++ CHECK(c.resv_valid); ++ ++ /* PUTLLC from an unaligned LSA stores the aligned line and succeeds. */ ++ memcpy(c.ls + 0x2000, other, 128); ++ atomic_cmd(&c, ea, 0x2000 + 0x7F, MFC_PUTLLC_CMD); ++ CHECK(c.atomic_stat == 0); ++ CHECK(memcmp(g_guest_mem + ea, other, 128) == 0); ++ ++ /* PUTLLUC likewise. */ ++ memcpy(c.ls + 0x3000, line, 128); ++ atomic_cmd(&c, ea + 0x80, 0x3000 + 0x01, MFC_PUTLLUC_CMD); ++ CHECK(memcmp(g_guest_mem + ea + 0x80, line, 128) == 0); ++ ++ /* The last 128 bytes of local store: an unaligned LSA used to carry the ++ * copy past the end of the store and over the context behind it. */ ++ { ++ const size_t after = offsetof(spu_context, ls_store) + SPU_LS_SIZE; ++ uint8_t tail[128], tail_before[128]; ++ memcpy(tail_before, (uint8_t*)&c + after, sizeof tail_before); ++ memcpy(g_guest_mem + ea, line, 128); ++ atomic_cmd(&c, ea, SPU_LS_SIZE - 16, MFC_GETLLAR_CMD); ++ memcpy(tail, (uint8_t*)&c + after, sizeof tail); ++ CHECK(memcmp(tail, tail_before, sizeof tail) == 0); ++ CHECK(memcmp(c.ls + SPU_LS_SIZE - 128, line, 128) == 0); ++ } ++} ++ ++int main(int argc, char** argv) ++{ ++ const int handoffs = argc > 1 ? atoi(argv[1]) : 2000; ++ ++ spu_context_init(&g_spu, 0); ++ g_spu.image_id = -1; ++ g_spu_force_ch_block = 1; /* blocking reads, as for a raw SPU */ ++ ++ test_wake_is_ordered_after_the_waiter(); ++ test_blocking_read_handoff(handoffs); ++ test_event_status_is_pending_and_enabled(); ++ test_srr0_is_a_word_local_store_address(); ++ test_atomic_commands_use_an_aligned_lsa(); ++ ++ printf("SPU channel semantics: %d passed, %d failed\n", g_pass, g_fail); ++ return g_fail ? 1 : 0; ++} ++ ++/* --------------------------------------------------------------------------- ++ * The runtime beyond the SPU channel layer, stubbed as in ++ * test_spu_decrementer.c. None of it is on the path this test drives. ++ * -----------------------------------------------------------------------*/ ++void ppu_resv_break_store(uint64_t ea) { (void)ea; } ++void ps3_ww_report_inline(uint32_t a, uint64_t v, int w) ++{ ++ (void)a; (void)v; (void)w; ++} ++unsigned long long ps3_ms_now(void) { return now_ns() / 1000000u; } ++uint32_t g_ww_lo = 0xFFFFFFFFu, g_ww_hi = 0; ++int g_resv_store_active = 0; ++uint32_t g_barrier_sync_watch = 0; ++ ++void (*g_spurs_kernel_hook)(uint32_t) = 0; ++uint32_t g_ydkj_spurs_ctx_ea = 0; ++uint32_t g_ydkj_real_spurs_ea = 0; ++uint32_t g_ydkj_real_taskset_ea = 0; ++uint32_t g_ydkj_real_taskid = 0; ++void spurs_ef_set_from_spu(uint32_t ea, uint16_t bits) { (void)ea; (void)bits; } ++void ydkj_wake_all_event_flags(void) { } ++void spurs_pm_build_context(spu_context* c, uint32_t a, uint32_t b, uint32_t d) ++{ ++ (void)c; (void)a; (void)b; (void)d; ++} ++ ++uint32_t g_spu_image_src_ea, g_spu_image_ls_start, g_spu_image_span; ++void spu_thread_publish_ctx(uint32_t tid, void* ctx) { (void)tid; (void)ctx; } +diff --git a/tools/test_spu_channel_semantics.py b/tools/test_spu_channel_semantics.py +new file mode 100644 +index 00000000..0002a566 +--- /dev/null ++++ b/tools/test_spu_channel_semantics.py +@@ -0,0 +1,33 @@ ++#!/usr/bin/env python3 ++"""SPU channels and atomics: wake ordering, RdEventStat, SRR0, aligned LSA. ++ ++Builds runtime/spu/tests/test_spu_channel_semantics.c against the SPU channel ++layer (the build line of test_spu_decrementer.c) and runs it. ++""" ++import os ++from pathlib import Path ++import subprocess ++import sys ++import tempfile ++ ++if os.name == 'nt': ++ print('SKIP: fixture currently requires a POSIX C compiler') ++ raise SystemExit(0) ++root = Path(__file__).resolve().parents[1] ++sources = ['runtime/spu/tests/test_spu_channel_semantics.c', ++ 'runtime/spu/spu_drain.c', 'runtime/spu/spu_lockstep.c', ++ 'runtime/spu/spu_coherency.c', 'runtime/spu/spu_workload.c', ++ 'runtime/spu/spurs_policy.c', 'runtime/spu/spurs_job.c', ++ 'runtime/spu/spu_tsp_weak.c', 'runtime/spu/spu_vm_pagemap.c', ++ 'runtime/spu/spurs_policy_blob_weak.c', 'runtime/spu/spu_interp.c', ++ 'runtime/platform/win32_compat.c'] ++env = {k: v for k, v in os.environ.items() ++ if not k.startswith(('SPU_', 'SPURS_', 'YDKJ_', 'LBP_', 'GH3_'))} ++with tempfile.TemporaryDirectory(prefix='spu-channel-semantics-') as tmp: ++ binary = Path(tmp) / 'test' ++ subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu17', '-O1', '-w', ++ '-I', str(root / 'include'), '-I', str(root / 'runtime/spu'), ++ '-I', str(root / 'runtime/platform'), ++ *[str(root / s) for s in sources], ++ '-o', str(binary), '-lpthread', '-lm'], check=True) ++ subprocess.run([str(binary)], check=True, timeout=60, env=env, cwd=tmp) diff --git a/tasks/sp00nznet__ps3recomp-619/tests/test.sh b/tasks/sp00nznet__ps3recomp-619/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-619/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-619/tests/verifier.py b/tasks/sp00nznet__ps3recomp-619/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-619/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-622/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-622/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-622/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-622/instruction.md b/tasks/sp00nznet__ps3recomp-622/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a2188a27024eb5affbb1b9634779921e0178b68 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-622/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** sys_event: queue destroy honours its mode, timed receive runs to an absolute deadline + +## Description + +Two fixes in `sys_event.c`. + +1. `sys_event_queue_destroy` ignored its mode and deleted the queue's lock under any blocked receiver, which then never woke. An unknown mode is now EINVAL, a plain destroy with receivers blocked is EBUSY and leaves them blocked, and `SYS_EVENT_QUEUE_DESTROY_FORCE` wakes every receiver with CELL_ECANCELED. Receivers are counted in a new `sys_event_queue_info.waiters` so destroy knows when the last one has left. Ports connected to the destroyed queue are disconnected, so a later send answers ENOTCONN instead of landing in whatever queue reuses the slot. +2. On Windows a timed receive of 1 ms or more waited `timeout_us / 1000` per wake. 1500 us became 1 ms, and every wake that found the queue empty (another receiver took the event) restarted the full timeout, so a contended receive could overrun without bound. It now waits to an absolute QPC deadline, rounded up so it never returns early. On POSIX, a timeout is no longer reported when an event arrived with it. + +Test: `tests/sync_stress/test_event_queue_destroy.c`, a new ctest target that links `sys_event.c` and the suite's shims. It checks the mode handling with two blocked receivers, ENOTCONN after a FORCE destroy (including after the slot is reused), and that a 120 ms receive with a spurious wake every 25 ms ends near 120 ms. Without the fix the timed receive never returns and the destroy checks fail. + +Tested on Windows 11 with clang-cl: the full ctest passes (master's 21 plus this test), and the new test passed 15 of 15 repeated runs. I haven't run a POSIX build; the POSIX changes are the timeout check and the shared waiter accounting. + +Nothing in this area is already on master. + +This is original code, written against the current file; no RPCS3 or other GPL code was used. It comes from the [Project 8 Plus](https://github.com/MaxLeiter/project-8-plus) port and was developed with AI assistance (Claude). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-622/solution/patch.diff b/tasks/sp00nznet__ps3recomp-622/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e3fd8b0753aab3be5adacc84c740465f62ffa290 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-622/solution/patch.diff @@ -0,0 +1,492 @@ +diff --git a/runtime/syscalls/sys_event.c b/runtime/syscalls/sys_event.c +index adabcc56..9153a475 100644 +--- a/runtime/syscalls/sys_event.c ++++ b/runtime/syscalls/sys_event.c +@@ -85,6 +85,21 @@ static uint64_t bswap64(uint64_t v) + #endif + } + ++#ifdef _WIN32 ++/* Milliseconds left to a lv2_usec_deadline() deadline, rounded UP (a timed ++ * receive must not return before the guest's timeout); 0 once it has passed. */ ++static DWORD evt_ms_until(int64_t deadline) ++{ ++ LARGE_INTEGER f, now; ++ QueryPerformanceFrequency(&f); ++ QueryPerformanceCounter(&now); ++ if (now.QuadPart >= deadline) return 0; ++ const uint64_t left = (uint64_t)(deadline - now.QuadPart), q = (uint64_t)f.QuadPart; ++ const uint64_t ms = (left / q) * 1000ull + ((left % q) * 1000ull + q - 1) / q; ++ return ms >= (uint64_t)INFINITE ? (DWORD)(INFINITE - 1) : (DWORD)ms; ++} ++#endif ++ + /* ========================================================================= + * EVENT QUEUES + * ========================================================================= */ +@@ -217,9 +232,13 @@ int64_t sys_event_queue_create(ppu_context* ctx) + int64_t sys_event_queue_destroy(ppu_context* ctx) + { + uint32_t queue_id = LV2_ARG_U32(ctx, 0); ++ /* r4 = mode: 0, or SYS_EVENT_QUEUE_DESTROY_FORCE. It was ignored. */ ++ int32_t mode = LV2_ARG_S32(ctx, 1); + + if (queue_id == 0 || queue_id > SYS_EVENT_QUEUE_MAX) + return getenv("YDKJ_EVT_LENIENT") ? CELL_OK : (int64_t)(int32_t)CELL_ESRCH; /* idempotent teardown */ ++ if (mode != 0 && mode != SYS_EVENT_QUEUE_DESTROY_FORCE) ++ return (int64_t)(int32_t)CELL_EINVAL; + + evt_table_lock(); + +@@ -229,14 +248,52 @@ int64_t sys_event_queue_destroy(ppu_context* ctx) + return getenv("YDKJ_EVT_LENIENT") ? CELL_OK : (int64_t)(int32_t)CELL_ESRCH; /* idempotent teardown */ + } + ++ /* Receivers blocked in the queue. This used to delete the lock and ++ * condition variable under them: a receiver parked with no timeout never ++ * woke again. lv2: a plain destroy with waiters is EBUSY; FORCE wakes every ++ * waiter with CELL_ECANCELED. The lock and condition variable are ++ * deliberately NOT destroyed: a receiver that passed its unlocked `active` ++ * test just before this can still enter them safely and will see !active, ++ * and create re-initialises them when the slot is reused. */ + #ifdef _WIN32 +- DeleteCriticalSection(&q->lock); ++ EnterCriticalSection(&q->lock); ++ if (q->waiters > 0 && mode != SYS_EVENT_QUEUE_DESTROY_FORCE) { ++ LeaveCriticalSection(&q->lock); ++ evt_table_unlock(); ++ return (int64_t)(int32_t)CELL_EBUSY; ++ } ++ q->active = 0; ++ WakeAllConditionVariable(&q->not_empty); ++ while (q->waiters > 0) { /* let them return ECANCELED first */ ++ LeaveCriticalSection(&q->lock); ++ SwitchToThread(); ++ EnterCriticalSection(&q->lock); ++ } ++ LeaveCriticalSection(&q->lock); + #else +- pthread_cond_destroy(&q->not_empty); +- pthread_mutex_destroy(&q->lock); ++ pthread_mutex_lock(&q->lock); ++ if (q->waiters > 0 && mode != SYS_EVENT_QUEUE_DESTROY_FORCE) { ++ pthread_mutex_unlock(&q->lock); ++ evt_table_unlock(); ++ return (int64_t)(int32_t)CELL_EBUSY; ++ } ++ q->active = 0; ++ pthread_cond_broadcast(&q->not_empty); ++ while (q->waiters > 0) { ++ pthread_mutex_unlock(&q->lock); ++ sched_yield(); ++ pthread_mutex_lock(&q->lock); ++ } ++ pthread_mutex_unlock(&q->lock); + #endif + +- q->active = 0; ++ /* Ports still wired to this queue are now unconnected: a send answers ++ * ENOTCONN, and the stale index can no longer deliver into whatever queue ++ * next reuses this slot. */ ++ for (int i = 0; i < SYS_EVENT_PORT_MAX; i++) ++ if (g_sys_event_ports[i].active && g_sys_event_ports[i].connected_queue == (int32_t)queue_id) ++ g_sys_event_ports[i].connected_queue = 0; ++ + evt_table_unlock(); + return CELL_OK; + } +@@ -477,6 +534,13 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + + #ifdef _WIN32 + EnterCriticalSection(&q->lock); ++ if (!q->active) { /* destroyed since the unlocked test */ ++ LeaveCriticalSection(&q->lock); ++ return (int64_t)(int32_t)CELL_ESRCH; ++ } ++ /* Counted while inside (every return below gives it back): destroy needs it ++ * for its EBUSY / FORCE decision and to know when we are out. */ ++ q->waiters++; + + /* EVT_RECV_KICK=<qid>:<ms>: an infinite wait on that queue that sees + * nothing for <ms> gets the last event pushed to the queue re-delivered. +@@ -490,6 +554,7 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + while (q->count == 0 && q->active && !q->cancelled) { + if (!SleepConditionVariableCS(&q->not_empty, &q->lock, s_kms) && q->count == 0) { + sys_event_t evt = s_last_evt[queue_id - 1]; ++ q->waiters--; + LeaveCriticalSection(&q->lock); + { static int n = 0; if (n++ < 16) + fprintf(stderr, "[evt] EVT_RECV_KICK: q=%u idle %lu ms -> re-delivered last event\n", +@@ -510,6 +575,7 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + SleepConditionVariableCS(&q->not_empty, &q->lock, INFINITE); + } + if (q->count == 0 && q->cancelled) { ++ q->waiters--; + LeaveCriticalSection(&q->lock); + return (int64_t)(int32_t)CELL_ECANCELED; + } +@@ -522,26 +588,45 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + * return ETIMEDOUT immediately if empty -- same result the game already + * handles, just without the bogus 15ms stall. */ + if (q->count == 0 || !q->active) { ++ q->waiters--; + LeaveCriticalSection(&q->lock); + return (int64_t)(int32_t)CELL_ETIMEDOUT; + } + } else { +- DWORD ms = (DWORD)(timeout_us / 1000); ++ /* Wait to an absolute deadline. A fixed `timeout_us / 1000` per wait ++ * truncated (1500 us became 1 ms) and restarted the FULL timeout after ++ * every wake that found the queue empty (another receiver took the ++ * event), so a contended timed receive could overrun without bound. ++ * The slice is rounded up, so it never returns before the guest's ++ * timeout, and an event that lands right at the deadline is still ++ * taken (the loop re-tests the count before giving up). Past 2^40 us ++ * (12.7 days) the QPC arithmetic would wrap; that is forever anyway. */ ++ const int64_t deadline = lv2_usec_deadline(timeout_us < (1ull << 40) ? timeout_us : (1ull << 40)); + while (q->count == 0 && q->active && !q->cancelled) { +- if (!SleepConditionVariableCS(&q->not_empty, &q->lock, ms)) { +- if (GetLastError() == ERROR_TIMEOUT) { +- LeaveCriticalSection(&q->lock); +- return (int64_t)(int32_t)CELL_ETIMEDOUT; +- } ++ const DWORD ms = evt_ms_until(deadline); ++ if (ms == 0) { ++ q->waiters--; ++ LeaveCriticalSection(&q->lock); ++ return (int64_t)(int32_t)CELL_ETIMEDOUT; + } ++ SleepConditionVariableCS(&q->not_empty, &q->lock, ms); + } + } + ++ if (!q->active) { ++ /* Destroyed with SYS_EVENT_QUEUE_DESTROY_FORCE while we waited: lv2 ++ * hands every waiter CELL_ECANCELED. */ ++ q->waiters--; ++ LeaveCriticalSection(&q->lock); ++ return (int64_t)(int32_t)CELL_ECANCELED; ++ } + if (q->count == 0 && q->cancelled) { ++ q->waiters--; + LeaveCriticalSection(&q->lock); + return (int64_t)(int32_t)CELL_ECANCELED; + } +- if (!q->active || q->count == 0) { ++ if (q->count == 0) { ++ q->waiters--; + LeaveCriticalSection(&q->lock); + return (int64_t)(int32_t)CELL_ESRCH; + } +@@ -550,9 +635,15 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + q->head = (q->head + 1) % q->capacity; + q->count--; + ++ q->waiters--; + LeaveCriticalSection(&q->lock); + #else + pthread_mutex_lock(&q->lock); ++ if (!q->active) { /* destroyed since the unlocked test */ ++ pthread_mutex_unlock(&q->lock); ++ return (int64_t)(int32_t)CELL_ESRCH; ++ } ++ q->waiters++; /* see the _WIN32 branch */ + + if (timeout_us == 0) { + while (q->count == 0 && q->active && !q->cancelled) { +@@ -569,18 +660,26 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + } + while (q->count == 0 && q->active && !q->cancelled) { + int rc = pthread_cond_timedwait(&q->not_empty, &q->lock, &ts); +- if (rc == ETIMEDOUT) { ++ if (rc == ETIMEDOUT && q->count == 0) { ++ q->waiters--; + pthread_mutex_unlock(&q->lock); + return (int64_t)(int32_t)CELL_ETIMEDOUT; + } + } + } + ++ if (!q->active) { /* FORCE-destroyed while waiting */ ++ q->waiters--; ++ pthread_mutex_unlock(&q->lock); ++ return (int64_t)(int32_t)CELL_ECANCELED; ++ } + if (q->count == 0 && q->cancelled) { ++ q->waiters--; + pthread_mutex_unlock(&q->lock); + return (int64_t)(int32_t)CELL_ECANCELED; + } +- if (!q->active || q->count == 0) { ++ if (q->count == 0) { ++ q->waiters--; + pthread_mutex_unlock(&q->lock); + return (int64_t)(int32_t)CELL_ESRCH; + } +@@ -589,6 +688,7 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + q->head = (q->head + 1) % q->capacity; + q->count--; + ++ q->waiters--; + pthread_mutex_unlock(&q->lock); + #endif + +diff --git a/runtime/syscalls/sys_event.h b/runtime/syscalls/sys_event.h +index 14c64255..1407bd7f 100644 +--- a/runtime/syscalls/sys_event.h ++++ b/runtime/syscalls/sys_event.h +@@ -65,6 +65,12 @@ typedef struct sys_event_queue_info { + * arrive; later receives fail the same way rather than re-blocking. */ + int cancelled; + ++ /* Receivers currently inside sys_event_queue_receive's locked section (under ++ * `lock`). sys_event_queue_destroy needs it: lv2 answers EBUSY to a plain ++ * destroy while receivers wait, and a FORCE destroy wakes them with ++ * ECANCELED and has to let them leave before the slot can be reused. */ ++ int waiters; ++ + #ifdef _WIN32 + CRITICAL_SECTION lock; + CONDITION_VARIABLE not_empty; +@@ -75,6 +81,9 @@ typedef struct sys_event_queue_info { + + } sys_event_queue_info; + ++/* sys_event_queue_destroy's mode argument. */ ++#define SYS_EVENT_QUEUE_DESTROY_FORCE 1 ++ + extern sys_event_queue_info g_sys_event_queues[SYS_EVENT_QUEUE_MAX]; + + /* --------------------------------------------------------------------------- +diff --git a/tests/sync_stress/CMakeLists.txt b/tests/sync_stress/CMakeLists.txt +index 455ce7a1..19f20713 100644 +--- a/tests/sync_stress/CMakeLists.txt ++++ b/tests/sync_stress/CMakeLists.txt +@@ -138,3 +138,27 @@ if(WIN32) + set_tests_properties(cond_${mode} PROPERTIES TIMEOUT 10) + endforeach() + endif() ++ ++# sys_event_queue_destroy modes (EINVAL / EBUSY / FORCE -> ECANCELED), ports ++# disconnected from a destroyed queue, and the absolute deadline of a timed ++# receive. Links sys_event.c alone. ++add_executable(test_event_queue_destroy ++ test_event_queue_destroy.c test_shims.c ++ "${RUNTIME_SYNC_DIR}/sys_event.c") ++if(NOT WIN32) ++ target_sources(test_event_queue_destroy PRIVATE ++ "${PS3RECOMP_TREE_ROOT}/runtime/platform/win32_compat.c") ++ find_package(Threads REQUIRED) ++ target_link_libraries(test_event_queue_destroy PRIVATE Threads::Threads) ++endif() ++target_include_directories(test_event_queue_destroy PRIVATE ++ "${PS3RECOMP_TREE_ROOT}" "${PS3RECOMP_TREE_ROOT}/include" ++ "${RUNTIME_SYNC_DIR}" "${PS3RECOMP_TREE_ROOT}/runtime") ++if(MSVC) ++ target_compile_definitions(test_event_queue_destroy PRIVATE _CRT_SECURE_NO_WARNINGS) ++ target_compile_options(test_event_queue_destroy PRIVATE /experimental:c11atomics) ++else() ++ target_compile_options(test_event_queue_destroy PRIVATE -Wall -Wextra -Wno-unused-parameter) ++endif() ++add_test(NAME event_queue_destroy COMMAND test_event_queue_destroy) ++set_tests_properties(event_queue_destroy PROPERTIES LABELS "runtime;sync" TIMEOUT 60) +diff --git a/tests/sync_stress/test_event_queue_destroy.c b/tests/sync_stress/test_event_queue_destroy.c +new file mode 100644 +index 00000000..3c301759 +--- /dev/null ++++ b/tests/sync_stress/test_event_queue_destroy.c +@@ -0,0 +1,194 @@ ++/* sys_event_queue_destroy and timed receive. ++ * ++ * - mode is honoured: an unknown mode is EINVAL; a plain destroy while a ++ * receiver is blocked is EBUSY and leaves that receiver blocked; a FORCE ++ * destroy returns every blocked receiver CELL_ECANCELED. The lock was ++ * deleted under a receiver parked with no timeout, which then never woke. ++ * - ports connected to a destroyed queue are disconnected (send is ENOTCONN), ++ * so a send cannot land in whatever queue next reuses the slot. ++ * - a timed receive runs to an absolute deadline: wake-ups that find the queue ++ * empty do not restart the timeout. ++ * ++ * Win32 host threads, through the shim off Windows. Links sys_event.c and ++ * test_shims.c only. */ ++#include "runtime/platform/win32_compat.h" ++#include "runtime/syscalls/sys_event.h" ++#include <stdio.h> ++#include <stdlib.h> ++#include <string.h> ++ ++uint8_t* vm_base; ++ ++/* sys_event.c's title-diagnostic side paths reach for these; none can run here. */ ++size_t spu_elf_image_size(const uint8_t* image, size_t max_avail) { (void)image; (void)max_avail; return 0; } ++int spu_workload_dispatch_async(const uint8_t* image, uint32_t image_size, uint32_t args_ea) ++{ (void)image; (void)image_size; (void)args_ea; return 0; } ++void ppu_dump_guest_stack(ppu_context* ctx, const char* tag) { (void)ctx; (void)tag; } ++uint32_t yz_thread_current_id(void) { return 0; } ++ ++static int failures; ++#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #x); failures++; } } while (0) ++#define CHECK_RC(call, want) do { int32_t _rc = (int32_t)(call); \ ++ if (_rc != (int32_t)(want)) { fprintf(stderr, "FAIL line %d: %s -> 0x%08X, want 0x%08X\n", \ ++ __LINE__, #call, (unsigned)_rc, (unsigned)(want)); failures++; } } while (0) ++ ++typedef int64_t (*sc_fn)(ppu_context*); ++static int32_t call(sc_fn f, uint32_t tid, uint64_t a, uint64_t b, uint64_t c, uint64_t d) ++{ ++ ppu_context ctx; ++ memset(&ctx, 0, sizeof ctx); ++ ctx.thread_id = tid; ++ ctx.gpr[3] = a; ctx.gpr[4] = b; ctx.gpr[5] = c; ctx.gpr[6] = d; ++ return (int32_t)f(&ctx); ++} ++static uint32_t be_read(unsigned off) ++{ ++ const uint8_t* p = vm_base + off; ++ return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3]; ++} ++static double now_ms(void) ++{ ++ LARGE_INTEGER f, c; ++ QueryPerformanceFrequency(&f); ++ QueryPerformanceCounter(&c); ++ return (double)c.QuadPart * 1000.0 / (double)f.QuadPart; ++} ++ ++typedef struct recv { ++ uint32_t q; ++ uint64_t timeout_us; ++ uint32_t event_at; ++ volatile int32_t rc; ++ double ms; ++ HANDLE h; ++} recv_t; ++static DWORD WINAPI recv_main(void* p) ++{ ++ recv_t* r = (recv_t*)p; ++ const double t0 = now_ms(); ++ r->rc = call(sys_event_queue_receive, 2, r->q, r->event_at, r->timeout_us, 0); ++ r->ms = now_ms() - t0; ++ return 0; ++} ++static void recv_start(recv_t* r, uint32_t q, uint64_t timeout_us, uint32_t event_at) ++{ ++ r->q = q; r->timeout_us = timeout_us; r->event_at = event_at; r->rc = -1; r->ms = 0; ++ r->h = CreateThread(NULL, 0, recv_main, r, 0, NULL); ++} ++static void recv_join(recv_t* r) { WaitForSingleObject(r->h, 20000); CloseHandle(r->h); } ++ ++static uint32_t make_queue(void) ++{ ++ CHECK_RC(call(sys_event_queue_create, 1, 0x200, 0, 0x1234, 8), CELL_OK); ++ return be_read(0x200); ++} ++/* Wait until `n` receivers are inside the queue. */ ++static void wait_waiters(uint32_t q, int n) ++{ ++ for (int i = 0; i < 3000 && g_sys_event_queues[q - 1].waiters != n; i++) Sleep(1); ++ CHECK(g_sys_event_queues[q - 1].waiters == n); ++} ++ ++static void test_destroy_modes(void) ++{ ++ uint32_t q = make_queue(); ++ CHECK_RC(call(sys_event_queue_destroy, 1, q, 7, 0, 0), CELL_EINVAL); ++ CHECK(g_sys_event_queues[q - 1].active); ++ ++ /* A port wired to the queue. */ ++ CHECK_RC(call(sys_event_port_create, 1, 0x210, SYS_EVENT_PORT_LOCAL, 0, 0), CELL_OK); ++ const uint32_t port = be_read(0x210); ++ CHECK_RC(call(sys_event_port_connect_local, 1, port, q, 0, 0), CELL_OK); ++ CHECK_RC(call(sys_event_port_send, 1, port, 1, 2, 3), CELL_OK); /* queued */ ++ ++ /* Two receivers: the first takes the queued event, then both block. */ ++ recv_t r1, r2; ++ recv_start(&r1, q, 0, 0x300); ++ recv_join(&r1); ++ CHECK(r1.rc == CELL_OK); ++ recv_start(&r1, q, 0, 0x300); ++ recv_start(&r2, q, 0, 0x340); ++ wait_waiters(q, 2); ++ ++ /* A plain destroy refuses and leaves them blocked. */ ++ CHECK_RC(call(sys_event_queue_destroy, 1, q, 0, 0, 0), CELL_EBUSY); ++ CHECK(g_sys_event_queues[q - 1].active); ++ Sleep(50); ++ CHECK(r1.rc == -1 && r2.rc == -1); ++ ++ /* FORCE wakes both with ECANCELED. */ ++ CHECK_RC(call(sys_event_queue_destroy, 1, q, SYS_EVENT_QUEUE_DESTROY_FORCE, 0, 0), CELL_OK); ++ recv_join(&r1); recv_join(&r2); ++ CHECK(r1.rc == (int32_t)CELL_ECANCELED); ++ CHECK(r2.rc == (int32_t)CELL_ECANCELED); ++ CHECK(!g_sys_event_queues[q - 1].active); ++ ++ /* The port no longer points at the dead queue, and a new queue in that slot ++ * does not receive from it. */ ++ CHECK_RC(call(sys_event_port_send, 1, port, 1, 2, 3), CELL_ENOTCONN); ++ const uint32_t q2 = make_queue(); ++ CHECK(q2 == q); /* the slot is reused */ ++ CHECK_RC(call(sys_event_port_send, 1, port, 1, 2, 3), CELL_ENOTCONN); ++ CHECK(g_sys_event_queues[q2 - 1].count == 0); ++ CHECK_RC(call(sys_event_queue_receive, 1, q2, 0x300, 1000, 0), CELL_ETIMEDOUT); ++ ++ /* Idle: a plain destroy works, and a second one is ESRCH. */ ++ CHECK_RC(call(sys_event_queue_destroy, 1, q2, 0, 0, 0), CELL_OK); ++ CHECK_RC(call(sys_event_queue_destroy, 1, q2, 0, 0, 0), CELL_ESRCH); ++ CHECK_RC(call(sys_event_port_destroy, 1, port, 0, 0, 0), CELL_OK); ++} ++ ++/* Spurious wake-ups (a broadcast that finds the queue empty) every 25 ms. */ ++static volatile int s_stop_wakes; ++static uint32_t s_wake_q; ++static DWORD WINAPI waker(void* unused) ++{ ++ (void)unused; ++ while (!s_stop_wakes) { ++ Sleep(25); ++ sys_event_queue_info* q = &g_sys_event_queues[s_wake_q - 1]; ++#ifdef _WIN32 ++ WakeAllConditionVariable(&q->not_empty); ++#else ++ pthread_cond_broadcast(&q->not_empty); ++#endif ++ } ++ return 0; ++} ++ ++static void test_timed_receive(void) ++{ ++ const uint32_t q = make_queue(); ++ ++ /* Plain timeout: not early, not wildly late. */ ++ recv_t r; ++ recv_start(&r, q, 60000, 0x300); ++ recv_join(&r); ++ CHECK(r.rc == (int32_t)CELL_ETIMEDOUT); ++ CHECK(r.ms >= 55.0 && r.ms < 500.0); ++ ++ /* A wake-up that finds nothing must not restart the timeout: with one every ++ * 25 ms, a 120 ms receive still ends at about 120 ms (it used to start its ++ * full wait over after each wake, and so never ended). */ ++ s_wake_q = q; s_stop_wakes = 0; ++ HANDLE w = CreateThread(NULL, 0, waker, NULL, 0, NULL); ++ recv_start(&r, q, 120000, 0x300); ++ recv_join(&r); ++ s_stop_wakes = 1; ++ WaitForSingleObject(w, 5000); CloseHandle(w); ++ printf("timed receive 120 ms with a wake every 25 ms: rc 0x%08X after %.1f ms\n", (unsigned)r.rc, r.ms); ++ CHECK(r.rc == (int32_t)CELL_ETIMEDOUT); ++ CHECK(r.ms >= 110.0 && r.ms < 400.0); ++ ++ CHECK_RC(call(sys_event_queue_destroy, 1, q, 0, 0, 0), CELL_OK); ++} ++ ++int main(void) ++{ ++ vm_base = (uint8_t*)calloc(1, 65536); ++ if (!vm_base) return 2; ++ test_destroy_modes(); ++ test_timed_receive(); ++ printf("event queue destroy / timed receive: %s\n", failures ? "FAIL" : "PASS"); ++ return failures ? 1 : 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-622/solution/solve.sh b/tasks/sp00nznet__ps3recomp-622/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-622/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-622/task.toml b/tasks/sp00nznet__ps3recomp-622/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7cf94945589a440557e2bc8ccd9cb62ba9031e46 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-622/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-622" +description = "sys_event: queue destroy honours its mode, timed receive runs to an absolute deadline" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/622" +source_access = "auto" +built_at = "2026-11-16T16:09:59.669928+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2244e6e00ce5e89edff874b052a73b811545146223e147253d98fd3c4eb5d2b2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "runtime/syscalls/sys_event.c", + "runtime/syscalls/sys_event.h", + "tests/sync_stress/CMakeLists.txt", + "tests/sync_stress/test_event_queue_destroy.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 353 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.135646+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-622/tests/capture.py b/tasks/sp00nznet__ps3recomp-622/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-622/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-622/tests/instruction.md b/tasks/sp00nznet__ps3recomp-622/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a2188a27024eb5affbb1b9634779921e0178b68 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-622/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** sys_event: queue destroy honours its mode, timed receive runs to an absolute deadline + +## Description + +Two fixes in `sys_event.c`. + +1. `sys_event_queue_destroy` ignored its mode and deleted the queue's lock under any blocked receiver, which then never woke. An unknown mode is now EINVAL, a plain destroy with receivers blocked is EBUSY and leaves them blocked, and `SYS_EVENT_QUEUE_DESTROY_FORCE` wakes every receiver with CELL_ECANCELED. Receivers are counted in a new `sys_event_queue_info.waiters` so destroy knows when the last one has left. Ports connected to the destroyed queue are disconnected, so a later send answers ENOTCONN instead of landing in whatever queue reuses the slot. +2. On Windows a timed receive of 1 ms or more waited `timeout_us / 1000` per wake. 1500 us became 1 ms, and every wake that found the queue empty (another receiver took the event) restarted the full timeout, so a contended receive could overrun without bound. It now waits to an absolute QPC deadline, rounded up so it never returns early. On POSIX, a timeout is no longer reported when an event arrived with it. + +Test: `tests/sync_stress/test_event_queue_destroy.c`, a new ctest target that links `sys_event.c` and the suite's shims. It checks the mode handling with two blocked receivers, ENOTCONN after a FORCE destroy (including after the slot is reused), and that a 120 ms receive with a spurious wake every 25 ms ends near 120 ms. Without the fix the timed receive never returns and the destroy checks fail. + +Tested on Windows 11 with clang-cl: the full ctest passes (master's 21 plus this test), and the new test passed 15 of 15 repeated runs. I haven't run a POSIX build; the POSIX changes are the timeout check and the shared waiter accounting. + +Nothing in this area is already on master. + +This is original code, written against the current file; no RPCS3 or other GPL code was used. It comes from the [Project 8 Plus](https://github.com/MaxLeiter/project-8-plus) port and was developed with AI assistance (Claude). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-622/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-622/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e3fd8b0753aab3be5adacc84c740465f62ffa290 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-622/tests/oracle.patch @@ -0,0 +1,492 @@ +diff --git a/runtime/syscalls/sys_event.c b/runtime/syscalls/sys_event.c +index adabcc56..9153a475 100644 +--- a/runtime/syscalls/sys_event.c ++++ b/runtime/syscalls/sys_event.c +@@ -85,6 +85,21 @@ static uint64_t bswap64(uint64_t v) + #endif + } + ++#ifdef _WIN32 ++/* Milliseconds left to a lv2_usec_deadline() deadline, rounded UP (a timed ++ * receive must not return before the guest's timeout); 0 once it has passed. */ ++static DWORD evt_ms_until(int64_t deadline) ++{ ++ LARGE_INTEGER f, now; ++ QueryPerformanceFrequency(&f); ++ QueryPerformanceCounter(&now); ++ if (now.QuadPart >= deadline) return 0; ++ const uint64_t left = (uint64_t)(deadline - now.QuadPart), q = (uint64_t)f.QuadPart; ++ const uint64_t ms = (left / q) * 1000ull + ((left % q) * 1000ull + q - 1) / q; ++ return ms >= (uint64_t)INFINITE ? (DWORD)(INFINITE - 1) : (DWORD)ms; ++} ++#endif ++ + /* ========================================================================= + * EVENT QUEUES + * ========================================================================= */ +@@ -217,9 +232,13 @@ int64_t sys_event_queue_create(ppu_context* ctx) + int64_t sys_event_queue_destroy(ppu_context* ctx) + { + uint32_t queue_id = LV2_ARG_U32(ctx, 0); ++ /* r4 = mode: 0, or SYS_EVENT_QUEUE_DESTROY_FORCE. It was ignored. */ ++ int32_t mode = LV2_ARG_S32(ctx, 1); + + if (queue_id == 0 || queue_id > SYS_EVENT_QUEUE_MAX) + return getenv("YDKJ_EVT_LENIENT") ? CELL_OK : (int64_t)(int32_t)CELL_ESRCH; /* idempotent teardown */ ++ if (mode != 0 && mode != SYS_EVENT_QUEUE_DESTROY_FORCE) ++ return (int64_t)(int32_t)CELL_EINVAL; + + evt_table_lock(); + +@@ -229,14 +248,52 @@ int64_t sys_event_queue_destroy(ppu_context* ctx) + return getenv("YDKJ_EVT_LENIENT") ? CELL_OK : (int64_t)(int32_t)CELL_ESRCH; /* idempotent teardown */ + } + ++ /* Receivers blocked in the queue. This used to delete the lock and ++ * condition variable under them: a receiver parked with no timeout never ++ * woke again. lv2: a plain destroy with waiters is EBUSY; FORCE wakes every ++ * waiter with CELL_ECANCELED. The lock and condition variable are ++ * deliberately NOT destroyed: a receiver that passed its unlocked `active` ++ * test just before this can still enter them safely and will see !active, ++ * and create re-initialises them when the slot is reused. */ + #ifdef _WIN32 +- DeleteCriticalSection(&q->lock); ++ EnterCriticalSection(&q->lock); ++ if (q->waiters > 0 && mode != SYS_EVENT_QUEUE_DESTROY_FORCE) { ++ LeaveCriticalSection(&q->lock); ++ evt_table_unlock(); ++ return (int64_t)(int32_t)CELL_EBUSY; ++ } ++ q->active = 0; ++ WakeAllConditionVariable(&q->not_empty); ++ while (q->waiters > 0) { /* let them return ECANCELED first */ ++ LeaveCriticalSection(&q->lock); ++ SwitchToThread(); ++ EnterCriticalSection(&q->lock); ++ } ++ LeaveCriticalSection(&q->lock); + #else +- pthread_cond_destroy(&q->not_empty); +- pthread_mutex_destroy(&q->lock); ++ pthread_mutex_lock(&q->lock); ++ if (q->waiters > 0 && mode != SYS_EVENT_QUEUE_DESTROY_FORCE) { ++ pthread_mutex_unlock(&q->lock); ++ evt_table_unlock(); ++ return (int64_t)(int32_t)CELL_EBUSY; ++ } ++ q->active = 0; ++ pthread_cond_broadcast(&q->not_empty); ++ while (q->waiters > 0) { ++ pthread_mutex_unlock(&q->lock); ++ sched_yield(); ++ pthread_mutex_lock(&q->lock); ++ } ++ pthread_mutex_unlock(&q->lock); + #endif + +- q->active = 0; ++ /* Ports still wired to this queue are now unconnected: a send answers ++ * ENOTCONN, and the stale index can no longer deliver into whatever queue ++ * next reuses this slot. */ ++ for (int i = 0; i < SYS_EVENT_PORT_MAX; i++) ++ if (g_sys_event_ports[i].active && g_sys_event_ports[i].connected_queue == (int32_t)queue_id) ++ g_sys_event_ports[i].connected_queue = 0; ++ + evt_table_unlock(); + return CELL_OK; + } +@@ -477,6 +534,13 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + + #ifdef _WIN32 + EnterCriticalSection(&q->lock); ++ if (!q->active) { /* destroyed since the unlocked test */ ++ LeaveCriticalSection(&q->lock); ++ return (int64_t)(int32_t)CELL_ESRCH; ++ } ++ /* Counted while inside (every return below gives it back): destroy needs it ++ * for its EBUSY / FORCE decision and to know when we are out. */ ++ q->waiters++; + + /* EVT_RECV_KICK=<qid>:<ms>: an infinite wait on that queue that sees + * nothing for <ms> gets the last event pushed to the queue re-delivered. +@@ -490,6 +554,7 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + while (q->count == 0 && q->active && !q->cancelled) { + if (!SleepConditionVariableCS(&q->not_empty, &q->lock, s_kms) && q->count == 0) { + sys_event_t evt = s_last_evt[queue_id - 1]; ++ q->waiters--; + LeaveCriticalSection(&q->lock); + { static int n = 0; if (n++ < 16) + fprintf(stderr, "[evt] EVT_RECV_KICK: q=%u idle %lu ms -> re-delivered last event\n", +@@ -510,6 +575,7 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + SleepConditionVariableCS(&q->not_empty, &q->lock, INFINITE); + } + if (q->count == 0 && q->cancelled) { ++ q->waiters--; + LeaveCriticalSection(&q->lock); + return (int64_t)(int32_t)CELL_ECANCELED; + } +@@ -522,26 +588,45 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + * return ETIMEDOUT immediately if empty -- same result the game already + * handles, just without the bogus 15ms stall. */ + if (q->count == 0 || !q->active) { ++ q->waiters--; + LeaveCriticalSection(&q->lock); + return (int64_t)(int32_t)CELL_ETIMEDOUT; + } + } else { +- DWORD ms = (DWORD)(timeout_us / 1000); ++ /* Wait to an absolute deadline. A fixed `timeout_us / 1000` per wait ++ * truncated (1500 us became 1 ms) and restarted the FULL timeout after ++ * every wake that found the queue empty (another receiver took the ++ * event), so a contended timed receive could overrun without bound. ++ * The slice is rounded up, so it never returns before the guest's ++ * timeout, and an event that lands right at the deadline is still ++ * taken (the loop re-tests the count before giving up). Past 2^40 us ++ * (12.7 days) the QPC arithmetic would wrap; that is forever anyway. */ ++ const int64_t deadline = lv2_usec_deadline(timeout_us < (1ull << 40) ? timeout_us : (1ull << 40)); + while (q->count == 0 && q->active && !q->cancelled) { +- if (!SleepConditionVariableCS(&q->not_empty, &q->lock, ms)) { +- if (GetLastError() == ERROR_TIMEOUT) { +- LeaveCriticalSection(&q->lock); +- return (int64_t)(int32_t)CELL_ETIMEDOUT; +- } ++ const DWORD ms = evt_ms_until(deadline); ++ if (ms == 0) { ++ q->waiters--; ++ LeaveCriticalSection(&q->lock); ++ return (int64_t)(int32_t)CELL_ETIMEDOUT; + } ++ SleepConditionVariableCS(&q->not_empty, &q->lock, ms); + } + } + ++ if (!q->active) { ++ /* Destroyed with SYS_EVENT_QUEUE_DESTROY_FORCE while we waited: lv2 ++ * hands every waiter CELL_ECANCELED. */ ++ q->waiters--; ++ LeaveCriticalSection(&q->lock); ++ return (int64_t)(int32_t)CELL_ECANCELED; ++ } + if (q->count == 0 && q->cancelled) { ++ q->waiters--; + LeaveCriticalSection(&q->lock); + return (int64_t)(int32_t)CELL_ECANCELED; + } +- if (!q->active || q->count == 0) { ++ if (q->count == 0) { ++ q->waiters--; + LeaveCriticalSection(&q->lock); + return (int64_t)(int32_t)CELL_ESRCH; + } +@@ -550,9 +635,15 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + q->head = (q->head + 1) % q->capacity; + q->count--; + ++ q->waiters--; + LeaveCriticalSection(&q->lock); + #else + pthread_mutex_lock(&q->lock); ++ if (!q->active) { /* destroyed since the unlocked test */ ++ pthread_mutex_unlock(&q->lock); ++ return (int64_t)(int32_t)CELL_ESRCH; ++ } ++ q->waiters++; /* see the _WIN32 branch */ + + if (timeout_us == 0) { + while (q->count == 0 && q->active && !q->cancelled) { +@@ -569,18 +660,26 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + } + while (q->count == 0 && q->active && !q->cancelled) { + int rc = pthread_cond_timedwait(&q->not_empty, &q->lock, &ts); +- if (rc == ETIMEDOUT) { ++ if (rc == ETIMEDOUT && q->count == 0) { ++ q->waiters--; + pthread_mutex_unlock(&q->lock); + return (int64_t)(int32_t)CELL_ETIMEDOUT; + } + } + } + ++ if (!q->active) { /* FORCE-destroyed while waiting */ ++ q->waiters--; ++ pthread_mutex_unlock(&q->lock); ++ return (int64_t)(int32_t)CELL_ECANCELED; ++ } + if (q->count == 0 && q->cancelled) { ++ q->waiters--; + pthread_mutex_unlock(&q->lock); + return (int64_t)(int32_t)CELL_ECANCELED; + } +- if (!q->active || q->count == 0) { ++ if (q->count == 0) { ++ q->waiters--; + pthread_mutex_unlock(&q->lock); + return (int64_t)(int32_t)CELL_ESRCH; + } +@@ -589,6 +688,7 @@ int64_t sys_event_queue_receive(ppu_context* ctx) + q->head = (q->head + 1) % q->capacity; + q->count--; + ++ q->waiters--; + pthread_mutex_unlock(&q->lock); + #endif + +diff --git a/runtime/syscalls/sys_event.h b/runtime/syscalls/sys_event.h +index 14c64255..1407bd7f 100644 +--- a/runtime/syscalls/sys_event.h ++++ b/runtime/syscalls/sys_event.h +@@ -65,6 +65,12 @@ typedef struct sys_event_queue_info { + * arrive; later receives fail the same way rather than re-blocking. */ + int cancelled; + ++ /* Receivers currently inside sys_event_queue_receive's locked section (under ++ * `lock`). sys_event_queue_destroy needs it: lv2 answers EBUSY to a plain ++ * destroy while receivers wait, and a FORCE destroy wakes them with ++ * ECANCELED and has to let them leave before the slot can be reused. */ ++ int waiters; ++ + #ifdef _WIN32 + CRITICAL_SECTION lock; + CONDITION_VARIABLE not_empty; +@@ -75,6 +81,9 @@ typedef struct sys_event_queue_info { + + } sys_event_queue_info; + ++/* sys_event_queue_destroy's mode argument. */ ++#define SYS_EVENT_QUEUE_DESTROY_FORCE 1 ++ + extern sys_event_queue_info g_sys_event_queues[SYS_EVENT_QUEUE_MAX]; + + /* --------------------------------------------------------------------------- +diff --git a/tests/sync_stress/CMakeLists.txt b/tests/sync_stress/CMakeLists.txt +index 455ce7a1..19f20713 100644 +--- a/tests/sync_stress/CMakeLists.txt ++++ b/tests/sync_stress/CMakeLists.txt +@@ -138,3 +138,27 @@ if(WIN32) + set_tests_properties(cond_${mode} PROPERTIES TIMEOUT 10) + endforeach() + endif() ++ ++# sys_event_queue_destroy modes (EINVAL / EBUSY / FORCE -> ECANCELED), ports ++# disconnected from a destroyed queue, and the absolute deadline of a timed ++# receive. Links sys_event.c alone. ++add_executable(test_event_queue_destroy ++ test_event_queue_destroy.c test_shims.c ++ "${RUNTIME_SYNC_DIR}/sys_event.c") ++if(NOT WIN32) ++ target_sources(test_event_queue_destroy PRIVATE ++ "${PS3RECOMP_TREE_ROOT}/runtime/platform/win32_compat.c") ++ find_package(Threads REQUIRED) ++ target_link_libraries(test_event_queue_destroy PRIVATE Threads::Threads) ++endif() ++target_include_directories(test_event_queue_destroy PRIVATE ++ "${PS3RECOMP_TREE_ROOT}" "${PS3RECOMP_TREE_ROOT}/include" ++ "${RUNTIME_SYNC_DIR}" "${PS3RECOMP_TREE_ROOT}/runtime") ++if(MSVC) ++ target_compile_definitions(test_event_queue_destroy PRIVATE _CRT_SECURE_NO_WARNINGS) ++ target_compile_options(test_event_queue_destroy PRIVATE /experimental:c11atomics) ++else() ++ target_compile_options(test_event_queue_destroy PRIVATE -Wall -Wextra -Wno-unused-parameter) ++endif() ++add_test(NAME event_queue_destroy COMMAND test_event_queue_destroy) ++set_tests_properties(event_queue_destroy PROPERTIES LABELS "runtime;sync" TIMEOUT 60) +diff --git a/tests/sync_stress/test_event_queue_destroy.c b/tests/sync_stress/test_event_queue_destroy.c +new file mode 100644 +index 00000000..3c301759 +--- /dev/null ++++ b/tests/sync_stress/test_event_queue_destroy.c +@@ -0,0 +1,194 @@ ++/* sys_event_queue_destroy and timed receive. ++ * ++ * - mode is honoured: an unknown mode is EINVAL; a plain destroy while a ++ * receiver is blocked is EBUSY and leaves that receiver blocked; a FORCE ++ * destroy returns every blocked receiver CELL_ECANCELED. The lock was ++ * deleted under a receiver parked with no timeout, which then never woke. ++ * - ports connected to a destroyed queue are disconnected (send is ENOTCONN), ++ * so a send cannot land in whatever queue next reuses the slot. ++ * - a timed receive runs to an absolute deadline: wake-ups that find the queue ++ * empty do not restart the timeout. ++ * ++ * Win32 host threads, through the shim off Windows. Links sys_event.c and ++ * test_shims.c only. */ ++#include "runtime/platform/win32_compat.h" ++#include "runtime/syscalls/sys_event.h" ++#include <stdio.h> ++#include <stdlib.h> ++#include <string.h> ++ ++uint8_t* vm_base; ++ ++/* sys_event.c's title-diagnostic side paths reach for these; none can run here. */ ++size_t spu_elf_image_size(const uint8_t* image, size_t max_avail) { (void)image; (void)max_avail; return 0; } ++int spu_workload_dispatch_async(const uint8_t* image, uint32_t image_size, uint32_t args_ea) ++{ (void)image; (void)image_size; (void)args_ea; return 0; } ++void ppu_dump_guest_stack(ppu_context* ctx, const char* tag) { (void)ctx; (void)tag; } ++uint32_t yz_thread_current_id(void) { return 0; } ++ ++static int failures; ++#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #x); failures++; } } while (0) ++#define CHECK_RC(call, want) do { int32_t _rc = (int32_t)(call); \ ++ if (_rc != (int32_t)(want)) { fprintf(stderr, "FAIL line %d: %s -> 0x%08X, want 0x%08X\n", \ ++ __LINE__, #call, (unsigned)_rc, (unsigned)(want)); failures++; } } while (0) ++ ++typedef int64_t (*sc_fn)(ppu_context*); ++static int32_t call(sc_fn f, uint32_t tid, uint64_t a, uint64_t b, uint64_t c, uint64_t d) ++{ ++ ppu_context ctx; ++ memset(&ctx, 0, sizeof ctx); ++ ctx.thread_id = tid; ++ ctx.gpr[3] = a; ctx.gpr[4] = b; ctx.gpr[5] = c; ctx.gpr[6] = d; ++ return (int32_t)f(&ctx); ++} ++static uint32_t be_read(unsigned off) ++{ ++ const uint8_t* p = vm_base + off; ++ return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3]; ++} ++static double now_ms(void) ++{ ++ LARGE_INTEGER f, c; ++ QueryPerformanceFrequency(&f); ++ QueryPerformanceCounter(&c); ++ return (double)c.QuadPart * 1000.0 / (double)f.QuadPart; ++} ++ ++typedef struct recv { ++ uint32_t q; ++ uint64_t timeout_us; ++ uint32_t event_at; ++ volatile int32_t rc; ++ double ms; ++ HANDLE h; ++} recv_t; ++static DWORD WINAPI recv_main(void* p) ++{ ++ recv_t* r = (recv_t*)p; ++ const double t0 = now_ms(); ++ r->rc = call(sys_event_queue_receive, 2, r->q, r->event_at, r->timeout_us, 0); ++ r->ms = now_ms() - t0; ++ return 0; ++} ++static void recv_start(recv_t* r, uint32_t q, uint64_t timeout_us, uint32_t event_at) ++{ ++ r->q = q; r->timeout_us = timeout_us; r->event_at = event_at; r->rc = -1; r->ms = 0; ++ r->h = CreateThread(NULL, 0, recv_main, r, 0, NULL); ++} ++static void recv_join(recv_t* r) { WaitForSingleObject(r->h, 20000); CloseHandle(r->h); } ++ ++static uint32_t make_queue(void) ++{ ++ CHECK_RC(call(sys_event_queue_create, 1, 0x200, 0, 0x1234, 8), CELL_OK); ++ return be_read(0x200); ++} ++/* Wait until `n` receivers are inside the queue. */ ++static void wait_waiters(uint32_t q, int n) ++{ ++ for (int i = 0; i < 3000 && g_sys_event_queues[q - 1].waiters != n; i++) Sleep(1); ++ CHECK(g_sys_event_queues[q - 1].waiters == n); ++} ++ ++static void test_destroy_modes(void) ++{ ++ uint32_t q = make_queue(); ++ CHECK_RC(call(sys_event_queue_destroy, 1, q, 7, 0, 0), CELL_EINVAL); ++ CHECK(g_sys_event_queues[q - 1].active); ++ ++ /* A port wired to the queue. */ ++ CHECK_RC(call(sys_event_port_create, 1, 0x210, SYS_EVENT_PORT_LOCAL, 0, 0), CELL_OK); ++ const uint32_t port = be_read(0x210); ++ CHECK_RC(call(sys_event_port_connect_local, 1, port, q, 0, 0), CELL_OK); ++ CHECK_RC(call(sys_event_port_send, 1, port, 1, 2, 3), CELL_OK); /* queued */ ++ ++ /* Two receivers: the first takes the queued event, then both block. */ ++ recv_t r1, r2; ++ recv_start(&r1, q, 0, 0x300); ++ recv_join(&r1); ++ CHECK(r1.rc == CELL_OK); ++ recv_start(&r1, q, 0, 0x300); ++ recv_start(&r2, q, 0, 0x340); ++ wait_waiters(q, 2); ++ ++ /* A plain destroy refuses and leaves them blocked. */ ++ CHECK_RC(call(sys_event_queue_destroy, 1, q, 0, 0, 0), CELL_EBUSY); ++ CHECK(g_sys_event_queues[q - 1].active); ++ Sleep(50); ++ CHECK(r1.rc == -1 && r2.rc == -1); ++ ++ /* FORCE wakes both with ECANCELED. */ ++ CHECK_RC(call(sys_event_queue_destroy, 1, q, SYS_EVENT_QUEUE_DESTROY_FORCE, 0, 0), CELL_OK); ++ recv_join(&r1); recv_join(&r2); ++ CHECK(r1.rc == (int32_t)CELL_ECANCELED); ++ CHECK(r2.rc == (int32_t)CELL_ECANCELED); ++ CHECK(!g_sys_event_queues[q - 1].active); ++ ++ /* The port no longer points at the dead queue, and a new queue in that slot ++ * does not receive from it. */ ++ CHECK_RC(call(sys_event_port_send, 1, port, 1, 2, 3), CELL_ENOTCONN); ++ const uint32_t q2 = make_queue(); ++ CHECK(q2 == q); /* the slot is reused */ ++ CHECK_RC(call(sys_event_port_send, 1, port, 1, 2, 3), CELL_ENOTCONN); ++ CHECK(g_sys_event_queues[q2 - 1].count == 0); ++ CHECK_RC(call(sys_event_queue_receive, 1, q2, 0x300, 1000, 0), CELL_ETIMEDOUT); ++ ++ /* Idle: a plain destroy works, and a second one is ESRCH. */ ++ CHECK_RC(call(sys_event_queue_destroy, 1, q2, 0, 0, 0), CELL_OK); ++ CHECK_RC(call(sys_event_queue_destroy, 1, q2, 0, 0, 0), CELL_ESRCH); ++ CHECK_RC(call(sys_event_port_destroy, 1, port, 0, 0, 0), CELL_OK); ++} ++ ++/* Spurious wake-ups (a broadcast that finds the queue empty) every 25 ms. */ ++static volatile int s_stop_wakes; ++static uint32_t s_wake_q; ++static DWORD WINAPI waker(void* unused) ++{ ++ (void)unused; ++ while (!s_stop_wakes) { ++ Sleep(25); ++ sys_event_queue_info* q = &g_sys_event_queues[s_wake_q - 1]; ++#ifdef _WIN32 ++ WakeAllConditionVariable(&q->not_empty); ++#else ++ pthread_cond_broadcast(&q->not_empty); ++#endif ++ } ++ return 0; ++} ++ ++static void test_timed_receive(void) ++{ ++ const uint32_t q = make_queue(); ++ ++ /* Plain timeout: not early, not wildly late. */ ++ recv_t r; ++ recv_start(&r, q, 60000, 0x300); ++ recv_join(&r); ++ CHECK(r.rc == (int32_t)CELL_ETIMEDOUT); ++ CHECK(r.ms >= 55.0 && r.ms < 500.0); ++ ++ /* A wake-up that finds nothing must not restart the timeout: with one every ++ * 25 ms, a 120 ms receive still ends at about 120 ms (it used to start its ++ * full wait over after each wake, and so never ended). */ ++ s_wake_q = q; s_stop_wakes = 0; ++ HANDLE w = CreateThread(NULL, 0, waker, NULL, 0, NULL); ++ recv_start(&r, q, 120000, 0x300); ++ recv_join(&r); ++ s_stop_wakes = 1; ++ WaitForSingleObject(w, 5000); CloseHandle(w); ++ printf("timed receive 120 ms with a wake every 25 ms: rc 0x%08X after %.1f ms\n", (unsigned)r.rc, r.ms); ++ CHECK(r.rc == (int32_t)CELL_ETIMEDOUT); ++ CHECK(r.ms >= 110.0 && r.ms < 400.0); ++ ++ CHECK_RC(call(sys_event_queue_destroy, 1, q, 0, 0, 0), CELL_OK); ++} ++ ++int main(void) ++{ ++ vm_base = (uint8_t*)calloc(1, 65536); ++ if (!vm_base) return 2; ++ test_destroy_modes(); ++ test_timed_receive(); ++ printf("event queue destroy / timed receive: %s\n", failures ? "FAIL" : "PASS"); ++ return failures ? 1 : 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-622/tests/test.sh b/tasks/sp00nznet__ps3recomp-622/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-622/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-622/tests/verifier.py b/tasks/sp00nznet__ps3recomp-622/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-622/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-623/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-623/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-623/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-623/instruction.md b/tasks/sp00nznet__ps3recomp-623/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c4a1ec5778445350cb37ab3e8eb97d3c15f96053 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-623/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** sys_ppu_thread: Windows join no longer frees the slot under the exiting thread + +## Description + +On Windows, `sys_ppu_thread_exit` signals `finish_event` from inside the thread body, and the thread then still runs the host thread epilogue. The joiner woke at the signal, freed the slot and closed the handles. The epilogue then wrote to the closed handle and set the slot it had just freed back to FINISHED, where it stayed. The thread table lost a slot per join, so a title that joins short-lived workers runs out of ids. + +1. `sys_ppu_thread_join`, and `sys_ppu_thread_detach` of an already-finished thread, now wait for the host thread to end before freeing the slot, as `pthread_join` already does on POSIX. The wait is bounded at 5 s so a thread kept running past its exit (`PS3_NO_THREAD_EXIT_UNWIND=1`) can't hang the joiner. Detach releases the table lock while it waits, because the epilogue takes it. +2. Joining yourself is EDEADLK (it waited on its own finish event forever). A second joiner of the same thread is EINVAL, through a new `joining` flag, instead of both waiting and both freeing the slot. + +Test: `tests/syscalls/test_ppu_thread_join.c`, a new ctest target. It includes `sys_ppu_thread.c` and runs real host threads through a trampoline that returns, exits or waits on a gate. It does 200 create/exit/join rounds and checks each exit status and that no slot is left behind, then detaches 100 finished threads, then covers self-join and a second joiner. On master it fails from the first round (wrong statuses, then EAGAIN as the table fills). + +Tested on Windows 11 with clang-cl: the full ctest passes (master's 21 plus this test), and the new test passed 15 of 15 repeated runs. I haven't run a POSIX build. The race is Windows-only, but the EDEADLK and EINVAL results apply everywhere. `test_ppu_thread_slots.py` is POSIX-only, so I couldn't run it. + +Already on master, so not included: non-joinable threads freeing their own slot (#415 and later). + +This is original code, written against the current file; no RPCS3 or other GPL code was used. It comes from the [Project 8 Plus](https://github.com/MaxLeiter/project-8-plus) port and was developed with AI assistance (Claude). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-623/solution/patch.diff b/tasks/sp00nznet__ps3recomp-623/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7fee288ab8e478750cca25762095a8237aa759f6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-623/solution/patch.diff @@ -0,0 +1,274 @@ +diff --git a/runtime/syscalls/sys_ppu_thread.c b/runtime/syscalls/sys_ppu_thread.c +index 41d5721c..3404faf9 100644 +--- a/runtime/syscalls/sys_ppu_thread.c ++++ b/runtime/syscalls/sys_ppu_thread.c +@@ -662,21 +662,43 @@ int64_t sys_ppu_thread_join(ppu_context* ctx) + { static int n=0; if(PS3_LOG_FIRST(n, 30)) fprintf(stderr,"[WAIT] ppu_thread_join(tid=%llu)\n", (unsigned long long)tid); } + ppu_thread_note_block(ctx->thread_id); /* PS3_PRIO_START */ + ++ /* Joining yourself is EDEADLK (it used to wait on its own finish event ++ * for good). */ ++ if (tid == ctx->thread_id) ++ return (int64_t)(int32_t)CELL_EDEADLK; ++ + table_lock(); + ppu_thread_info* t = find_thread(tid); + if (!t) { + table_unlock(); + return (int64_t)(int32_t)CELL_ESRCH; + } +- if (!t->joinable || t->state == PPU_THREAD_STATE_DETACHED) { ++ /* A thread has one joiner: a second one gets EINVAL instead of both ++ * waiting, both closing the same handles and both freeing the slot. */ ++ if (!t->joinable || t->joining || t->state == PPU_THREAD_STATE_DETACHED) { + table_unlock(); + return (int64_t)(int32_t)CELL_EINVAL; + } ++ t->joining = 1; + table_unlock(); + + /* Wait for completion */ + #ifdef _WIN32 + WaitForSingleObject(t->finish_event, INFINITE); ++ /* sys_ppu_thread_exit signals finish_event from INSIDE the thread, which ++ * then still unwinds through ppu_host_thread_proc's epilogue, touching the ++ * slot (it stamps the state and signals the event again). Freeing the slot ++ * and closing the handles before that finished let the epilogue write to ++ * a closed handle and put a slot this join had freed back to FINISHED, so ++ * it never came back. Wait for the host thread itself first, as ++ * pthread_join does below. Bounded, so that a thread kept running past its ++ * exit (PS3_NO_THREAD_EXIT_UNWIND=1) cannot hang the joiner. */ ++ if (t->host_thread && WaitForSingleObject(t->host_thread, 5000) == WAIT_TIMEOUT) { ++ static int s_warned = 0; ++ if (s_warned++ < 4) ++ fprintf(stderr, "[SYS] ppu_thread_join(tid=%llu): host thread still running 5 s " ++ "after exit -- freeing the slot anyway\n", (unsigned long long)tid); ++ } + #else + pthread_mutex_lock(&t->finish_mutex); + while (!t->finished) { +@@ -759,8 +781,22 @@ int64_t sys_ppu_thread_detach(ppu_context* ctx) + if (t->state == PPU_THREAD_STATE_FINISHED) { + /* Already finished, free it */ + #ifdef _WIN32 ++ /* FINISHED is set by sys_ppu_thread_exit while the host thread still has ++ * its epilogue to run (it takes the table lock): let it end before the ++ * slot is freed, with the lock released while waiting, as in join. */ ++ HANDLE h = t->host_thread; ++ t->joining = 1; /* nobody joins it meanwhile */ ++ table_unlock(); ++ if (h) WaitForSingleObject(h, 5000); ++ table_lock(); ++ if (t->state != PPU_THREAD_STATE_FINISHED || t->host_thread != h) { ++ table_unlock(); /* freed or reused in the meantime */ ++ return CELL_OK; ++ } + CloseHandle(t->host_thread); + CloseHandle(t->finish_event); ++ t->host_thread = NULL; ++ t->finish_event = NULL; + #else + pthread_detach(t->host_thread); + pthread_mutex_destroy(&t->finish_mutex); +diff --git a/runtime/syscalls/sys_ppu_thread.h b/runtime/syscalls/sys_ppu_thread.h +index 633446e0..039264d3 100644 +--- a/runtime/syscalls/sys_ppu_thread.h ++++ b/runtime/syscalls/sys_ppu_thread.h +@@ -47,6 +47,7 @@ typedef struct ppu_thread_info { + int32_t priority; + int64_t exit_status; + int joinable; ++ int joining; /* a sys_ppu_thread_join is in progress: a second joiner is EINVAL */ + uint32_t stack_addr; /* guest stack base */ + uint32_t stack_size; + uint64_t entry_addr; /* guest entry point */ +diff --git a/tests/syscalls/CMakeLists.txt b/tests/syscalls/CMakeLists.txt +index c0ab35b9..bd54d2a1 100644 +--- a/tests/syscalls/CMakeLists.txt ++++ b/tests/syscalls/CMakeLists.txt +@@ -48,3 +48,24 @@ set_tests_properties(lock_line PROPERTIES + LABELS "runtime;syscalls" + TIMEOUT 30 + ) ++ ++# sys_ppu_thread_join / detach through the real sys_ppu_thread.c with host ++# threads: the slot a join frees stays free (Windows), self-join, second joiner. ++add_executable(test_ppu_thread_join test_ppu_thread_join.c) ++target_include_directories(test_ppu_thread_join PRIVATE ++ "${PS3RECOMP_ROOT}/runtime/syscalls" ++ "${PS3RECOMP_ROOT}/runtime" ++ "${PS3RECOMP_ROOT}/include" ++) ++if(MSVC) ++ target_compile_definitions(test_ppu_thread_join PRIVATE _CRT_SECURE_NO_WARNINGS) ++else() ++ target_compile_options(test_ppu_thread_join PRIVATE -Wall -Wextra -Wno-unused-parameter -UNDEBUG) ++ find_package(Threads REQUIRED) ++ target_link_libraries(test_ppu_thread_join PRIVATE Threads::Threads) ++endif() ++add_test(NAME ppu_thread_join COMMAND test_ppu_thread_join) ++set_tests_properties(ppu_thread_join PROPERTIES ++ LABELS "runtime;syscalls" ++ TIMEOUT 120 ++) +diff --git a/tests/syscalls/test_ppu_thread_join.c b/tests/syscalls/test_ppu_thread_join.c +new file mode 100644 +index 00000000..e410b957 +--- /dev/null ++++ b/tests/syscalls/test_ppu_thread_join.c +@@ -0,0 +1,155 @@ ++/* sys_ppu_thread_join / detach through the real sys_ppu_thread.c, with real host threads. ++ * ++ * - A thread that ends in sys_ppu_thread_exit signals its joiner from inside the thread body and then still unwinds ++ * through the host thread's epilogue. On Windows the joiner freed the slot and closed the handles at once; the ++ * epilogue then wrote to the closed handle and put the slot it had just freed back to FINISHED, where it stayed ++ * for good. The join now waits for the host thread to end first, so after a join (and after a detach of a ++ * finished thread) the slot is FREE and stays FREE. ++ * - Joining yourself is EDEADLK; a second joiner of the same thread is EINVAL. ++ * ++ * The guest entry is a trampoline that exits, returns, or waits for a gate, by its argument. */ ++#include "../../runtime/syscalls/sys_ppu_thread.c" ++#include <assert.h> ++ ++uint8_t* vm_base; ++uint32_t ppu_vm_size = 0x10000; ++uint32_t vm_read32(uint64_t a) /* guest words are big-endian (sys_ppu_thread_yield peeks at some) */ ++{ ++ const uint8_t* p = vm_base + (uint32_t)a; ++ return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3]; ++} ++void ppu_resv_register(ppu_context* c) { (void)c; } ++int ps3_intr_is_handler(unsigned long long tid) { (void)tid; return 0; } ++int ps3_intr_wait(unsigned long long tid) { (void)tid; return 0; } ++ ++enum { ARG_RETURN = 0, ARG_EXIT = 1, ARG_GATED = 2 }; ++static volatile int s_gate; /* a gated thread returns once this is set */ ++ ++static void guest_entry(ppu_context* ctx) ++{ ++ switch ((int)ctx->gpr[3]) { ++ case ARG_EXIT: ++ ctx->gpr[3] = 9; /* exit status */ ++ sys_ppu_thread_exit(ctx); /* does not return when the unwind is armed */ ++ break; ++ case ARG_GATED: ++ while (!s_gate) Sleep(1); ++ ctx->gpr[3] = 3; ++ break; ++ default: ++ ctx->gpr[3] = 5; ++ break; ++ } ++} ++ ++static int g_fails; ++#define EXPECT_EQ(got, want) do { long long g_ = (long long)(got), w_ = (long long)(want); if (g_ != w_) { g_fails++; \ ++ fprintf(stderr, "FAIL line %d: %s = 0x%llX, want 0x%llX\n", __LINE__, #got, g_, w_); } } while (0) ++ ++static int64_t create(uint64_t flags, uint64_t arg, uint64_t* tid) ++{ ++ ppu_context ctx; memset(&ctx, 0, sizeof(ctx)); ++ ctx.gpr[3] = 0x100; /* tid out */ ++ ctx.gpr[4] = 0x10000; /* entry */ ++ ctx.gpr[5] = arg; ++ ctx.gpr[6] = 1000; /* priority */ ++ ctx.gpr[7] = 0x10000; /* stack size */ ++ ctx.gpr[8] = flags; ++ ctx.gpr[9] = 0; /* name */ ++ int64_t rc = sys_ppu_thread_create(&ctx); ++ if (rc == 0 && tid) { uint64_t be; memcpy(&be, vm_base + 0x100, 8); *tid = __builtin_bswap64(be); } ++ return rc; ++} ++static int64_t join_as(uint64_t caller, uint64_t tid, int64_t* status) ++{ ++ ppu_context ctx; memset(&ctx, 0, sizeof(ctx)); ++ ctx.thread_id = caller; ++ ctx.gpr[3] = tid; ctx.gpr[4] = 0x200; ++ int64_t rc = sys_ppu_thread_join(&ctx); ++ if (rc == 0 && status) { uint64_t be; memcpy(&be, vm_base + 0x200, 8); *status = (int64_t)__builtin_bswap64(be); } ++ return rc; ++} ++static int64_t detach(uint64_t tid) ++{ ++ ppu_context ctx; memset(&ctx, 0, sizeof(ctx)); ++ ctx.gpr[3] = tid; ++ return sys_ppu_thread_detach(&ctx); ++} ++static int slot_state(uint64_t tid) { table_lock(); int s = g_ppu_threads[tid - 1].state; table_unlock(); return s; } ++static int used_slots(void) /* slots other than main that are not FREE */ ++{ ++ int n = 0; ++ table_lock(); ++ for (int i = 1; i < PPU_THREAD_MAX; i++) if (g_ppu_threads[i].state != PPU_THREAD_STATE_FREE) n++; ++ table_unlock(); ++ return n; ++} ++static void wait_state(uint64_t tid, int want) ++{ ++ for (int i = 0; i < 5000 && slot_state(tid) != want; i++) Sleep(1); ++} ++ ++typedef struct { uint64_t caller, tid; int64_t rc, status; } bgjoin_t; ++static DWORD WINAPI bgjoin_main(LPVOID p) ++{ ++ bgjoin_t* b = (bgjoin_t*)p; ++ b->rc = join_as(b->caller, b->tid, &b->status); ++ return 0; ++} ++ ++int main(void) ++{ ++ vm_base = (uint8_t*)calloc(1, 0x10000); assert(vm_base); ++ g_vm_stack_alloc.next_addr = 0x10000000u; /* the guest stack region the threads bump-allocate from */ ++ g_vm_stack_alloc.region_end = 0xA0000000u; ++ g_ppu_thread_entry_trampoline = guest_entry; ++ ppu_thread_register_main(); ++ ++ /* 1. Create / exit / join, over and over: every join returns the exit status and leaves its slot FREE for good. ++ * The slot table has 64 entries and is searched next-fit, so 200 rounds reuse every slot several times. */ ++ for (int i = 0; i < 200; i++) { ++ uint64_t tid = 0; int64_t status = 0; ++ EXPECT_EQ(create(1, (i & 1) ? ARG_EXIT : ARG_RETURN, &tid), 0); ++ EXPECT_EQ(join_as(1, tid, &status), 0); ++ EXPECT_EQ(status, (i & 1) ? 9 : 5); ++ Sleep(0); /* give a late epilogue its chance to misbehave */ ++ } ++ Sleep(50); ++ EXPECT_EQ(used_slots(), 0); /* nothing resurrected as FINISHED */ ++ ++ /* 2. Detaching a thread that has exited: the slot is freed and stays free. */ ++ for (int i = 0; i < 100; i++) { ++ uint64_t tid = 0; ++ EXPECT_EQ(create(1, ARG_EXIT, &tid), 0); ++ wait_state(tid, PPU_THREAD_STATE_FINISHED); ++ EXPECT_EQ(detach(tid), 0); ++ } ++ Sleep(50); ++ EXPECT_EQ(used_slots(), 0); ++ ++ /* 3. Self-join and a second joiner. */ ++ { ++ uint64_t tid = 0; int64_t status = 0; ++ s_gate = 0; ++ EXPECT_EQ(create(1, ARG_GATED, &tid), 0); ++ EXPECT_EQ(join_as(tid, tid, &status), (int64_t)(int32_t)CELL_EDEADLK); /* the thread joining itself */ ++ bgjoin_t b = { 1, tid, -1, 0 }; ++ HANDLE h = CreateThread(NULL, 0, bgjoin_main, &b, 0, NULL); ++ for (int i = 0; i < 5000; i++) { ++ table_lock(); int joining = g_ppu_threads[tid - 1].joining; table_unlock(); ++ if (joining) break; ++ Sleep(1); ++ } ++ EXPECT_EQ(join_as(1, tid, &status), (int64_t)(int32_t)CELL_EINVAL); /* a second joiner */ ++ s_gate = 1; ++ WaitForSingleObject(h, 20000); CloseHandle(h); ++ EXPECT_EQ(b.rc, 0); ++ EXPECT_EQ(b.status, 3); ++ Sleep(50); ++ EXPECT_EQ(used_slots(), 0); ++ EXPECT_EQ(join_as(1, tid, &status), (int64_t)(int32_t)CELL_ESRCH); /* and it is gone */ ++ } ++ ++ printf("ppu thread join: %s\n", g_fails ? "FAIL" : "PASS"); ++ return g_fails ? 1 : 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-623/solution/solve.sh b/tasks/sp00nznet__ps3recomp-623/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-623/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-623/task.toml b/tasks/sp00nznet__ps3recomp-623/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ecd2634fad3a000c0ae6c396316e546894cdc92f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-623/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-623" +description = "sys_ppu_thread: Windows join no longer frees the slot under the exiting thread" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/623" +source_access = "auto" +built_at = "2026-11-16T16:09:59.667947+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8ed019ee9ca9dc20386fc1034e857479d309af74f1715ac168e72a656424a7f8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "runtime/syscalls/sys_ppu_thread.c", + "runtime/syscalls/sys_ppu_thread.h", + "tests/syscalls/CMakeLists.txt", + "tests/syscalls/test_ppu_thread_join.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 215 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.136337+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-623/tests/capture.py b/tasks/sp00nznet__ps3recomp-623/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-623/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-623/tests/instruction.md b/tasks/sp00nznet__ps3recomp-623/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c4a1ec5778445350cb37ab3e8eb97d3c15f96053 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-623/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** sys_ppu_thread: Windows join no longer frees the slot under the exiting thread + +## Description + +On Windows, `sys_ppu_thread_exit` signals `finish_event` from inside the thread body, and the thread then still runs the host thread epilogue. The joiner woke at the signal, freed the slot and closed the handles. The epilogue then wrote to the closed handle and set the slot it had just freed back to FINISHED, where it stayed. The thread table lost a slot per join, so a title that joins short-lived workers runs out of ids. + +1. `sys_ppu_thread_join`, and `sys_ppu_thread_detach` of an already-finished thread, now wait for the host thread to end before freeing the slot, as `pthread_join` already does on POSIX. The wait is bounded at 5 s so a thread kept running past its exit (`PS3_NO_THREAD_EXIT_UNWIND=1`) can't hang the joiner. Detach releases the table lock while it waits, because the epilogue takes it. +2. Joining yourself is EDEADLK (it waited on its own finish event forever). A second joiner of the same thread is EINVAL, through a new `joining` flag, instead of both waiting and both freeing the slot. + +Test: `tests/syscalls/test_ppu_thread_join.c`, a new ctest target. It includes `sys_ppu_thread.c` and runs real host threads through a trampoline that returns, exits or waits on a gate. It does 200 create/exit/join rounds and checks each exit status and that no slot is left behind, then detaches 100 finished threads, then covers self-join and a second joiner. On master it fails from the first round (wrong statuses, then EAGAIN as the table fills). + +Tested on Windows 11 with clang-cl: the full ctest passes (master's 21 plus this test), and the new test passed 15 of 15 repeated runs. I haven't run a POSIX build. The race is Windows-only, but the EDEADLK and EINVAL results apply everywhere. `test_ppu_thread_slots.py` is POSIX-only, so I couldn't run it. + +Already on master, so not included: non-joinable threads freeing their own slot (#415 and later). + +This is original code, written against the current file; no RPCS3 or other GPL code was used. It comes from the [Project 8 Plus](https://github.com/MaxLeiter/project-8-plus) port and was developed with AI assistance (Claude). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-623/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-623/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7fee288ab8e478750cca25762095a8237aa759f6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-623/tests/oracle.patch @@ -0,0 +1,274 @@ +diff --git a/runtime/syscalls/sys_ppu_thread.c b/runtime/syscalls/sys_ppu_thread.c +index 41d5721c..3404faf9 100644 +--- a/runtime/syscalls/sys_ppu_thread.c ++++ b/runtime/syscalls/sys_ppu_thread.c +@@ -662,21 +662,43 @@ int64_t sys_ppu_thread_join(ppu_context* ctx) + { static int n=0; if(PS3_LOG_FIRST(n, 30)) fprintf(stderr,"[WAIT] ppu_thread_join(tid=%llu)\n", (unsigned long long)tid); } + ppu_thread_note_block(ctx->thread_id); /* PS3_PRIO_START */ + ++ /* Joining yourself is EDEADLK (it used to wait on its own finish event ++ * for good). */ ++ if (tid == ctx->thread_id) ++ return (int64_t)(int32_t)CELL_EDEADLK; ++ + table_lock(); + ppu_thread_info* t = find_thread(tid); + if (!t) { + table_unlock(); + return (int64_t)(int32_t)CELL_ESRCH; + } +- if (!t->joinable || t->state == PPU_THREAD_STATE_DETACHED) { ++ /* A thread has one joiner: a second one gets EINVAL instead of both ++ * waiting, both closing the same handles and both freeing the slot. */ ++ if (!t->joinable || t->joining || t->state == PPU_THREAD_STATE_DETACHED) { + table_unlock(); + return (int64_t)(int32_t)CELL_EINVAL; + } ++ t->joining = 1; + table_unlock(); + + /* Wait for completion */ + #ifdef _WIN32 + WaitForSingleObject(t->finish_event, INFINITE); ++ /* sys_ppu_thread_exit signals finish_event from INSIDE the thread, which ++ * then still unwinds through ppu_host_thread_proc's epilogue, touching the ++ * slot (it stamps the state and signals the event again). Freeing the slot ++ * and closing the handles before that finished let the epilogue write to ++ * a closed handle and put a slot this join had freed back to FINISHED, so ++ * it never came back. Wait for the host thread itself first, as ++ * pthread_join does below. Bounded, so that a thread kept running past its ++ * exit (PS3_NO_THREAD_EXIT_UNWIND=1) cannot hang the joiner. */ ++ if (t->host_thread && WaitForSingleObject(t->host_thread, 5000) == WAIT_TIMEOUT) { ++ static int s_warned = 0; ++ if (s_warned++ < 4) ++ fprintf(stderr, "[SYS] ppu_thread_join(tid=%llu): host thread still running 5 s " ++ "after exit -- freeing the slot anyway\n", (unsigned long long)tid); ++ } + #else + pthread_mutex_lock(&t->finish_mutex); + while (!t->finished) { +@@ -759,8 +781,22 @@ int64_t sys_ppu_thread_detach(ppu_context* ctx) + if (t->state == PPU_THREAD_STATE_FINISHED) { + /* Already finished, free it */ + #ifdef _WIN32 ++ /* FINISHED is set by sys_ppu_thread_exit while the host thread still has ++ * its epilogue to run (it takes the table lock): let it end before the ++ * slot is freed, with the lock released while waiting, as in join. */ ++ HANDLE h = t->host_thread; ++ t->joining = 1; /* nobody joins it meanwhile */ ++ table_unlock(); ++ if (h) WaitForSingleObject(h, 5000); ++ table_lock(); ++ if (t->state != PPU_THREAD_STATE_FINISHED || t->host_thread != h) { ++ table_unlock(); /* freed or reused in the meantime */ ++ return CELL_OK; ++ } + CloseHandle(t->host_thread); + CloseHandle(t->finish_event); ++ t->host_thread = NULL; ++ t->finish_event = NULL; + #else + pthread_detach(t->host_thread); + pthread_mutex_destroy(&t->finish_mutex); +diff --git a/runtime/syscalls/sys_ppu_thread.h b/runtime/syscalls/sys_ppu_thread.h +index 633446e0..039264d3 100644 +--- a/runtime/syscalls/sys_ppu_thread.h ++++ b/runtime/syscalls/sys_ppu_thread.h +@@ -47,6 +47,7 @@ typedef struct ppu_thread_info { + int32_t priority; + int64_t exit_status; + int joinable; ++ int joining; /* a sys_ppu_thread_join is in progress: a second joiner is EINVAL */ + uint32_t stack_addr; /* guest stack base */ + uint32_t stack_size; + uint64_t entry_addr; /* guest entry point */ +diff --git a/tests/syscalls/CMakeLists.txt b/tests/syscalls/CMakeLists.txt +index c0ab35b9..bd54d2a1 100644 +--- a/tests/syscalls/CMakeLists.txt ++++ b/tests/syscalls/CMakeLists.txt +@@ -48,3 +48,24 @@ set_tests_properties(lock_line PROPERTIES + LABELS "runtime;syscalls" + TIMEOUT 30 + ) ++ ++# sys_ppu_thread_join / detach through the real sys_ppu_thread.c with host ++# threads: the slot a join frees stays free (Windows), self-join, second joiner. ++add_executable(test_ppu_thread_join test_ppu_thread_join.c) ++target_include_directories(test_ppu_thread_join PRIVATE ++ "${PS3RECOMP_ROOT}/runtime/syscalls" ++ "${PS3RECOMP_ROOT}/runtime" ++ "${PS3RECOMP_ROOT}/include" ++) ++if(MSVC) ++ target_compile_definitions(test_ppu_thread_join PRIVATE _CRT_SECURE_NO_WARNINGS) ++else() ++ target_compile_options(test_ppu_thread_join PRIVATE -Wall -Wextra -Wno-unused-parameter -UNDEBUG) ++ find_package(Threads REQUIRED) ++ target_link_libraries(test_ppu_thread_join PRIVATE Threads::Threads) ++endif() ++add_test(NAME ppu_thread_join COMMAND test_ppu_thread_join) ++set_tests_properties(ppu_thread_join PROPERTIES ++ LABELS "runtime;syscalls" ++ TIMEOUT 120 ++) +diff --git a/tests/syscalls/test_ppu_thread_join.c b/tests/syscalls/test_ppu_thread_join.c +new file mode 100644 +index 00000000..e410b957 +--- /dev/null ++++ b/tests/syscalls/test_ppu_thread_join.c +@@ -0,0 +1,155 @@ ++/* sys_ppu_thread_join / detach through the real sys_ppu_thread.c, with real host threads. ++ * ++ * - A thread that ends in sys_ppu_thread_exit signals its joiner from inside the thread body and then still unwinds ++ * through the host thread's epilogue. On Windows the joiner freed the slot and closed the handles at once; the ++ * epilogue then wrote to the closed handle and put the slot it had just freed back to FINISHED, where it stayed ++ * for good. The join now waits for the host thread to end first, so after a join (and after a detach of a ++ * finished thread) the slot is FREE and stays FREE. ++ * - Joining yourself is EDEADLK; a second joiner of the same thread is EINVAL. ++ * ++ * The guest entry is a trampoline that exits, returns, or waits for a gate, by its argument. */ ++#include "../../runtime/syscalls/sys_ppu_thread.c" ++#include <assert.h> ++ ++uint8_t* vm_base; ++uint32_t ppu_vm_size = 0x10000; ++uint32_t vm_read32(uint64_t a) /* guest words are big-endian (sys_ppu_thread_yield peeks at some) */ ++{ ++ const uint8_t* p = vm_base + (uint32_t)a; ++ return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3]; ++} ++void ppu_resv_register(ppu_context* c) { (void)c; } ++int ps3_intr_is_handler(unsigned long long tid) { (void)tid; return 0; } ++int ps3_intr_wait(unsigned long long tid) { (void)tid; return 0; } ++ ++enum { ARG_RETURN = 0, ARG_EXIT = 1, ARG_GATED = 2 }; ++static volatile int s_gate; /* a gated thread returns once this is set */ ++ ++static void guest_entry(ppu_context* ctx) ++{ ++ switch ((int)ctx->gpr[3]) { ++ case ARG_EXIT: ++ ctx->gpr[3] = 9; /* exit status */ ++ sys_ppu_thread_exit(ctx); /* does not return when the unwind is armed */ ++ break; ++ case ARG_GATED: ++ while (!s_gate) Sleep(1); ++ ctx->gpr[3] = 3; ++ break; ++ default: ++ ctx->gpr[3] = 5; ++ break; ++ } ++} ++ ++static int g_fails; ++#define EXPECT_EQ(got, want) do { long long g_ = (long long)(got), w_ = (long long)(want); if (g_ != w_) { g_fails++; \ ++ fprintf(stderr, "FAIL line %d: %s = 0x%llX, want 0x%llX\n", __LINE__, #got, g_, w_); } } while (0) ++ ++static int64_t create(uint64_t flags, uint64_t arg, uint64_t* tid) ++{ ++ ppu_context ctx; memset(&ctx, 0, sizeof(ctx)); ++ ctx.gpr[3] = 0x100; /* tid out */ ++ ctx.gpr[4] = 0x10000; /* entry */ ++ ctx.gpr[5] = arg; ++ ctx.gpr[6] = 1000; /* priority */ ++ ctx.gpr[7] = 0x10000; /* stack size */ ++ ctx.gpr[8] = flags; ++ ctx.gpr[9] = 0; /* name */ ++ int64_t rc = sys_ppu_thread_create(&ctx); ++ if (rc == 0 && tid) { uint64_t be; memcpy(&be, vm_base + 0x100, 8); *tid = __builtin_bswap64(be); } ++ return rc; ++} ++static int64_t join_as(uint64_t caller, uint64_t tid, int64_t* status) ++{ ++ ppu_context ctx; memset(&ctx, 0, sizeof(ctx)); ++ ctx.thread_id = caller; ++ ctx.gpr[3] = tid; ctx.gpr[4] = 0x200; ++ int64_t rc = sys_ppu_thread_join(&ctx); ++ if (rc == 0 && status) { uint64_t be; memcpy(&be, vm_base + 0x200, 8); *status = (int64_t)__builtin_bswap64(be); } ++ return rc; ++} ++static int64_t detach(uint64_t tid) ++{ ++ ppu_context ctx; memset(&ctx, 0, sizeof(ctx)); ++ ctx.gpr[3] = tid; ++ return sys_ppu_thread_detach(&ctx); ++} ++static int slot_state(uint64_t tid) { table_lock(); int s = g_ppu_threads[tid - 1].state; table_unlock(); return s; } ++static int used_slots(void) /* slots other than main that are not FREE */ ++{ ++ int n = 0; ++ table_lock(); ++ for (int i = 1; i < PPU_THREAD_MAX; i++) if (g_ppu_threads[i].state != PPU_THREAD_STATE_FREE) n++; ++ table_unlock(); ++ return n; ++} ++static void wait_state(uint64_t tid, int want) ++{ ++ for (int i = 0; i < 5000 && slot_state(tid) != want; i++) Sleep(1); ++} ++ ++typedef struct { uint64_t caller, tid; int64_t rc, status; } bgjoin_t; ++static DWORD WINAPI bgjoin_main(LPVOID p) ++{ ++ bgjoin_t* b = (bgjoin_t*)p; ++ b->rc = join_as(b->caller, b->tid, &b->status); ++ return 0; ++} ++ ++int main(void) ++{ ++ vm_base = (uint8_t*)calloc(1, 0x10000); assert(vm_base); ++ g_vm_stack_alloc.next_addr = 0x10000000u; /* the guest stack region the threads bump-allocate from */ ++ g_vm_stack_alloc.region_end = 0xA0000000u; ++ g_ppu_thread_entry_trampoline = guest_entry; ++ ppu_thread_register_main(); ++ ++ /* 1. Create / exit / join, over and over: every join returns the exit status and leaves its slot FREE for good. ++ * The slot table has 64 entries and is searched next-fit, so 200 rounds reuse every slot several times. */ ++ for (int i = 0; i < 200; i++) { ++ uint64_t tid = 0; int64_t status = 0; ++ EXPECT_EQ(create(1, (i & 1) ? ARG_EXIT : ARG_RETURN, &tid), 0); ++ EXPECT_EQ(join_as(1, tid, &status), 0); ++ EXPECT_EQ(status, (i & 1) ? 9 : 5); ++ Sleep(0); /* give a late epilogue its chance to misbehave */ ++ } ++ Sleep(50); ++ EXPECT_EQ(used_slots(), 0); /* nothing resurrected as FINISHED */ ++ ++ /* 2. Detaching a thread that has exited: the slot is freed and stays free. */ ++ for (int i = 0; i < 100; i++) { ++ uint64_t tid = 0; ++ EXPECT_EQ(create(1, ARG_EXIT, &tid), 0); ++ wait_state(tid, PPU_THREAD_STATE_FINISHED); ++ EXPECT_EQ(detach(tid), 0); ++ } ++ Sleep(50); ++ EXPECT_EQ(used_slots(), 0); ++ ++ /* 3. Self-join and a second joiner. */ ++ { ++ uint64_t tid = 0; int64_t status = 0; ++ s_gate = 0; ++ EXPECT_EQ(create(1, ARG_GATED, &tid), 0); ++ EXPECT_EQ(join_as(tid, tid, &status), (int64_t)(int32_t)CELL_EDEADLK); /* the thread joining itself */ ++ bgjoin_t b = { 1, tid, -1, 0 }; ++ HANDLE h = CreateThread(NULL, 0, bgjoin_main, &b, 0, NULL); ++ for (int i = 0; i < 5000; i++) { ++ table_lock(); int joining = g_ppu_threads[tid - 1].joining; table_unlock(); ++ if (joining) break; ++ Sleep(1); ++ } ++ EXPECT_EQ(join_as(1, tid, &status), (int64_t)(int32_t)CELL_EINVAL); /* a second joiner */ ++ s_gate = 1; ++ WaitForSingleObject(h, 20000); CloseHandle(h); ++ EXPECT_EQ(b.rc, 0); ++ EXPECT_EQ(b.status, 3); ++ Sleep(50); ++ EXPECT_EQ(used_slots(), 0); ++ EXPECT_EQ(join_as(1, tid, &status), (int64_t)(int32_t)CELL_ESRCH); /* and it is gone */ ++ } ++ ++ printf("ppu thread join: %s\n", g_fails ? "FAIL" : "PASS"); ++ return g_fails ? 1 : 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-623/tests/test.sh b/tasks/sp00nznet__ps3recomp-623/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-623/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-623/tests/verifier.py b/tasks/sp00nznet__ps3recomp-623/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-623/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-624/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-624/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-624/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-624/instruction.md b/tasks/sp00nznet__ps3recomp-624/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b68fdd1df31ed092d3cd74d1cbf5b248066e0075 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-624/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** lv2 SPU group syscalls: destroy of a running group, group_start state, error returns + +## Description + +Fixes in the SPU thread-group handlers in `lv2_register.c`. + +1. `sys_spu_thread_group_destroy` freed the context and local store of a thread that was still running, a use-after-free inside that thread. Middleware commonly writes a quit word to a signal register and destroys the group without a join. It now waits up to 250 ms for running threads to stop and otherwise answers CELL_EBUSY with nothing freed. Only threads that own memory freed by destroy count. +2. `group_start` on a group whose lifted thread is still running is CELL_ESTAT, instead of running the setup over the live context and spawning a second host thread. An unknown group is ESRCH. +3. A new group's unused thread slots are invalid (`MAX_SPU_THREADS`) instead of index 0, which is another group's thread. Every per-group loop used to start, join or free `s_spu_threads[0]`. +4. About 20 error paths set r3 to a CELL_E* code and then did `return -1`. `lv2_try_syscall` stores the handler's return value in r3, so the guest saw 0xFFFFFFFFFFFFFFFF. They return the code now. +5. Smaller: `get_exit_status` of a running thread is ESTAT (it used ENOSYS's value), `get_spu_cfg` stores the value through its pointer argument, `connect_event` on an unknown thread is ESRCH, and `image_import` answers CELL_EFAULT / CELL_ENOEXEC instead of -14 / -8. + +Test: `runtime/spu/tests/test_spu_group_lifecycle.c`, written like the other fixtures that include `lv2_register.c` (no new infrastructure). It checks the codes, a running thread making destroy and start refuse, nothing freed on EBUSY, and a clean destroy once the thread stops. `test_spu_group_lifecycle_win_stubs.c` supplies the symbols the COFF linker wants. Without the fix 13 checks fail. + +Tested on Windows 11 with clang-cl: the full ctest still passes (21/21). The fixture isn't wired into ctest, like its siblings, so I built and ran it by hand with clang and it passes. I haven't run a POSIX build. + +Not included: `write_snr`, the raw-SPU interrupt calls and the SPURS error blocks, which overlap other open work (#598). + +This is original code, written against the current file; no RPCS3 or other GPL code was used. It comes from the [Project 8 Plus](https://github.com/MaxLeiter/project-8-plus) port and was developed with AI assistance (Claude). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-624/solution/patch.diff b/tasks/sp00nznet__ps3recomp-624/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b9afbb7772f4f2b2ab923b2ff7705b6d1c63df24 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-624/solution/patch.diff @@ -0,0 +1,467 @@ +diff --git a/runtime/spu/tests/test_spu_group_lifecycle.c b/runtime/spu/tests/test_spu_group_lifecycle.c +new file mode 100644 +index 00000000..8503b4fe +--- /dev/null ++++ b/runtime/spu/tests/test_spu_group_lifecycle.c +@@ -0,0 +1,125 @@ ++/* SPU thread-group syscalls (lv2_register.c): teardown and error returns. ++ * ++ * - sys_spu_thread_group_destroy frees each thread's context and local store, so it must not run while a thread is ++ * still executing on its host thread: that is a use-after-free in the thread. A running thread makes it wait a ++ * moment and then answer CELL_EBUSY with nothing freed; once the thread has stopped it succeeds. ++ * - sys_spu_thread_group_start on a group whose thread is still running is CELL_ESTAT. ++ * - A group's unused thread slots are invalid (index MAX_SPU_THREADS), not index 0, which is some other group's thread. ++ * - Error paths return the CELL_E* code. lv2_try_syscall stores the handler's return value in r3, so a handler that ++ * set r3 and then `return -1` handed the guest 0xFFFFFFFFFFFFFFFF. ++ * - sys_spu_thread_get_spu_cfg stores the value through its pointer argument; sys_spu_thread_connect_event on an ++ * unknown thread is ESRCH; sys_spu_image_import answers CELL_EFAULT / CELL_ENOEXEC, not host errnos. ++ * ++ * clang -std=gnu17 -I include -I runtime -I runtime/syscalls -I runtime/spu -I libs/video ++ * runtime/spu/tests/test_spu_group_lifecycle.c -Wl,-dead_strip -pthread -o /tmp/test_spu_group_lifecycle ++ */ ++#include <stdint.h> ++/* Syscall 14's classifier (#341) lives in lv2_lock_line.c, which pulls in the ++ * VM map table; nothing here issues syscall 14. */ ++int64_t lv2_spu_lock_line_classify(uint32_t a, uint64_t f) { (void)a; (void)f; return 0; } ++#include "../../syscalls/lv2_register.c" ++#include <assert.h> ++#include <stdio.h> ++ ++uint8_t* vm_base; ++uint32_t ppu_vm_size; ++#ifndef _WIN32 ++void SetLastError(DWORD e) { (void)e; } ++#endif ++uint32_t spurs_port_queue(uint32_t port) { (void)port; return 0; } ++int64_t sys_event_flag_set(ppu_context* c) { (void)c; return 0; } ++size_t spu_elf_image_size(const uint8_t* image, size_t max_avail) { (void)image; (void)max_avail; return 0; } ++ ++static int fails; ++#define CHECK(c, ...) do { if (!(c)) { printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); fails++; } } while (0) ++ ++static uint32_t rd32(uint32_t a) { const uint8_t* p = vm_base + a; return (uint32_t)p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]; } ++ ++/* Run a handler as lv2_try_syscall does: r3 receives the return value. */ ++static uint32_t sc(int64_t (*h)(ppu_context*), uint64_t a, uint64_t b, uint64_t c, uint64_t d) ++{ ++ ppu_context ctx; memset(&ctx, 0, sizeof ctx); ++ ctx.gpr[3] = a; ctx.gpr[4] = b; ctx.gpr[5] = c; ctx.gpr[6] = d; ++ ctx.gpr[3] = (uint64_t)h(&ctx); ++ return (uint32_t)ctx.gpr[3]; ++} ++ ++/* A group with one thread that owns a lifted context and a local store. */ ++static spu_thread_t* make_thread(spu_group_t** gout) ++{ ++ spu_group_t* g = spu_alloc_group(); assert(g); ++ spu_thread_t* t = spu_alloc_thread(); assert(t); ++ t->group_id = g->id; ++ g->num_threads = 1; ++ g->thread_indices[0] = (uint32_t)(t - s_spu_threads); ++ t->sctx = (struct spu_context*)calloc(1, sizeof(spu_context)); assert(t->sctx); ++ t->local_store = (uint8_t*)calloc(1, 64); assert(t->local_store); ++ if (gout) *gout = g; ++ return t; ++} ++ ++int main(void) ++{ ++ vm_base = calloc(1, 1u << 20); assert(vm_base); ++ ppu_vm_size = 1u << 20; ++ ++ /* Unused thread slots of a fresh group are invalid, not index 0. */ ++ { ++ spu_group_t* g = spu_alloc_group(); assert(g); ++ int ok = 1; ++ for (int k = 0; k < 8; k++) ok &= g->thread_indices[k] == MAX_SPU_THREADS; ++ CHECK(ok, "a fresh group's thread slots are all invalid"); ++ g->in_use = 0; ++ } ++ ++ /* Error returns are the codes, not -1. */ ++ CHECK(sc(sys_spu_thread_group_start_handler, 0xDEAD, 0, 0, 0) == (uint32_t)CELL_ESRCH, ++ "group_start of an unknown group is ESRCH"); ++ CHECK(sc(sys_spu_thread_get_exit_status_handler, 0xDEAD, 0x100, 0, 0) == (uint32_t)CELL_ESRCH, ++ "get_exit_status of an unknown thread is ESRCH"); ++ CHECK(sc(sys_spu_thread_connect_event_handler, 0xDEAD, 1, 1, 0) == (uint32_t)CELL_ESRCH, ++ "connect_event on an unknown thread is ESRCH"); ++ CHECK(sc(sys_spu_thread_write_ls_handler, 0xDEAD, 0, 0, 4) == (uint32_t)CELL_ESRCH, ++ "write_ls on an unknown thread is ESRCH"); ++ CHECK(sc(sys_spu_thread_get_spu_cfg_handler, 0xDEAD, 0x100, 0, 0) == (uint32_t)CELL_ESRCH, ++ "get_spu_cfg on an unknown thread is ESRCH"); ++ CHECK(sc(sys_spu_image_import_handler, 0x2000, 0, 0, 0) == (uint32_t)CELL_EFAULT, ++ "image_import with a null source is EFAULT"); ++ memset(vm_base + 0x3000, 0, 16); ++ CHECK(sc(sys_spu_image_import_handler, 0x2000, 0x3000, 0, 0) == (uint32_t)CELL_ENOEXEC, ++ "image_import of something that is not an ELF is ENOEXEC"); ++ ++ /* A thread that is still running. */ ++ spu_group_t* g = NULL; ++ spu_thread_t* t = make_thread(&g); ++ t->running = 1; ++ CHECK(sc(sys_spu_thread_get_exit_status_handler, t->tid, 0x100, 0, 0) == (uint32_t)CELL_ESTAT, ++ "get_exit_status of a running thread is ESTAT (got 0x%08X)", ++ sc(sys_spu_thread_get_exit_status_handler, t->tid, 0x100, 0, 0)); ++ CHECK(sc(sys_spu_thread_group_start_handler, g->id, 0, 0, 0) == (uint32_t)CELL_ESTAT, ++ "group_start with a running thread is ESTAT"); ++ ++ /* get_spu_cfg stores through the pointer. */ ++ t->spu_cfg = 3; ++ memset(vm_base + 0x400, 0xEE, 16); ++ CHECK(sc(sys_spu_thread_get_spu_cfg_handler, t->tid, 0x400, 0, 0) == 0, "get_spu_cfg succeeds"); ++ CHECK(rd32(0x400) == 0 && rd32(0x404) == 3, "get_spu_cfg stores 3 through the pointer (0x%08X 0x%08X)", ++ rd32(0x400), rd32(0x404)); ++ CHECK(vm_base[0x408] == 0xEE, "and nothing past the u64"); ++ ++ /* group_destroy with the thread running: refused, nothing freed. */ ++ uint8_t* ls = t->local_store; struct spu_context* sctx = t->sctx; ++ CHECK(sc(sys_spu_thread_group_destroy_handler, g->id, 0, 0, 0) == (uint32_t)CELL_EBUSY, ++ "group_destroy with a running thread is EBUSY"); ++ CHECK(t->in_use && g->in_use && t->local_store == ls && t->sctx == sctx, ++ "and the thread, its context and its local store are untouched"); ++ ++ /* The thread stops: the same destroy now goes through. */ ++ t->running = 0; ++ CHECK(sc(sys_spu_thread_group_destroy_handler, g->id, 0, 0, 0) == 0, "group_destroy of a stopped group succeeds"); ++ CHECK(!t->in_use && !g->in_use && !t->local_store && !t->sctx, "and releases the thread and the group"); ++ ++ printf("[spu_group_lifecycle] %s (%d failed)\n", fails ? "FAIL" : "PASS", fails); ++ free(vm_base); ++ return fails ? 1 : 0; ++} +diff --git a/runtime/spu/tests/test_spu_group_lifecycle_win_stubs.c b/runtime/spu/tests/test_spu_group_lifecycle_win_stubs.c +new file mode 100644 +index 00000000..c3636303 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_group_lifecycle_win_stubs.c +@@ -0,0 +1,61 @@ ++/* Windows link stubs for test_spu_group_lifecycle.c. ++ * ++ * The fixture includes lv2_register.c whole and relies on the linker dropping what it does not use (-dead_strip / ++ * --gc-sections). The COFF linker resolves every reference first, so on Windows the symbols the rest of the runtime ++ * would supply are defined here. None of them is reached by the checks in the fixture: the functions answer 0 and the ++ * data is zero. Build it as ++ * clang -std=gnu17 -I include -I runtime -I runtime/syscalls -I runtime/spu -I libs/video ++ * runtime/spu/tests/test_spu_group_lifecycle.c runtime/spu/tests/test_spu_group_lifecycle_win_stubs.c ++ * runtime/spu/spu_lifted_thread.c -o test_spu_group_lifecycle.exe ++ * (no declarations are visible here, so the definitions carry no types: x64 does not mangle them.) */ ++#ifdef _WIN32 ++/* data */ ++char function_table[64]; ++char function_table_count[64]; ++char g_ps3_sdk_version[64]; ++char g_spu_interp_last_pc[64]; ++char g_spu_interp_steps[64]; ++char g_spu_out_mbox_hook[64]; ++char g_spu_user_event_hook[64]; ++char g_spurs_kernel_hook[64]; ++char g_ydkj_spurs_ctx_ea[64]; ++char ppu_guard_page[64]; ++ ++/* functions */ ++long long np_psnr_identity() { return 0; } ++long long ppu_dump_guest_stack() { return 0; } ++long long ppu_guest_caller() { return 0; } ++long long ppu_guest_callstack() { return 0; } ++long long ppu_log_host_chain() { return 0; } ++long long ps3_hle_register_ctx() { return 0; } ++long long ps3_spu_image_source_ea() { return 0; } ++long long spu_ch_wake() { return 0; } ++long long spu_coh_unregister() { return 0; } ++long long spu_have_function() { return 0; } ++long long spu_image_of_function() { return 0; } ++long long spu_indirect_branch() { return 0; } ++long long spu_interp_run() { return 0; } ++long long spu_lookup_ppu_fallback() { return 0; } ++long long spu_mfc_release() { return 0; } ++long long spu_raw_note_image() { return 0; } ++long long spu_register_ppu_fallback() { return 0; } ++long long spu_registry_fallback() { return 0; } ++long long spu_run_with_halt() { return 0; } ++long long spurs_job_ls_for_handle() { return 0; } ++long long sys_cond_init() { return 0; } ++long long sys_event_init() { return 0; } ++long long sys_event_queue_push_by_id() { return 0; } ++long long sys_fs_init() { return 0; } ++long long sys_fs_translate_path() { return 0; } ++long long sys_memory_init() { return 0; } ++long long sys_mutex_init() { return 0; } ++long long sys_ppu_thread_init() { return 0; } ++long long sys_process_exit() { return 0; } ++long long sys_process_getpid() { return 0; } ++long long sys_raw_spu_init() { return 0; } ++long long sys_rsx_init() { return 0; } ++long long sys_rwlock_init() { return 0; } ++long long sys_semaphore_init() { return 0; } ++long long sys_timer_init() { return 0; } ++long long sys_vm_init() { return 0; } ++#endif +diff --git a/runtime/syscalls/lv2_register.c b/runtime/syscalls/lv2_register.c +index 96266731..e5be07d6 100644 +--- a/runtime/syscalls/lv2_register.c ++++ b/runtime/syscalls/lv2_register.c +@@ -383,6 +383,11 @@ static spu_group_t* spu_alloc_group(void) + s_spu_groups[i].state = SPU_GROUP_STATE_INITIALIZED; + s_spu_groups[i].exit_status = 0; + s_spu_groups[i].cause = SPU_GROUP_CAUSE_ALL_THREADS_EXIT; ++ /* A slot that has not been given a thread by sys_spu_thread_initialize ++ * must not read as index 0: every per-group loop would then start, ++ * join or free s_spu_threads[0], which belongs to another group. */ ++ for (int k = 0; k < 8; k++) ++ s_spu_groups[i].thread_indices[k] = MAX_SPU_THREADS; + return &s_spu_groups[i]; + } + } +@@ -516,8 +521,8 @@ static int64_t sys_spu_thread_group_create_handler(ppu_context* ctx) + if (!g) { + fprintf(stderr, "[SPU] group_create: out of groups\n"); + fflush(stderr); +- ctx->gpr[3] = (uint64_t)(int64_t)-1; /* EAGAIN-ish */ +- return -1; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_EAGAIN; ++ return (int64_t)ctx->gpr[3]; + } + if (num > 8) num = 8; + g->num_threads = num; +@@ -592,13 +597,13 @@ static int64_t sys_spu_thread_initialize_handler(ppu_context* ctx) + if (!g) { + fprintf(stderr, "[SPU] thread_init: group 0x%X not found\n", group_id); + fflush(stderr); +- ctx->gpr[3] = (uint64_t)(int64_t)-1; +- return -1; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_ESRCH; ++ return (int64_t)ctx->gpr[3]; + } + spu_thread_t* t = spu_alloc_thread(); + if (!t) { +- ctx->gpr[3] = (uint64_t)(int64_t)-1; +- return -1; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_EAGAIN; ++ return (int64_t)ctx->gpr[3]; + } + t->group_id = group_id; + t->index = thread_num; +@@ -966,7 +971,21 @@ static int64_t sys_spu_thread_group_start_handler(ppu_context* ctx) + { + uint32_t id = (uint32_t)ctx->gpr[3]; + spu_group_t* g = spu_find_group(id); +- if (!g) { ctx->gpr[3] = (uint64_t)(int64_t)-1; return -1; } ++ /* An unknown group is ESRCH (it was a bare -1). */ ++ if (!g) { ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_ESRCH; return (int64_t)ctx->gpr[3]; } ++ /* Starting a group whose thread is still running is ESTAT. For a lifted ++ * thread it would run spu_lifted_thread_setup over the live context and ++ * spawn a second host thread on it. */ ++ for (uint32_t i = 0; i < g->num_threads && i < 8; i++) { ++ uint32_t idx = g->thread_indices[i]; ++ if (idx < MAX_SPU_THREADS && s_spu_threads[idx].in_use && ++ *(volatile int*)&s_spu_threads[idx].running && s_spu_threads[idx].sctx) { ++ fprintf(stderr, "[SPU] group_start id=0x%X: thread 0x%X still running -> CELL_ESTAT\n", ++ id, s_spu_threads[idx].tid); ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_ESTAT; ++ return (int64_t)ctx->gpr[3]; ++ } ++ } + g->state = SPU_GROUP_STATE_RUNNING; + /* This run has produced no cause yet. group_join now preserves a cause a + * thread reported, so a group id started a second time has to begin with a +@@ -1340,6 +1359,35 @@ static int64_t sys_spu_thread_group_destroy_handler(ppu_context* ctx) + } + spu_group_t* g = spu_find_group(id); + if (g) { ++ /* A thread still running on its host thread owns its context and local ++ * store, so freeing them below is a use-after-free inside that thread. ++ * lv2 refuses to destroy a group that has not stopped (CELL_EBUSY). A ++ * middleware shutdown commonly writes its "quit" word to a signal ++ * register and destroys the group straight away without a join, so give ++ * running threads a moment to see it and stop; if one is still running, ++ * refuse and free nothing. Only threads that own memory freed below ++ * count (a lifted context or a local store). */ ++ int busy = 0; ++ const uint64_t t0 = GetTickCount64(); /* wall time: Sleep(1) can be a 15.6 ms tick */ ++ for (;;) { ++ busy = 0; ++ for (int i = 0; i < 8 && i < (int)g->num_threads; i++) { ++ uint32_t idx = g->thread_indices[i]; ++ if (idx < MAX_SPU_THREADS && s_spu_threads[idx].in_use && ++ *(volatile int*)&s_spu_threads[idx].running && ++ (s_spu_threads[idx].sctx || s_spu_threads[idx].local_store)) ++ busy = 1; ++ } ++ if (!busy || GetTickCount64() - t0 >= 250) break; ++ Sleep(1); ++ } ++ if (busy) { ++ fprintf(stderr, "[SPU] group_destroy id=0x%X: a thread is still running " ++ "-> CELL_EBUSY (nothing freed)\n", id); ++ fflush(stderr); ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_EBUSY; ++ return (int64_t)ctx->gpr[3]; ++ } + for (int i = 0; i < 8 && i < (int)g->num_threads; i++) { + uint32_t idx = g->thread_indices[i]; + if (idx < MAX_SPU_THREADS) { +@@ -1394,13 +1442,13 @@ static int64_t sys_spu_thread_get_exit_status_handler(ppu_context* ctx) + spu_thread_t* t = spu_find_thread(tid); + if (!t) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; /* CELL_ESRCH */ +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + if (t->running) { + /* Still in flight — Sony's behaviour. Games that want the exit code + * synchronously should call group_join first. */ +- ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010003; /* CELL_ESTAT */ +- return -1; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_ESTAT; /* was 0x80010003 = ENOSYS */ ++ return (int64_t)ctx->gpr[3]; + } + vm_write_be32(status_ea, (uint32_t)t->exit_status); + ctx->gpr[3] = 0; +@@ -1592,7 +1640,7 @@ static int64_t sys_spu_thread_group_connect_event_handler(ppu_context* ctx) + spu_group_t* g = spu_find_group(group_id); + if (!g) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; /* CELL_ESRCH */ +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + g->event_queue_id = queue_id; + fprintf(stderr, "[SPU] group_connect_event group=0x%X queue=0x%X\n", +@@ -1752,8 +1800,10 @@ static int64_t sys_spu_thread_connect_event_handler(ppu_context* ctx) + fprintf(stderr, "[SPU] thread_connect_event tid=0x%X queue=0x%X et=0x%X spup=0x%X%s\n", + tid, eq, et, (uint32_t)ctx->gpr[6], t ? "" : " (thread not found)"); + fflush(stderr); +- ctx->gpr[3] = 0; +- return 0; ++ /* Nothing is bound for an unknown thread, so say so (ESRCH) instead of ++ * CELL_OK. */ ++ ctx->gpr[3] = t ? 0 : (uint64_t)(int64_t)(int32_t)CELL_ESRCH; ++ return (int64_t)ctx->gpr[3]; + } + + /* SPU -> PPU outbound mailbox delivery. Installed into spu_channels.c's +@@ -1832,16 +1882,16 @@ static int64_t sys_spu_thread_write_ls_handler(ppu_context* ctx) + spu_thread_t* t = spu_find_thread(tid); + if (!t) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; /* CELL_ESRCH */ +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + if (ls_offset + type > SPU_LS_SIZE) { +- ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; /* CELL_EFAULT */ +- return -1; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; /* CELL_EINVAL */ ++ return (int64_t)ctx->gpr[3]; + } + uint8_t* ls = spu_thread_get_or_alloc_ls(t); + if (!ls) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010004; /* CELL_ENOMEM */ +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + /* Big-endian store, mirroring guest convention. */ + switch (type) { +@@ -1856,7 +1906,7 @@ static int64_t sys_spu_thread_write_ls_handler(ppu_context* ctx) + break; + default: + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + ctx->gpr[3] = 0; + return 0; +@@ -1902,16 +1952,16 @@ static int64_t sys_spu_thread_read_ls_handler(ppu_context* ctx) + spu_thread_t* t = spu_find_thread(tid); + if (!t || !value_ea || !vm_base) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; /* CELL_ESRCH */ +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + if (ls_offset + type > SPU_LS_SIZE) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + uint8_t* ls = spu_thread_get_or_alloc_ls(t); + if (!ls) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010004; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + /* Big-endian load → write to guest as 8 bytes (always); the syscall + * is documented to write a u64 with the value zero-extended in the +@@ -1930,7 +1980,7 @@ static int64_t sys_spu_thread_read_ls_handler(ppu_context* ctx) + break; + default: + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + /* Write 8-byte BE value to guest. */ + uint8_t* p = vm_base + value_ea; +@@ -2004,8 +2054,8 @@ static int64_t sys_spu_image_import_handler(ppu_context* ctx) + + if (!img_ea || !src_ea || !vm_base) { + if (img_ea && vm_base) memset(vm_base + img_ea, 0, 16); +- ctx->gpr[3] = (uint64_t)(int64_t)-14; /* EFAULT */ +- return -14; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_EFAULT; /* was -14, a host errno */ ++ return (int64_t)ctx->gpr[3]; + } + + /* Validate SPU ELF32 (big-endian) magic. */ +@@ -2014,8 +2064,8 @@ static int64_t sys_spu_image_import_handler(ppu_context* ctx) + memset(vm_base + img_ea, 0, 16); + fprintf(stderr, "[SPU] image_import img=0x%08X src=0x%08X -- not an ELF\n", img_ea, src_ea); + fflush(stderr); +- ctx->gpr[3] = (uint64_t)(int64_t)-8; /* ENOEXEC */ +- return -8; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_ENOEXEC; /* was -8, a host errno */ ++ return (int64_t)ctx->gpr[3]; + } + + uint32_t entry = vm_read_be32(src_ea + 0x18); +@@ -2361,12 +2411,12 @@ static int64_t sys_spu_thread_write_snr_handler(ppu_context* ctx) + uint32_t val = (uint32_t)ctx->gpr[5]; + if (num > 1) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + spu_thread_t* t = spu_find_thread(tid); + if (!t) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + if (t->sctx) { + spu_channel* ch = &t->sctx->ch_sig_notify[num]; +@@ -2393,12 +2443,12 @@ static int64_t sys_spu_thread_set_spu_cfg_handler(ppu_context* ctx) + uint64_t val = (uint64_t)ctx->gpr[4]; + if (val & ~3ull) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + spu_thread_t* t = spu_find_thread(tid); + if (!t) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + t->spu_cfg = (uint32_t)val; + ctx->gpr[3] = 0; +@@ -2412,8 +2462,13 @@ static int64_t sys_spu_thread_get_spu_cfg_handler(ppu_context* ctx) + spu_thread_t* t = spu_find_thread(tid); + if (!t) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } ++ /* The ABI is (id, u64* value): the config is stored THROUGH the pointer in ++ * r4. Setting r4 alone left the caller's u64 unwritten. r4 is still set, as ++ * before. */ ++ { uint32_t out_ea = (uint32_t)ctx->gpr[4]; ++ if (out_ea) { vm_write_be32(out_ea, 0); vm_write_be32(out_ea + 4, (uint32_t)t->spu_cfg); } } + ctx->gpr[4] = (uint64_t)t->spu_cfg; + ctx->gpr[3] = 0; + return 0; diff --git a/tasks/sp00nznet__ps3recomp-624/solution/solve.sh b/tasks/sp00nznet__ps3recomp-624/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-624/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-624/task.toml b/tasks/sp00nznet__ps3recomp-624/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d6cbe5e96c56cb0f2067aaecaaced31d7b8a8097 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-624/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-624" +description = "lv2 SPU group syscalls: destroy of a running group, group_start state, error returns" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/624" +source_access = "auto" +built_at = "2026-11-16T16:09:59.635091+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b03cb2f11b270fa738bea070e27496f118b2f9363778dc4d5af4ad9496461f59" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "runtime/spu/tests/test_spu_group_lifecycle.c", + "runtime/spu/tests/test_spu_group_lifecycle_win_stubs.c", + "runtime/syscalls/lv2_register.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 303 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.136957+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-624/tests/capture.py b/tasks/sp00nznet__ps3recomp-624/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-624/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-624/tests/instruction.md b/tasks/sp00nznet__ps3recomp-624/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b68fdd1df31ed092d3cd74d1cbf5b248066e0075 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-624/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** lv2 SPU group syscalls: destroy of a running group, group_start state, error returns + +## Description + +Fixes in the SPU thread-group handlers in `lv2_register.c`. + +1. `sys_spu_thread_group_destroy` freed the context and local store of a thread that was still running, a use-after-free inside that thread. Middleware commonly writes a quit word to a signal register and destroys the group without a join. It now waits up to 250 ms for running threads to stop and otherwise answers CELL_EBUSY with nothing freed. Only threads that own memory freed by destroy count. +2. `group_start` on a group whose lifted thread is still running is CELL_ESTAT, instead of running the setup over the live context and spawning a second host thread. An unknown group is ESRCH. +3. A new group's unused thread slots are invalid (`MAX_SPU_THREADS`) instead of index 0, which is another group's thread. Every per-group loop used to start, join or free `s_spu_threads[0]`. +4. About 20 error paths set r3 to a CELL_E* code and then did `return -1`. `lv2_try_syscall` stores the handler's return value in r3, so the guest saw 0xFFFFFFFFFFFFFFFF. They return the code now. +5. Smaller: `get_exit_status` of a running thread is ESTAT (it used ENOSYS's value), `get_spu_cfg` stores the value through its pointer argument, `connect_event` on an unknown thread is ESRCH, and `image_import` answers CELL_EFAULT / CELL_ENOEXEC instead of -14 / -8. + +Test: `runtime/spu/tests/test_spu_group_lifecycle.c`, written like the other fixtures that include `lv2_register.c` (no new infrastructure). It checks the codes, a running thread making destroy and start refuse, nothing freed on EBUSY, and a clean destroy once the thread stops. `test_spu_group_lifecycle_win_stubs.c` supplies the symbols the COFF linker wants. Without the fix 13 checks fail. + +Tested on Windows 11 with clang-cl: the full ctest still passes (21/21). The fixture isn't wired into ctest, like its siblings, so I built and ran it by hand with clang and it passes. I haven't run a POSIX build. + +Not included: `write_snr`, the raw-SPU interrupt calls and the SPURS error blocks, which overlap other open work (#598). + +This is original code, written against the current file; no RPCS3 or other GPL code was used. It comes from the [Project 8 Plus](https://github.com/MaxLeiter/project-8-plus) port and was developed with AI assistance (Claude). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-624/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-624/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b9afbb7772f4f2b2ab923b2ff7705b6d1c63df24 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-624/tests/oracle.patch @@ -0,0 +1,467 @@ +diff --git a/runtime/spu/tests/test_spu_group_lifecycle.c b/runtime/spu/tests/test_spu_group_lifecycle.c +new file mode 100644 +index 00000000..8503b4fe +--- /dev/null ++++ b/runtime/spu/tests/test_spu_group_lifecycle.c +@@ -0,0 +1,125 @@ ++/* SPU thread-group syscalls (lv2_register.c): teardown and error returns. ++ * ++ * - sys_spu_thread_group_destroy frees each thread's context and local store, so it must not run while a thread is ++ * still executing on its host thread: that is a use-after-free in the thread. A running thread makes it wait a ++ * moment and then answer CELL_EBUSY with nothing freed; once the thread has stopped it succeeds. ++ * - sys_spu_thread_group_start on a group whose thread is still running is CELL_ESTAT. ++ * - A group's unused thread slots are invalid (index MAX_SPU_THREADS), not index 0, which is some other group's thread. ++ * - Error paths return the CELL_E* code. lv2_try_syscall stores the handler's return value in r3, so a handler that ++ * set r3 and then `return -1` handed the guest 0xFFFFFFFFFFFFFFFF. ++ * - sys_spu_thread_get_spu_cfg stores the value through its pointer argument; sys_spu_thread_connect_event on an ++ * unknown thread is ESRCH; sys_spu_image_import answers CELL_EFAULT / CELL_ENOEXEC, not host errnos. ++ * ++ * clang -std=gnu17 -I include -I runtime -I runtime/syscalls -I runtime/spu -I libs/video ++ * runtime/spu/tests/test_spu_group_lifecycle.c -Wl,-dead_strip -pthread -o /tmp/test_spu_group_lifecycle ++ */ ++#include <stdint.h> ++/* Syscall 14's classifier (#341) lives in lv2_lock_line.c, which pulls in the ++ * VM map table; nothing here issues syscall 14. */ ++int64_t lv2_spu_lock_line_classify(uint32_t a, uint64_t f) { (void)a; (void)f; return 0; } ++#include "../../syscalls/lv2_register.c" ++#include <assert.h> ++#include <stdio.h> ++ ++uint8_t* vm_base; ++uint32_t ppu_vm_size; ++#ifndef _WIN32 ++void SetLastError(DWORD e) { (void)e; } ++#endif ++uint32_t spurs_port_queue(uint32_t port) { (void)port; return 0; } ++int64_t sys_event_flag_set(ppu_context* c) { (void)c; return 0; } ++size_t spu_elf_image_size(const uint8_t* image, size_t max_avail) { (void)image; (void)max_avail; return 0; } ++ ++static int fails; ++#define CHECK(c, ...) do { if (!(c)) { printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); fails++; } } while (0) ++ ++static uint32_t rd32(uint32_t a) { const uint8_t* p = vm_base + a; return (uint32_t)p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]; } ++ ++/* Run a handler as lv2_try_syscall does: r3 receives the return value. */ ++static uint32_t sc(int64_t (*h)(ppu_context*), uint64_t a, uint64_t b, uint64_t c, uint64_t d) ++{ ++ ppu_context ctx; memset(&ctx, 0, sizeof ctx); ++ ctx.gpr[3] = a; ctx.gpr[4] = b; ctx.gpr[5] = c; ctx.gpr[6] = d; ++ ctx.gpr[3] = (uint64_t)h(&ctx); ++ return (uint32_t)ctx.gpr[3]; ++} ++ ++/* A group with one thread that owns a lifted context and a local store. */ ++static spu_thread_t* make_thread(spu_group_t** gout) ++{ ++ spu_group_t* g = spu_alloc_group(); assert(g); ++ spu_thread_t* t = spu_alloc_thread(); assert(t); ++ t->group_id = g->id; ++ g->num_threads = 1; ++ g->thread_indices[0] = (uint32_t)(t - s_spu_threads); ++ t->sctx = (struct spu_context*)calloc(1, sizeof(spu_context)); assert(t->sctx); ++ t->local_store = (uint8_t*)calloc(1, 64); assert(t->local_store); ++ if (gout) *gout = g; ++ return t; ++} ++ ++int main(void) ++{ ++ vm_base = calloc(1, 1u << 20); assert(vm_base); ++ ppu_vm_size = 1u << 20; ++ ++ /* Unused thread slots of a fresh group are invalid, not index 0. */ ++ { ++ spu_group_t* g = spu_alloc_group(); assert(g); ++ int ok = 1; ++ for (int k = 0; k < 8; k++) ok &= g->thread_indices[k] == MAX_SPU_THREADS; ++ CHECK(ok, "a fresh group's thread slots are all invalid"); ++ g->in_use = 0; ++ } ++ ++ /* Error returns are the codes, not -1. */ ++ CHECK(sc(sys_spu_thread_group_start_handler, 0xDEAD, 0, 0, 0) == (uint32_t)CELL_ESRCH, ++ "group_start of an unknown group is ESRCH"); ++ CHECK(sc(sys_spu_thread_get_exit_status_handler, 0xDEAD, 0x100, 0, 0) == (uint32_t)CELL_ESRCH, ++ "get_exit_status of an unknown thread is ESRCH"); ++ CHECK(sc(sys_spu_thread_connect_event_handler, 0xDEAD, 1, 1, 0) == (uint32_t)CELL_ESRCH, ++ "connect_event on an unknown thread is ESRCH"); ++ CHECK(sc(sys_spu_thread_write_ls_handler, 0xDEAD, 0, 0, 4) == (uint32_t)CELL_ESRCH, ++ "write_ls on an unknown thread is ESRCH"); ++ CHECK(sc(sys_spu_thread_get_spu_cfg_handler, 0xDEAD, 0x100, 0, 0) == (uint32_t)CELL_ESRCH, ++ "get_spu_cfg on an unknown thread is ESRCH"); ++ CHECK(sc(sys_spu_image_import_handler, 0x2000, 0, 0, 0) == (uint32_t)CELL_EFAULT, ++ "image_import with a null source is EFAULT"); ++ memset(vm_base + 0x3000, 0, 16); ++ CHECK(sc(sys_spu_image_import_handler, 0x2000, 0x3000, 0, 0) == (uint32_t)CELL_ENOEXEC, ++ "image_import of something that is not an ELF is ENOEXEC"); ++ ++ /* A thread that is still running. */ ++ spu_group_t* g = NULL; ++ spu_thread_t* t = make_thread(&g); ++ t->running = 1; ++ CHECK(sc(sys_spu_thread_get_exit_status_handler, t->tid, 0x100, 0, 0) == (uint32_t)CELL_ESTAT, ++ "get_exit_status of a running thread is ESTAT (got 0x%08X)", ++ sc(sys_spu_thread_get_exit_status_handler, t->tid, 0x100, 0, 0)); ++ CHECK(sc(sys_spu_thread_group_start_handler, g->id, 0, 0, 0) == (uint32_t)CELL_ESTAT, ++ "group_start with a running thread is ESTAT"); ++ ++ /* get_spu_cfg stores through the pointer. */ ++ t->spu_cfg = 3; ++ memset(vm_base + 0x400, 0xEE, 16); ++ CHECK(sc(sys_spu_thread_get_spu_cfg_handler, t->tid, 0x400, 0, 0) == 0, "get_spu_cfg succeeds"); ++ CHECK(rd32(0x400) == 0 && rd32(0x404) == 3, "get_spu_cfg stores 3 through the pointer (0x%08X 0x%08X)", ++ rd32(0x400), rd32(0x404)); ++ CHECK(vm_base[0x408] == 0xEE, "and nothing past the u64"); ++ ++ /* group_destroy with the thread running: refused, nothing freed. */ ++ uint8_t* ls = t->local_store; struct spu_context* sctx = t->sctx; ++ CHECK(sc(sys_spu_thread_group_destroy_handler, g->id, 0, 0, 0) == (uint32_t)CELL_EBUSY, ++ "group_destroy with a running thread is EBUSY"); ++ CHECK(t->in_use && g->in_use && t->local_store == ls && t->sctx == sctx, ++ "and the thread, its context and its local store are untouched"); ++ ++ /* The thread stops: the same destroy now goes through. */ ++ t->running = 0; ++ CHECK(sc(sys_spu_thread_group_destroy_handler, g->id, 0, 0, 0) == 0, "group_destroy of a stopped group succeeds"); ++ CHECK(!t->in_use && !g->in_use && !t->local_store && !t->sctx, "and releases the thread and the group"); ++ ++ printf("[spu_group_lifecycle] %s (%d failed)\n", fails ? "FAIL" : "PASS", fails); ++ free(vm_base); ++ return fails ? 1 : 0; ++} +diff --git a/runtime/spu/tests/test_spu_group_lifecycle_win_stubs.c b/runtime/spu/tests/test_spu_group_lifecycle_win_stubs.c +new file mode 100644 +index 00000000..c3636303 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_group_lifecycle_win_stubs.c +@@ -0,0 +1,61 @@ ++/* Windows link stubs for test_spu_group_lifecycle.c. ++ * ++ * The fixture includes lv2_register.c whole and relies on the linker dropping what it does not use (-dead_strip / ++ * --gc-sections). The COFF linker resolves every reference first, so on Windows the symbols the rest of the runtime ++ * would supply are defined here. None of them is reached by the checks in the fixture: the functions answer 0 and the ++ * data is zero. Build it as ++ * clang -std=gnu17 -I include -I runtime -I runtime/syscalls -I runtime/spu -I libs/video ++ * runtime/spu/tests/test_spu_group_lifecycle.c runtime/spu/tests/test_spu_group_lifecycle_win_stubs.c ++ * runtime/spu/spu_lifted_thread.c -o test_spu_group_lifecycle.exe ++ * (no declarations are visible here, so the definitions carry no types: x64 does not mangle them.) */ ++#ifdef _WIN32 ++/* data */ ++char function_table[64]; ++char function_table_count[64]; ++char g_ps3_sdk_version[64]; ++char g_spu_interp_last_pc[64]; ++char g_spu_interp_steps[64]; ++char g_spu_out_mbox_hook[64]; ++char g_spu_user_event_hook[64]; ++char g_spurs_kernel_hook[64]; ++char g_ydkj_spurs_ctx_ea[64]; ++char ppu_guard_page[64]; ++ ++/* functions */ ++long long np_psnr_identity() { return 0; } ++long long ppu_dump_guest_stack() { return 0; } ++long long ppu_guest_caller() { return 0; } ++long long ppu_guest_callstack() { return 0; } ++long long ppu_log_host_chain() { return 0; } ++long long ps3_hle_register_ctx() { return 0; } ++long long ps3_spu_image_source_ea() { return 0; } ++long long spu_ch_wake() { return 0; } ++long long spu_coh_unregister() { return 0; } ++long long spu_have_function() { return 0; } ++long long spu_image_of_function() { return 0; } ++long long spu_indirect_branch() { return 0; } ++long long spu_interp_run() { return 0; } ++long long spu_lookup_ppu_fallback() { return 0; } ++long long spu_mfc_release() { return 0; } ++long long spu_raw_note_image() { return 0; } ++long long spu_register_ppu_fallback() { return 0; } ++long long spu_registry_fallback() { return 0; } ++long long spu_run_with_halt() { return 0; } ++long long spurs_job_ls_for_handle() { return 0; } ++long long sys_cond_init() { return 0; } ++long long sys_event_init() { return 0; } ++long long sys_event_queue_push_by_id() { return 0; } ++long long sys_fs_init() { return 0; } ++long long sys_fs_translate_path() { return 0; } ++long long sys_memory_init() { return 0; } ++long long sys_mutex_init() { return 0; } ++long long sys_ppu_thread_init() { return 0; } ++long long sys_process_exit() { return 0; } ++long long sys_process_getpid() { return 0; } ++long long sys_raw_spu_init() { return 0; } ++long long sys_rsx_init() { return 0; } ++long long sys_rwlock_init() { return 0; } ++long long sys_semaphore_init() { return 0; } ++long long sys_timer_init() { return 0; } ++long long sys_vm_init() { return 0; } ++#endif +diff --git a/runtime/syscalls/lv2_register.c b/runtime/syscalls/lv2_register.c +index 96266731..e5be07d6 100644 +--- a/runtime/syscalls/lv2_register.c ++++ b/runtime/syscalls/lv2_register.c +@@ -383,6 +383,11 @@ static spu_group_t* spu_alloc_group(void) + s_spu_groups[i].state = SPU_GROUP_STATE_INITIALIZED; + s_spu_groups[i].exit_status = 0; + s_spu_groups[i].cause = SPU_GROUP_CAUSE_ALL_THREADS_EXIT; ++ /* A slot that has not been given a thread by sys_spu_thread_initialize ++ * must not read as index 0: every per-group loop would then start, ++ * join or free s_spu_threads[0], which belongs to another group. */ ++ for (int k = 0; k < 8; k++) ++ s_spu_groups[i].thread_indices[k] = MAX_SPU_THREADS; + return &s_spu_groups[i]; + } + } +@@ -516,8 +521,8 @@ static int64_t sys_spu_thread_group_create_handler(ppu_context* ctx) + if (!g) { + fprintf(stderr, "[SPU] group_create: out of groups\n"); + fflush(stderr); +- ctx->gpr[3] = (uint64_t)(int64_t)-1; /* EAGAIN-ish */ +- return -1; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_EAGAIN; ++ return (int64_t)ctx->gpr[3]; + } + if (num > 8) num = 8; + g->num_threads = num; +@@ -592,13 +597,13 @@ static int64_t sys_spu_thread_initialize_handler(ppu_context* ctx) + if (!g) { + fprintf(stderr, "[SPU] thread_init: group 0x%X not found\n", group_id); + fflush(stderr); +- ctx->gpr[3] = (uint64_t)(int64_t)-1; +- return -1; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_ESRCH; ++ return (int64_t)ctx->gpr[3]; + } + spu_thread_t* t = spu_alloc_thread(); + if (!t) { +- ctx->gpr[3] = (uint64_t)(int64_t)-1; +- return -1; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_EAGAIN; ++ return (int64_t)ctx->gpr[3]; + } + t->group_id = group_id; + t->index = thread_num; +@@ -966,7 +971,21 @@ static int64_t sys_spu_thread_group_start_handler(ppu_context* ctx) + { + uint32_t id = (uint32_t)ctx->gpr[3]; + spu_group_t* g = spu_find_group(id); +- if (!g) { ctx->gpr[3] = (uint64_t)(int64_t)-1; return -1; } ++ /* An unknown group is ESRCH (it was a bare -1). */ ++ if (!g) { ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_ESRCH; return (int64_t)ctx->gpr[3]; } ++ /* Starting a group whose thread is still running is ESTAT. For a lifted ++ * thread it would run spu_lifted_thread_setup over the live context and ++ * spawn a second host thread on it. */ ++ for (uint32_t i = 0; i < g->num_threads && i < 8; i++) { ++ uint32_t idx = g->thread_indices[i]; ++ if (idx < MAX_SPU_THREADS && s_spu_threads[idx].in_use && ++ *(volatile int*)&s_spu_threads[idx].running && s_spu_threads[idx].sctx) { ++ fprintf(stderr, "[SPU] group_start id=0x%X: thread 0x%X still running -> CELL_ESTAT\n", ++ id, s_spu_threads[idx].tid); ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_ESTAT; ++ return (int64_t)ctx->gpr[3]; ++ } ++ } + g->state = SPU_GROUP_STATE_RUNNING; + /* This run has produced no cause yet. group_join now preserves a cause a + * thread reported, so a group id started a second time has to begin with a +@@ -1340,6 +1359,35 @@ static int64_t sys_spu_thread_group_destroy_handler(ppu_context* ctx) + } + spu_group_t* g = spu_find_group(id); + if (g) { ++ /* A thread still running on its host thread owns its context and local ++ * store, so freeing them below is a use-after-free inside that thread. ++ * lv2 refuses to destroy a group that has not stopped (CELL_EBUSY). A ++ * middleware shutdown commonly writes its "quit" word to a signal ++ * register and destroys the group straight away without a join, so give ++ * running threads a moment to see it and stop; if one is still running, ++ * refuse and free nothing. Only threads that own memory freed below ++ * count (a lifted context or a local store). */ ++ int busy = 0; ++ const uint64_t t0 = GetTickCount64(); /* wall time: Sleep(1) can be a 15.6 ms tick */ ++ for (;;) { ++ busy = 0; ++ for (int i = 0; i < 8 && i < (int)g->num_threads; i++) { ++ uint32_t idx = g->thread_indices[i]; ++ if (idx < MAX_SPU_THREADS && s_spu_threads[idx].in_use && ++ *(volatile int*)&s_spu_threads[idx].running && ++ (s_spu_threads[idx].sctx || s_spu_threads[idx].local_store)) ++ busy = 1; ++ } ++ if (!busy || GetTickCount64() - t0 >= 250) break; ++ Sleep(1); ++ } ++ if (busy) { ++ fprintf(stderr, "[SPU] group_destroy id=0x%X: a thread is still running " ++ "-> CELL_EBUSY (nothing freed)\n", id); ++ fflush(stderr); ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_EBUSY; ++ return (int64_t)ctx->gpr[3]; ++ } + for (int i = 0; i < 8 && i < (int)g->num_threads; i++) { + uint32_t idx = g->thread_indices[i]; + if (idx < MAX_SPU_THREADS) { +@@ -1394,13 +1442,13 @@ static int64_t sys_spu_thread_get_exit_status_handler(ppu_context* ctx) + spu_thread_t* t = spu_find_thread(tid); + if (!t) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; /* CELL_ESRCH */ +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + if (t->running) { + /* Still in flight — Sony's behaviour. Games that want the exit code + * synchronously should call group_join first. */ +- ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010003; /* CELL_ESTAT */ +- return -1; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_ESTAT; /* was 0x80010003 = ENOSYS */ ++ return (int64_t)ctx->gpr[3]; + } + vm_write_be32(status_ea, (uint32_t)t->exit_status); + ctx->gpr[3] = 0; +@@ -1592,7 +1640,7 @@ static int64_t sys_spu_thread_group_connect_event_handler(ppu_context* ctx) + spu_group_t* g = spu_find_group(group_id); + if (!g) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; /* CELL_ESRCH */ +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + g->event_queue_id = queue_id; + fprintf(stderr, "[SPU] group_connect_event group=0x%X queue=0x%X\n", +@@ -1752,8 +1800,10 @@ static int64_t sys_spu_thread_connect_event_handler(ppu_context* ctx) + fprintf(stderr, "[SPU] thread_connect_event tid=0x%X queue=0x%X et=0x%X spup=0x%X%s\n", + tid, eq, et, (uint32_t)ctx->gpr[6], t ? "" : " (thread not found)"); + fflush(stderr); +- ctx->gpr[3] = 0; +- return 0; ++ /* Nothing is bound for an unknown thread, so say so (ESRCH) instead of ++ * CELL_OK. */ ++ ctx->gpr[3] = t ? 0 : (uint64_t)(int64_t)(int32_t)CELL_ESRCH; ++ return (int64_t)ctx->gpr[3]; + } + + /* SPU -> PPU outbound mailbox delivery. Installed into spu_channels.c's +@@ -1832,16 +1882,16 @@ static int64_t sys_spu_thread_write_ls_handler(ppu_context* ctx) + spu_thread_t* t = spu_find_thread(tid); + if (!t) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; /* CELL_ESRCH */ +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + if (ls_offset + type > SPU_LS_SIZE) { +- ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; /* CELL_EFAULT */ +- return -1; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; /* CELL_EINVAL */ ++ return (int64_t)ctx->gpr[3]; + } + uint8_t* ls = spu_thread_get_or_alloc_ls(t); + if (!ls) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010004; /* CELL_ENOMEM */ +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + /* Big-endian store, mirroring guest convention. */ + switch (type) { +@@ -1856,7 +1906,7 @@ static int64_t sys_spu_thread_write_ls_handler(ppu_context* ctx) + break; + default: + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + ctx->gpr[3] = 0; + return 0; +@@ -1902,16 +1952,16 @@ static int64_t sys_spu_thread_read_ls_handler(ppu_context* ctx) + spu_thread_t* t = spu_find_thread(tid); + if (!t || !value_ea || !vm_base) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; /* CELL_ESRCH */ +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + if (ls_offset + type > SPU_LS_SIZE) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + uint8_t* ls = spu_thread_get_or_alloc_ls(t); + if (!ls) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010004; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + /* Big-endian load → write to guest as 8 bytes (always); the syscall + * is documented to write a u64 with the value zero-extended in the +@@ -1930,7 +1980,7 @@ static int64_t sys_spu_thread_read_ls_handler(ppu_context* ctx) + break; + default: + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + /* Write 8-byte BE value to guest. */ + uint8_t* p = vm_base + value_ea; +@@ -2004,8 +2054,8 @@ static int64_t sys_spu_image_import_handler(ppu_context* ctx) + + if (!img_ea || !src_ea || !vm_base) { + if (img_ea && vm_base) memset(vm_base + img_ea, 0, 16); +- ctx->gpr[3] = (uint64_t)(int64_t)-14; /* EFAULT */ +- return -14; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_EFAULT; /* was -14, a host errno */ ++ return (int64_t)ctx->gpr[3]; + } + + /* Validate SPU ELF32 (big-endian) magic. */ +@@ -2014,8 +2064,8 @@ static int64_t sys_spu_image_import_handler(ppu_context* ctx) + memset(vm_base + img_ea, 0, 16); + fprintf(stderr, "[SPU] image_import img=0x%08X src=0x%08X -- not an ELF\n", img_ea, src_ea); + fflush(stderr); +- ctx->gpr[3] = (uint64_t)(int64_t)-8; /* ENOEXEC */ +- return -8; ++ ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)CELL_ENOEXEC; /* was -8, a host errno */ ++ return (int64_t)ctx->gpr[3]; + } + + uint32_t entry = vm_read_be32(src_ea + 0x18); +@@ -2361,12 +2411,12 @@ static int64_t sys_spu_thread_write_snr_handler(ppu_context* ctx) + uint32_t val = (uint32_t)ctx->gpr[5]; + if (num > 1) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + spu_thread_t* t = spu_find_thread(tid); + if (!t) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + if (t->sctx) { + spu_channel* ch = &t->sctx->ch_sig_notify[num]; +@@ -2393,12 +2443,12 @@ static int64_t sys_spu_thread_set_spu_cfg_handler(ppu_context* ctx) + uint64_t val = (uint64_t)ctx->gpr[4]; + if (val & ~3ull) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010002; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + spu_thread_t* t = spu_find_thread(tid); + if (!t) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } + t->spu_cfg = (uint32_t)val; + ctx->gpr[3] = 0; +@@ -2412,8 +2462,13 @@ static int64_t sys_spu_thread_get_spu_cfg_handler(ppu_context* ctx) + spu_thread_t* t = spu_find_thread(tid); + if (!t) { + ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x80010005; +- return -1; ++ return (int64_t)ctx->gpr[3]; + } ++ /* The ABI is (id, u64* value): the config is stored THROUGH the pointer in ++ * r4. Setting r4 alone left the caller's u64 unwritten. r4 is still set, as ++ * before. */ ++ { uint32_t out_ea = (uint32_t)ctx->gpr[4]; ++ if (out_ea) { vm_write_be32(out_ea, 0); vm_write_be32(out_ea + 4, (uint32_t)t->spu_cfg); } } + ctx->gpr[4] = (uint64_t)t->spu_cfg; + ctx->gpr[3] = 0; + return 0; diff --git a/tasks/sp00nznet__ps3recomp-624/tests/test.sh b/tasks/sp00nznet__ps3recomp-624/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-624/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-624/tests/verifier.py b/tasks/sp00nznet__ps3recomp-624/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-624/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-625/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-625/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-625/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-625/instruction.md b/tasks/sp00nznet__ps3recomp-625/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..441ea86ad39ee464577ad77c93afe1cbfddd2051 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-625/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** HLE heap delete_heap and bounds; boot_main window close quits through ps3_host_quit + +## Description + +Three small changes, two in the HLE heap and one in the boot scaffold. + +1. `_sys_heap_delete_heap` returns CELL_OK. It forwarded to `sys_heap_destroy_heap`, which searches a table that the ids from `_sys_heap_create_heap` are never entered in, so it answered ESRCH for every heap. Blocks aren't reclaimed, as before. +2. `yz_heap_alloc` (behind `_sys_heap_malloc` and `_sys_heap_memalign`) is bounds-safe now. A request bigger than the window is rejected, where `size + align + 16` used to wrap 32 bits and come back as a tiny block. The room is checked before the bump pointer advances. Advancing first left it past the window after one failed allocation, and a later request could wrap it back to an address outside the window. +3. `runtime/ppu/tests/boot_main.cpp` calls `ps3_host_quit("window closed")` when the window closes or ESC is pressed. That posts CELL_SYSUTIL_REQUEST_EXITGAME to the title's sysutil callbacks, as `templates/project/main.cpp` and the Metal backend already do. The scaffold only cleared `rsx_ok`, so the guest kept running with no window until killed. + +Tests: +- New checks in `tests/test_mmapper_hle_heap.c`: oversized and wrapping requests return 0 and leave the pointer alone, a small allocation still works near the end of the window, and `_sys_heap_delete_heap` is OK. `tools/test_mmapper_hle_heap.py` now also extracts `_sys_heap_delete_heap`, with a stub for `sys_heap_destroy_heap`. On master the first bounds check fails. +- `boot_main.cpp` needs a game's `ppu_recomp.h`, so `tools/check_ppu_scaffold.py` is the check. It compiles with no regression. + +Tested on Windows 11 with clang-cl. The full ctest passes (21/21). The mapper/heap fixture is skipped on Windows by its runner, so I ran the same script with the skip lifted and `clang`, and it passes (53 checks). I haven't run a POSIX build or a window close in a real port. + +Not included: the cellSysmodule unload refcount. `test_sysmodule_*` pins the current idempotent behaviour. + +This is original code, written against the current files; no RPCS3 or other GPL code was used. It comes from the [Project 8 Plus](https://github.com/MaxLeiter/project-8-plus) port and was developed with AI assistance (Claude). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-625/solution/patch.diff b/tasks/sp00nznet__ps3recomp-625/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..92c5722e8e9e86d37a0b96fb52d9e8c4571f091e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-625/solution/patch.diff @@ -0,0 +1,127 @@ +diff --git a/libs/system/sysPrxForUser.c b/libs/system/sysPrxForUser.c +index b2cba7b6..4aeaee66 100644 +--- a/libs/system/sysPrxForUser.c ++++ b/libs/system/sysPrxForUser.c +@@ -877,6 +877,10 @@ static u32 yz_bin_for(u32 need) + static u32 yz_heap_alloc(u32 size, u32 align) + { + if (align < 16) align = 16; ++ /* Anything larger than the window can never fit, and letting it through ++ * wrapped `need` (size + align + 16 in 32 bits) to a tiny bin: a block far ++ * smaller than the caller asked for. */ ++ if (size > YZ_HEAP_END - YZ_HEAP_BASE || align > YZ_HEAP_END - YZ_HEAP_BASE) return 0; + u32 need = size + align + 16; /* header + worst-case alignment pad */ + u32 b = yz_bin_for(need); + u32 raw; +@@ -887,9 +891,12 @@ static u32 yz_heap_alloc(u32 size, u32 align) + s_heap_bin[b] = vm_read32(raw); + } else { + if (s_heap_bump == 0) s_heap_bump = YZ_HEAP_BASE; ++ /* Check BEFORE advancing: bump-then-test left s_heap_bump past the end ++ * after one failure, and a later request could wrap it back below ++ * YZ_HEAP_END and hand out an address outside the window. */ ++ if ((1u << b) > YZ_HEAP_END - s_heap_bump) { slot_unlock(); return 0; } + raw = s_heap_bump; + s_heap_bump += (1u << b); +- if (s_heap_bump > YZ_HEAP_END) { slot_unlock(); return 0; } + } + slot_unlock(); + +@@ -970,7 +977,13 @@ u32 _sys_heap_create_heap(u32 name, u32 type, u32 blocksize, u32 flags) + + s32 _sys_heap_delete_heap(sys_heap_t heap) + { +- return sys_heap_destroy_heap(heap); ++ /* The ids _sys_heap_create_heap hands out (sys_heap_create_heap_ret) are ++ * never entered in the s_heaps table that sys_heap_destroy_heap searches, so ++ * forwarding there answered CELL_ESRCH for every heap this API ever created. ++ * Deleting one is CELL_OK; blocks are not reclaimed (the bump window has no ++ * per-heap ownership). */ ++ (void)heap; ++ return CELL_OK; + } + + /* The plain libc allocator sysPrxForUser exports, as opposed to the sys_heap_* +diff --git a/runtime/ppu/tests/boot_main.cpp b/runtime/ppu/tests/boot_main.cpp +index a55afb05..af539f63 100644 +--- a/runtime/ppu/tests/boot_main.cpp ++++ b/runtime/ppu/tests/boot_main.cpp +@@ -378,6 +378,7 @@ static void rsx_present_frame(void) + } + static int rsx_pump_messages(void) + { return s_rsx_live ? rsx_null_backend_pump_messages() : rsx_backend_pump(); } ++extern "C" void ps3_host_quit(const char* why); /* libs/system/cellSysutil.c: REQUEST_EXITGAME, then exit 0 */ + + /* Frames handed to the backend at a guest FLIP boundary -- one per frame the + * guest actually finished, which is the number a port means by "is anything +@@ -538,7 +539,13 @@ static DWORD WINAPI vblank_ticker(LPVOID) + if(++s_q3 % 8 == 0){ int r=sys_event_queue_inject(qid, 0x1234, 0, 0, 0); + static int _n=0; if(_n++<12) fprintf(stderr,"[INJQ3] injected q%u event rc=%d\n",qid,r); } } + if (rsx_ok) { +- if (rsx_pump_messages() != 0) { rsx_ok = 0; } ++ if (rsx_pump_messages() != 0) { ++ rsx_ok = 0; ++ /* The window was closed (or ESC pressed): quit as the console's Quit Game does -- every ++ * registered sysutil callback gets CELL_SYSUTIL_REQUEST_EXITGAME, so the title can finish a ++ * save and exit -- instead of leaving the guest running with no window. Once only. */ ++ ps3_host_quit("window closed"); ++ } + if (getenv("YDKJ_PACETRACE")) { + static ULONGLONG s_win=0; static int s_pf=0, s_pres=0; static ULONGLONG s_presms=0; + s_pf += fired; s_pres++; +diff --git a/tests/test_mmapper_hle_heap.c b/tests/test_mmapper_hle_heap.c +index db21e675..5966283d 100644 +--- a/tests/test_mmapper_hle_heap.c ++++ b/tests/test_mmapper_hle_heap.c +@@ -18,6 +18,9 @@ static void vm_write32(uint32_t a,uint32_t v) { + uint8_t* p=vm_base+a;p[0]=v>>24;p[1]=v>>16;p[2]=v>>8;p[3]=v; + } + extern int64_t sys_mmapper_allocate_memory(ppu_context*); ++/* The old _sys_heap_delete_heap forwarded to this, which only knows the ids of ++ * the s_heaps table and so answers ESRCH for a _sys_heap_create_heap id. */ ++s32 sys_heap_destroy_heap(sys_heap_t heap) { (void)heap; return (s32)CELL_ESRCH; } + static void slot_lock(void) {} + static void slot_unlock(void) {} + /* Exact production heap definitions/functions, copied without modification by +@@ -90,5 +93,28 @@ int main(void) { + reset();vm_write32(0x10000,0xAABBCCDDu); + CHECK(reserve(0x80000000,0x10000000)!=(int64_t)CELL_OK);CHECK(out()==0xAABBCCDDu); + CHECK(reserve(0x100000,0x100000)==CELL_OK);CHECK(out()==0x40000000u); ++ /* Heap bounds. A request larger than the window can never fit, and one ++ * whose size + alignment + header wraps 32 bits used to come back as a tiny ++ * block. */ ++ reset(); ++ CHECK(yz_heap_alloc(YZ_HEAP_END-YZ_HEAP_BASE+1u,16)==0); ++ CHECK(yz_heap_alloc(0xFFFFFFF0u,16)==0); ++ CHECK(yz_heap_alloc(0x100,0xFFFFFFF0u)==0); ++ CHECK(s_heap_bump==0); ++ /* A request that does not fit in what is left must fail WITHOUT moving the ++ * bump pointer past the end of the window; the next small request still ++ * succeeds, inside the window. (The pointer used to be advanced first, so ++ * after one failure every later request failed or wrapped.) */ ++ reset();CHECK(vm_commit(YZ_HEAP_END-0x1000,0x1000)==CELL_OK); ++ s_heap_bump=YZ_HEAP_END-0x1000; ++ CHECK(yz_heap_alloc(0x10000,16)==0); ++ CHECK(s_heap_bump==YZ_HEAP_END-0x1000); ++ uint32_t tail=yz_heap_alloc(16,16); ++ CHECK(tail>=YZ_HEAP_BASE && tail+16<=YZ_HEAP_END); ++ CHECK(s_heap_bump<=YZ_HEAP_END); ++ /* Deleting a heap made by _sys_heap_create_heap is CELL_OK. */ ++ u32 heap=_sys_heap_create_heap(0,0,0,0); ++ CHECK(heap!=0); ++ CHECK(_sys_heap_delete_heap(heap)==CELL_OK); + vm_shutdown();printf("PASS %u mapper/HLE heap checks\n",checks);return 0; + } +diff --git a/tools/test_mmapper_hle_heap.py b/tools/test_mmapper_hle_heap.py +index ce100dbc..b19cccaa 100644 +--- a/tools/test_mmapper_hle_heap.py ++++ b/tools/test_mmapper_hle_heap.py +@@ -11,7 +11,7 @@ def main(): + return 0 + source = (ROOT / 'libs/system/sysPrxForUser.c').read_text() + begin = source.index('#define YZ_HEAP_BASE') +- end = source.index('/* _sys_heap_create_heap', begin) ++ end = source.index('/* The plain libc allocator sysPrxForUser exports', begin) + body = source[begin:end] + with tempfile.TemporaryDirectory(prefix='ps3-mmapper-hle-heap-') as tmp: + temp = Path(tmp) diff --git a/tasks/sp00nznet__ps3recomp-625/solution/solve.sh b/tasks/sp00nznet__ps3recomp-625/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-625/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-625/task.toml b/tasks/sp00nznet__ps3recomp-625/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7dfcc86c4723328a74f34ef7911c9ae11860c088 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-625/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-625" +description = "HLE heap delete_heap and bounds; boot_main window close quits through ps3_host_quit" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/625" +source_access = "auto" +built_at = "2026-11-16T16:09:59.666200+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6e275d960e80a446fcee352a36fa2d93f2ff534e3fbbd0f2474d4002dd0055c4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/system/sysPrxForUser.c", + "runtime/ppu/tests/boot_main.cpp", + "tests/test_mmapper_hle_heap.c", + "tools/test_mmapper_hle_heap.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 54 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.137694+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-625/tests/capture.py b/tasks/sp00nznet__ps3recomp-625/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-625/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-625/tests/instruction.md b/tasks/sp00nznet__ps3recomp-625/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..441ea86ad39ee464577ad77c93afe1cbfddd2051 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-625/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** HLE heap delete_heap and bounds; boot_main window close quits through ps3_host_quit + +## Description + +Three small changes, two in the HLE heap and one in the boot scaffold. + +1. `_sys_heap_delete_heap` returns CELL_OK. It forwarded to `sys_heap_destroy_heap`, which searches a table that the ids from `_sys_heap_create_heap` are never entered in, so it answered ESRCH for every heap. Blocks aren't reclaimed, as before. +2. `yz_heap_alloc` (behind `_sys_heap_malloc` and `_sys_heap_memalign`) is bounds-safe now. A request bigger than the window is rejected, where `size + align + 16` used to wrap 32 bits and come back as a tiny block. The room is checked before the bump pointer advances. Advancing first left it past the window after one failed allocation, and a later request could wrap it back to an address outside the window. +3. `runtime/ppu/tests/boot_main.cpp` calls `ps3_host_quit("window closed")` when the window closes or ESC is pressed. That posts CELL_SYSUTIL_REQUEST_EXITGAME to the title's sysutil callbacks, as `templates/project/main.cpp` and the Metal backend already do. The scaffold only cleared `rsx_ok`, so the guest kept running with no window until killed. + +Tests: +- New checks in `tests/test_mmapper_hle_heap.c`: oversized and wrapping requests return 0 and leave the pointer alone, a small allocation still works near the end of the window, and `_sys_heap_delete_heap` is OK. `tools/test_mmapper_hle_heap.py` now also extracts `_sys_heap_delete_heap`, with a stub for `sys_heap_destroy_heap`. On master the first bounds check fails. +- `boot_main.cpp` needs a game's `ppu_recomp.h`, so `tools/check_ppu_scaffold.py` is the check. It compiles with no regression. + +Tested on Windows 11 with clang-cl. The full ctest passes (21/21). The mapper/heap fixture is skipped on Windows by its runner, so I ran the same script with the skip lifted and `clang`, and it passes (53 checks). I haven't run a POSIX build or a window close in a real port. + +Not included: the cellSysmodule unload refcount. `test_sysmodule_*` pins the current idempotent behaviour. + +This is original code, written against the current files; no RPCS3 or other GPL code was used. It comes from the [Project 8 Plus](https://github.com/MaxLeiter/project-8-plus) port and was developed with AI assistance (Claude). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-625/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-625/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..92c5722e8e9e86d37a0b96fb52d9e8c4571f091e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-625/tests/oracle.patch @@ -0,0 +1,127 @@ +diff --git a/libs/system/sysPrxForUser.c b/libs/system/sysPrxForUser.c +index b2cba7b6..4aeaee66 100644 +--- a/libs/system/sysPrxForUser.c ++++ b/libs/system/sysPrxForUser.c +@@ -877,6 +877,10 @@ static u32 yz_bin_for(u32 need) + static u32 yz_heap_alloc(u32 size, u32 align) + { + if (align < 16) align = 16; ++ /* Anything larger than the window can never fit, and letting it through ++ * wrapped `need` (size + align + 16 in 32 bits) to a tiny bin: a block far ++ * smaller than the caller asked for. */ ++ if (size > YZ_HEAP_END - YZ_HEAP_BASE || align > YZ_HEAP_END - YZ_HEAP_BASE) return 0; + u32 need = size + align + 16; /* header + worst-case alignment pad */ + u32 b = yz_bin_for(need); + u32 raw; +@@ -887,9 +891,12 @@ static u32 yz_heap_alloc(u32 size, u32 align) + s_heap_bin[b] = vm_read32(raw); + } else { + if (s_heap_bump == 0) s_heap_bump = YZ_HEAP_BASE; ++ /* Check BEFORE advancing: bump-then-test left s_heap_bump past the end ++ * after one failure, and a later request could wrap it back below ++ * YZ_HEAP_END and hand out an address outside the window. */ ++ if ((1u << b) > YZ_HEAP_END - s_heap_bump) { slot_unlock(); return 0; } + raw = s_heap_bump; + s_heap_bump += (1u << b); +- if (s_heap_bump > YZ_HEAP_END) { slot_unlock(); return 0; } + } + slot_unlock(); + +@@ -970,7 +977,13 @@ u32 _sys_heap_create_heap(u32 name, u32 type, u32 blocksize, u32 flags) + + s32 _sys_heap_delete_heap(sys_heap_t heap) + { +- return sys_heap_destroy_heap(heap); ++ /* The ids _sys_heap_create_heap hands out (sys_heap_create_heap_ret) are ++ * never entered in the s_heaps table that sys_heap_destroy_heap searches, so ++ * forwarding there answered CELL_ESRCH for every heap this API ever created. ++ * Deleting one is CELL_OK; blocks are not reclaimed (the bump window has no ++ * per-heap ownership). */ ++ (void)heap; ++ return CELL_OK; + } + + /* The plain libc allocator sysPrxForUser exports, as opposed to the sys_heap_* +diff --git a/runtime/ppu/tests/boot_main.cpp b/runtime/ppu/tests/boot_main.cpp +index a55afb05..af539f63 100644 +--- a/runtime/ppu/tests/boot_main.cpp ++++ b/runtime/ppu/tests/boot_main.cpp +@@ -378,6 +378,7 @@ static void rsx_present_frame(void) + } + static int rsx_pump_messages(void) + { return s_rsx_live ? rsx_null_backend_pump_messages() : rsx_backend_pump(); } ++extern "C" void ps3_host_quit(const char* why); /* libs/system/cellSysutil.c: REQUEST_EXITGAME, then exit 0 */ + + /* Frames handed to the backend at a guest FLIP boundary -- one per frame the + * guest actually finished, which is the number a port means by "is anything +@@ -538,7 +539,13 @@ static DWORD WINAPI vblank_ticker(LPVOID) + if(++s_q3 % 8 == 0){ int r=sys_event_queue_inject(qid, 0x1234, 0, 0, 0); + static int _n=0; if(_n++<12) fprintf(stderr,"[INJQ3] injected q%u event rc=%d\n",qid,r); } } + if (rsx_ok) { +- if (rsx_pump_messages() != 0) { rsx_ok = 0; } ++ if (rsx_pump_messages() != 0) { ++ rsx_ok = 0; ++ /* The window was closed (or ESC pressed): quit as the console's Quit Game does -- every ++ * registered sysutil callback gets CELL_SYSUTIL_REQUEST_EXITGAME, so the title can finish a ++ * save and exit -- instead of leaving the guest running with no window. Once only. */ ++ ps3_host_quit("window closed"); ++ } + if (getenv("YDKJ_PACETRACE")) { + static ULONGLONG s_win=0; static int s_pf=0, s_pres=0; static ULONGLONG s_presms=0; + s_pf += fired; s_pres++; +diff --git a/tests/test_mmapper_hle_heap.c b/tests/test_mmapper_hle_heap.c +index db21e675..5966283d 100644 +--- a/tests/test_mmapper_hle_heap.c ++++ b/tests/test_mmapper_hle_heap.c +@@ -18,6 +18,9 @@ static void vm_write32(uint32_t a,uint32_t v) { + uint8_t* p=vm_base+a;p[0]=v>>24;p[1]=v>>16;p[2]=v>>8;p[3]=v; + } + extern int64_t sys_mmapper_allocate_memory(ppu_context*); ++/* The old _sys_heap_delete_heap forwarded to this, which only knows the ids of ++ * the s_heaps table and so answers ESRCH for a _sys_heap_create_heap id. */ ++s32 sys_heap_destroy_heap(sys_heap_t heap) { (void)heap; return (s32)CELL_ESRCH; } + static void slot_lock(void) {} + static void slot_unlock(void) {} + /* Exact production heap definitions/functions, copied without modification by +@@ -90,5 +93,28 @@ int main(void) { + reset();vm_write32(0x10000,0xAABBCCDDu); + CHECK(reserve(0x80000000,0x10000000)!=(int64_t)CELL_OK);CHECK(out()==0xAABBCCDDu); + CHECK(reserve(0x100000,0x100000)==CELL_OK);CHECK(out()==0x40000000u); ++ /* Heap bounds. A request larger than the window can never fit, and one ++ * whose size + alignment + header wraps 32 bits used to come back as a tiny ++ * block. */ ++ reset(); ++ CHECK(yz_heap_alloc(YZ_HEAP_END-YZ_HEAP_BASE+1u,16)==0); ++ CHECK(yz_heap_alloc(0xFFFFFFF0u,16)==0); ++ CHECK(yz_heap_alloc(0x100,0xFFFFFFF0u)==0); ++ CHECK(s_heap_bump==0); ++ /* A request that does not fit in what is left must fail WITHOUT moving the ++ * bump pointer past the end of the window; the next small request still ++ * succeeds, inside the window. (The pointer used to be advanced first, so ++ * after one failure every later request failed or wrapped.) */ ++ reset();CHECK(vm_commit(YZ_HEAP_END-0x1000,0x1000)==CELL_OK); ++ s_heap_bump=YZ_HEAP_END-0x1000; ++ CHECK(yz_heap_alloc(0x10000,16)==0); ++ CHECK(s_heap_bump==YZ_HEAP_END-0x1000); ++ uint32_t tail=yz_heap_alloc(16,16); ++ CHECK(tail>=YZ_HEAP_BASE && tail+16<=YZ_HEAP_END); ++ CHECK(s_heap_bump<=YZ_HEAP_END); ++ /* Deleting a heap made by _sys_heap_create_heap is CELL_OK. */ ++ u32 heap=_sys_heap_create_heap(0,0,0,0); ++ CHECK(heap!=0); ++ CHECK(_sys_heap_delete_heap(heap)==CELL_OK); + vm_shutdown();printf("PASS %u mapper/HLE heap checks\n",checks);return 0; + } +diff --git a/tools/test_mmapper_hle_heap.py b/tools/test_mmapper_hle_heap.py +index ce100dbc..b19cccaa 100644 +--- a/tools/test_mmapper_hle_heap.py ++++ b/tools/test_mmapper_hle_heap.py +@@ -11,7 +11,7 @@ def main(): + return 0 + source = (ROOT / 'libs/system/sysPrxForUser.c').read_text() + begin = source.index('#define YZ_HEAP_BASE') +- end = source.index('/* _sys_heap_create_heap', begin) ++ end = source.index('/* The plain libc allocator sysPrxForUser exports', begin) + body = source[begin:end] + with tempfile.TemporaryDirectory(prefix='ps3-mmapper-hle-heap-') as tmp: + temp = Path(tmp) diff --git a/tasks/sp00nznet__ps3recomp-625/tests/test.sh b/tasks/sp00nznet__ps3recomp-625/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-625/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-625/tests/verifier.py b/tasks/sp00nznet__ps3recomp-625/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-625/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-634/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-634/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-634/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-634/instruction.md b/tasks/sp00nznet__ps3recomp-634/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0df57f430cfd1affdb5edee0ee340b4c2aaeac5 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-634/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** ppu: per-thread caches for HLE NID lookups, profiler breadcrumbs and indirect-call targets; exact VMX converts + +## Description + +## Why + +Profiles of God of War HD's (NPUA80490) main thread in gameplay showed runtime lookups, not guest work, in several hot spots: + +- `ps3_hle_call` scanned `g_ctx` (about a hundred entries) and then `g_hle_nids` (over a thousand) linearly on every call, at about 95k HLE calls a second: 6.5% of the main thread. +- `ppu_gcm_pump`, called on every HLE call and timer sleep, took the pump and swapped both pending words even with nothing pending: three atomic operations on lines the ticker thread writes. +- `ppu_prof_resolve_host`, which stamps every lv2 syscall's and HLE call's caller for the sampling profiler, did a binary search over every lifted function that missed the cache: a third of `lv2_syscall`. +- `ps3_indirect_call_impl` probed a 256k-slot table (3 MB with the addresses) and missed the cache, about a fifth of the function. +- `vcfux`, `vcfsx`, `vctsxs` and `vctuxs` called `ldexpf` per lane, which also kept those helpers out of line. + +## Change + +Three commits, which can be reviewed one at a time. + +- **ppu_hle**: a per-thread slot per NID keeps the `g_ctx` index or the table index, with the table sizes it was filled against, so a registration made after the first call is still found and no slot is read half-written. `ppu_gcm_pump` returns at once when nothing is pending; a notification posted just after the check is delivered by the next pump, as one posted while another thread holds the pump already is. +- **ppu: per-thread caches**: `ppu_prof_resolve_host` keeps each thread's last answer per call site (the inverse table is built once, so answers do not go stale); `ps3_indirect_call_impl` keeps each thread's last hits, tagged with a registration count that any later `ppu_register_function` bumps. +- **ppu_vmx**: `uimm` is 5 bits, so 2^-uimm and 2^uimm are normal floats and multiplying by them is exact. + +## Evidence + +- God of War HD, main thread samples in gameplay: `ps3_hle_call` 6.5% -> 1.5%, `lv2_syscall` 2.2% -> 1.0%, `ps3_indirect_call_impl` 3.1% -> 2.5%, `ppu_prof_resolve_host` 0.6% -> 0.2%; `vmx_vcfsx` was 0.8%. +- The VMX converts give the same results as `ldexpf` for every `uimm` over 12.8M operands each, signed and unsigned. +- Windows, clang-cl, Release: the runtime builds; every `tools/test_*.py` and `check_ppu_scaffold.py` give the same results as `master` on the same machine. +- Linux, gcc 15 (WSL Ubuntu): the PPU scaffold ratchet has no regression, and the self-contained test steps of `linux.yml` and every `tools/test_*.py` (the POSIX-only loader fixtures among them) give the same results as `master`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-634/solution/patch.diff b/tasks/sp00nznet__ps3recomp-634/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9ce51049a303b6393e5c6e2f7506491fcd3f4889 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-634/solution/patch.diff @@ -0,0 +1,197 @@ +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..3b991298 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -840,6 +840,13 @@ void* ppu_gcm_wait_pump(void (**pump)(void)) + + void ppu_gcm_pump(void) + { ++ /* Every HLE call and timer sleep pumps, tens of thousands of times a ++ * second, and almost always nothing is pending. Look before taking the ++ * pump and swapping the pending words out: three atomic operations on ++ * lines the ticker thread writes. A notification posted just after this ++ * read is delivered by the next pump, as one posted while another thread ++ * holds the pump is. */ ++ if (!s_gcm_pending && !s_user_pending) return; + if (!GCM_PUMP_TRY_ENTER()) return; + long p = (long)GCM_PENDING_TAKE(); + u64 user = GCM_USER_PENDING_TAKE(); +diff --git a/runtime/ppu/ppu_hle.cpp b/runtime/ppu/ppu_hle.cpp +index 15d4ef60..5148b384 100644 +--- a/runtime/ppu/ppu_hle.cpp ++++ b/runtime/ppu/ppu_hle.cpp +@@ -50,6 +50,33 @@ typedef void (*hle_ctx_fn)(ppu_context*); + static struct { uint32_t nid; hle_ctx_fn fn; const char* name; } g_ctx[HLE_CTX_CAP]; + static uint32_t g_ctx_count = 0; + ++/* NID -> handler, per calling thread. Both tables above are searched ++ * linearly, g_ctx with about a hundred entries and g_hle_nids with over a ++ * thousand, and a title calls a few imports tens of thousands of times a ++ * second: God of War HD makes ~95k HLE calls a second in gameplay, most of ++ * them cellGcmAddressToOffset and _sys_memcpy, and the two scans were most of ++ * ps3_hle_call's cost. A slot keeps the indexes and the table sizes it was ++ * filled against, so a registration made after the first call is still ++ * found. Per thread, so no slot is read half-written. */ ++struct HleSlot { uint32_t nid, ctx_n, tab_n; int32_t ctx_i, tab_i; }; ++static thread_local HleSlot t_hle_slot[1024]; ++static const HleSlot* hle_slot(uint32_t nid) ++{ ++ HleSlot* s = &t_hle_slot[(nid * 2654435761u) >> 22]; ++ const uint32_t ctx_n = g_ctx_count, tab_n = g_hle_inited ? g_hle_nids.count : 0; ++ if (s->nid != nid || s->ctx_n != ctx_n || s->tab_n != tab_n || (!s->ctx_n && !s->tab_n)) { ++ s->ctx_i = s->tab_i = -1; ++ for (uint32_t i = 0; i < ctx_n; i++) ++ if (g_ctx[i].nid == nid) { s->ctx_i = (int32_t)i; break; } ++ if (s->ctx_i < 0 && tab_n) { ++ const ps3_nid_entry* e = ps3_nid_table_find(&g_hle_nids, nid); ++ if (e) s->tab_i = (int32_t)(e - g_hle_nids.entries); ++ } ++ s->nid = nid; s->ctx_n = ctx_n; s->tab_n = tab_n; ++ } ++ return s; ++} ++ + extern "C" void ps3_hle_register_ctx(uint32_t nid, const char* name, hle_ctx_fn fn) + { + if (g_ctx_count < HLE_CTX_CAP) { +@@ -700,8 +727,9 @@ extern "C" void ps3_hle_call(uint32_t nid, ppu_context* ctx) + } + } + +- for (uint32_t i = 0; i < g_ctx_count; i++) +- if (g_ctx[i].nid == nid) { ++ const HleSlot* hs = hle_slot(nid); ++ if (hs->ctx_i >= 0) { ++ const uint32_t i = (uint32_t)hs->ctx_i; + ps3_msf("hle:%s", g_ctx[i].name); + /* Record the name here too. This loop dispatches every + * ps3_hle_register_ctx handler -- which is the whole sysPrxForUser +@@ -722,7 +750,7 @@ extern "C" void ps3_hle_call(uint32_t nid, ppu_context* ctx) + return; + } + +- ps3_nid_entry* e = g_hle_inited ? ps3_nid_table_find(&g_hle_nids, nid) : nullptr; ++ ps3_nid_entry* e = hs->tab_i >= 0 ? &g_hle_nids.entries[hs->tab_i] : nullptr; + if (!e || !e->handler) { + /* Recorded before the diagnostic paths below, several of which return + * early. An import moving between resolved and unresolved is exactly the +diff --git a/runtime/ppu/ppu_loader.cpp b/runtime/ppu/ppu_loader.cpp +index 9309f2d3..357dc2aa 100644 +--- a/runtime/ppu/ppu_loader.cpp ++++ b/runtime/ppu/ppu_loader.cpp +@@ -2139,6 +2139,7 @@ typedef void (*ppu_fn)(ppu_context*); + static uint32_t g_addr[PPU_HASH_SIZE]; + static ppu_fn g_fn[PPU_HASH_SIZE]; + static uint32_t g_fn_count = 0; ++static uint32_t g_fn_gen = 0; /* bumped by every registration; see ppu_lookup_icall */ + + extern "C" void ppu_register_function(uint64_t addr, ppu_fn fn) + { +@@ -2147,8 +2148,10 @@ extern "C" void ppu_register_function(uint64_t addr, ppu_fn fn) + /* Bounded probe: never loop past the whole table. A full table (function + * count >= PPU_HASH_SIZE) would otherwise spin forever here at startup. */ + for (uint32_t probes = 0; probes < PPU_HASH_SIZE; probes++) { +- if (g_fn[i] == nullptr) { g_addr[i] = a; g_fn[i] = fn; g_fn_count++; return; } +- if (g_addr[i] == a) { g_fn[i] = fn; return; } /* overwrite */ ++ if (g_fn[i] == nullptr) { g_addr[i] = a; g_fn[i] = fn; g_fn_count++; ++ __atomic_fetch_add(&g_fn_gen, 1u, __ATOMIC_RELEASE); return; } ++ if (g_addr[i] == a) { g_fn[i] = fn; /* overwrite */ ++ __atomic_fetch_add(&g_fn_gen, 1u, __ATOMIC_RELEASE); return; } + i = (i + 1) & PPU_HASH_MASK; + } + static int warned = 0; +@@ -2164,7 +2167,24 @@ extern "C" void ppu_register_function(uint64_t addr, ppu_fn fn) + * Built lazily on first use (registration is boot-time-only). */ + static struct { void* host; uint32_t guest; } g_inv[PPU_HASH_SIZE]; + static uint32_t g_inv_n = 0; ++static uint32_t ppu_prof_resolve_host_slow(void* ra); + extern "C" uint32_t ppu_prof_resolve_host(void* ra) ++{ ++ /* Every lv2 syscall and HLE call stamps its caller for the sampling ++ * profiler, and the binary search below missed the cache on most of its ++ * steps: in God of War HD gameplay it was a third of lv2_syscall. Call ++ * sites are few, so each thread keeps its last answer per site. The ++ * inverse table is built once, so an answer does not go stale. */ ++ struct RaSlot { void* ra; uint32_t guest; }; ++ static PPU_THREAD_LOCAL RaSlot t_ra[256]; ++ RaSlot& slot = t_ra[((uintptr_t)ra >> 2) & 255u]; ++ if (slot.ra == ra && g_inv_n) return slot.guest; ++ const uint32_t g = ppu_prof_resolve_host_slow(ra); ++ if (g_inv_n) { slot.ra = ra; slot.guest = g; } ++ return g; ++} ++ ++static uint32_t ppu_prof_resolve_host_slow(void* ra) + { + if (!g_inv_n) { + for (uint32_t i = 0; i < PPU_HASH_SIZE; i++) +@@ -2185,6 +2205,25 @@ extern "C" uint32_t ppu_prof_resolve_host(void* ra) + return lo ? g_inv[lo - 1].guest : 0; + } + ++static ppu_fn ppu_lookup(uint32_t a); ++ ++/* ppu_lookup for indirect calls. The table and its addresses are 3 MB, so the ++ * probe of an indirect call missed the cache: about a fifth of ++ * ps3_indirect_call_impl in God of War HD gameplay. Targets repeat (vtables, ++ * callbacks), so each thread keeps its last hits, tagged with the registration ++ * count they were found under; any later registration retires them. */ ++static ppu_fn ppu_lookup_icall(uint32_t a) ++{ ++ struct IcSlot { uint32_t addr, gen; ppu_fn fn; }; ++ static PPU_THREAD_LOCAL IcSlot t_ic[512]; ++ IcSlot& s = t_ic[(a >> 2) & 511u]; ++ const uint32_t gen = __atomic_load_n(&g_fn_gen, __ATOMIC_ACQUIRE); ++ if (s.fn && s.addr == a && s.gen == gen) return s.fn; ++ ppu_fn fn = ppu_lookup(a); ++ if (fn) { s.addr = a; s.gen = gen; s.fn = fn; } ++ return fn; ++} ++ + static ppu_fn ppu_lookup(uint32_t a) + { + uint32_t i = (a * 2654435761u) & PPU_HASH_MASK; +@@ -2844,7 +2883,7 @@ static void ps3_indirect_call_impl(ppu_context* ctx) + } + } + +- ppu_fn fn = ppu_lookup(addr); ++ ppu_fn fn = ppu_lookup_icall(addr); + if (!fn) { + /* OPD-swap clobber fixup: a malformed memcpy (game func_0036FA74) writes + * some handler/vtable OPDs as {TOC, func} (code & toc SWAPPED), so lifted +diff --git a/runtime/ppu/ppu_vmx.h b/runtime/ppu/ppu_vmx.h +index 35052c67..c278eb06 100644 +--- a/runtime/ppu/ppu_vmx.h ++++ b/runtime/ppu/ppu_vmx.h +@@ -300,20 +300,25 @@ VMX_FUN(vmx_vrfiz, truncf(f), 0, 2) + VMX_FUN(vmx_vrfip, ceilf(f), 1, 2) + VMX_FUN(vmx_vrfim, floorf(f), 1, 2) + +-/* int <-> float with a 2^uimm scale */ ++/* int <-> float with a 2^uimm scale. uimm is 5 bits, so 2^-uimm and 2^uimm are ++ * normal floats and the scaling is exact: the same results as ldexpf, without ++ * a libm call per lane (which also kept these helpers out of line). */ ++VMX_INL float vmx_pow2(int e) { return vmx_f((uint32_t)(127 + e) << 23); } + VMX_INL void vmx_vcfux(VMX_D, VMX_B, unsigned uimm) { const uint8_t* b = (const uint8_t*)b_; uint8_t r[16]; +- for (int i = 0; i < 4; i++) vmx_sw(r, i, vmx_u(ldexpf((float)vmx_w(b, i), -(int)uimm))); VMX_OUT; } ++ const float s = vmx_pow2(-(int)(uimm & 31u)); ++ for (int i = 0; i < 4; i++) vmx_sw(r, i, vmx_u((float)vmx_w(b, i) * s)); VMX_OUT; } + VMX_INL void vmx_vcfsx(VMX_D, VMX_B, unsigned uimm) { const uint8_t* b = (const uint8_t*)b_; uint8_t r[16]; +- for (int i = 0; i < 4; i++) vmx_sw(r, i, vmx_u(ldexpf((float)(int32_t)vmx_w(b, i), -(int)uimm))); VMX_OUT; } ++ const float s = vmx_pow2(-(int)(uimm & 31u)); ++ for (int i = 0; i < 4; i++) vmx_sw(r, i, vmx_u((float)(int32_t)vmx_w(b, i) * s)); VMX_OUT; } + VMX_INL void vmx_vctsxs(VMX_D, VMX_B, unsigned uimm, uint32_t* vscr) { const uint8_t* b = (const uint8_t*)b_; uint8_t r[16]; +- for (int i = 0; i < 4; i++) { float f = vmx_f(vmx_w(b, i)) * ldexpf(1.0f, (int)uimm); int32_t v; ++ for (int i = 0; i < 4; i++) { float f = vmx_f(vmx_w(b, i)) * vmx_pow2((int)(uimm & 31u)); int32_t v; + if (f != f) v = 0; + else if (f < -2147483648.0f) { v = INT32_MIN; *vscr |= VMX_SAT; } + else if (f >= 2147483648.0f) { v = INT32_MAX; *vscr |= VMX_SAT; } + else v = (int32_t)f; + vmx_sw(r, i, (uint32_t)v); } VMX_OUT; } + VMX_INL void vmx_vctuxs(VMX_D, VMX_B, unsigned uimm, uint32_t* vscr) { const uint8_t* b = (const uint8_t*)b_; uint8_t r[16]; +- for (int i = 0; i < 4; i++) { float f = vmx_f(vmx_w(b, i)) * ldexpf(1.0f, (int)uimm); uint32_t v; ++ for (int i = 0; i < 4; i++) { float f = vmx_f(vmx_w(b, i)) * vmx_pow2((int)(uimm & 31u)); uint32_t v; + if (f != f) v = 0; + else if (f < 0.0f) { v = 0; *vscr |= VMX_SAT; } + else if (f >= 4294967296.0f) { v = 0xFFFFFFFFu; *vscr |= VMX_SAT; } diff --git a/tasks/sp00nznet__ps3recomp-634/solution/solve.sh b/tasks/sp00nznet__ps3recomp-634/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-634/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-634/task.toml b/tasks/sp00nznet__ps3recomp-634/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..66359bbde8512017bd1c70c2f0ea583ce81b8440 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-634/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-634" +description = "ppu: per-thread caches for HLE NID lookups, profiler breadcrumbs and indirect-call targets; exact VMX converts" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/634" +source_access = "auto" +built_at = "2026-11-16T16:09:59.664388+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:bd6c2cbdf66c5e2c6377391d2050b73d8f4eab4bdaf7b7d7fa265ad01387c8bf" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/video/cellGcmSys.c", + "runtime/ppu/ppu_hle.cpp", + "runtime/ppu/ppu_loader.cpp", + "runtime/ppu/ppu_vmx.h", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 101 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.138284+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-634/tests/capture.py b/tasks/sp00nznet__ps3recomp-634/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-634/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-634/tests/instruction.md b/tasks/sp00nznet__ps3recomp-634/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0df57f430cfd1affdb5edee0ee340b4c2aaeac5 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-634/tests/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** ppu: per-thread caches for HLE NID lookups, profiler breadcrumbs and indirect-call targets; exact VMX converts + +## Description + +## Why + +Profiles of God of War HD's (NPUA80490) main thread in gameplay showed runtime lookups, not guest work, in several hot spots: + +- `ps3_hle_call` scanned `g_ctx` (about a hundred entries) and then `g_hle_nids` (over a thousand) linearly on every call, at about 95k HLE calls a second: 6.5% of the main thread. +- `ppu_gcm_pump`, called on every HLE call and timer sleep, took the pump and swapped both pending words even with nothing pending: three atomic operations on lines the ticker thread writes. +- `ppu_prof_resolve_host`, which stamps every lv2 syscall's and HLE call's caller for the sampling profiler, did a binary search over every lifted function that missed the cache: a third of `lv2_syscall`. +- `ps3_indirect_call_impl` probed a 256k-slot table (3 MB with the addresses) and missed the cache, about a fifth of the function. +- `vcfux`, `vcfsx`, `vctsxs` and `vctuxs` called `ldexpf` per lane, which also kept those helpers out of line. + +## Change + +Three commits, which can be reviewed one at a time. + +- **ppu_hle**: a per-thread slot per NID keeps the `g_ctx` index or the table index, with the table sizes it was filled against, so a registration made after the first call is still found and no slot is read half-written. `ppu_gcm_pump` returns at once when nothing is pending; a notification posted just after the check is delivered by the next pump, as one posted while another thread holds the pump already is. +- **ppu: per-thread caches**: `ppu_prof_resolve_host` keeps each thread's last answer per call site (the inverse table is built once, so answers do not go stale); `ps3_indirect_call_impl` keeps each thread's last hits, tagged with a registration count that any later `ppu_register_function` bumps. +- **ppu_vmx**: `uimm` is 5 bits, so 2^-uimm and 2^uimm are normal floats and multiplying by them is exact. + +## Evidence + +- God of War HD, main thread samples in gameplay: `ps3_hle_call` 6.5% -> 1.5%, `lv2_syscall` 2.2% -> 1.0%, `ps3_indirect_call_impl` 3.1% -> 2.5%, `ppu_prof_resolve_host` 0.6% -> 0.2%; `vmx_vcfsx` was 0.8%. +- The VMX converts give the same results as `ldexpf` for every `uimm` over 12.8M operands each, signed and unsigned. +- Windows, clang-cl, Release: the runtime builds; every `tools/test_*.py` and `check_ppu_scaffold.py` give the same results as `master` on the same machine. +- Linux, gcc 15 (WSL Ubuntu): the PPU scaffold ratchet has no regression, and the self-contained test steps of `linux.yml` and every `tools/test_*.py` (the POSIX-only loader fixtures among them) give the same results as `master`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-634/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-634/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9ce51049a303b6393e5c6e2f7506491fcd3f4889 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-634/tests/oracle.patch @@ -0,0 +1,197 @@ +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..3b991298 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -840,6 +840,13 @@ void* ppu_gcm_wait_pump(void (**pump)(void)) + + void ppu_gcm_pump(void) + { ++ /* Every HLE call and timer sleep pumps, tens of thousands of times a ++ * second, and almost always nothing is pending. Look before taking the ++ * pump and swapping the pending words out: three atomic operations on ++ * lines the ticker thread writes. A notification posted just after this ++ * read is delivered by the next pump, as one posted while another thread ++ * holds the pump is. */ ++ if (!s_gcm_pending && !s_user_pending) return; + if (!GCM_PUMP_TRY_ENTER()) return; + long p = (long)GCM_PENDING_TAKE(); + u64 user = GCM_USER_PENDING_TAKE(); +diff --git a/runtime/ppu/ppu_hle.cpp b/runtime/ppu/ppu_hle.cpp +index 15d4ef60..5148b384 100644 +--- a/runtime/ppu/ppu_hle.cpp ++++ b/runtime/ppu/ppu_hle.cpp +@@ -50,6 +50,33 @@ typedef void (*hle_ctx_fn)(ppu_context*); + static struct { uint32_t nid; hle_ctx_fn fn; const char* name; } g_ctx[HLE_CTX_CAP]; + static uint32_t g_ctx_count = 0; + ++/* NID -> handler, per calling thread. Both tables above are searched ++ * linearly, g_ctx with about a hundred entries and g_hle_nids with over a ++ * thousand, and a title calls a few imports tens of thousands of times a ++ * second: God of War HD makes ~95k HLE calls a second in gameplay, most of ++ * them cellGcmAddressToOffset and _sys_memcpy, and the two scans were most of ++ * ps3_hle_call's cost. A slot keeps the indexes and the table sizes it was ++ * filled against, so a registration made after the first call is still ++ * found. Per thread, so no slot is read half-written. */ ++struct HleSlot { uint32_t nid, ctx_n, tab_n; int32_t ctx_i, tab_i; }; ++static thread_local HleSlot t_hle_slot[1024]; ++static const HleSlot* hle_slot(uint32_t nid) ++{ ++ HleSlot* s = &t_hle_slot[(nid * 2654435761u) >> 22]; ++ const uint32_t ctx_n = g_ctx_count, tab_n = g_hle_inited ? g_hle_nids.count : 0; ++ if (s->nid != nid || s->ctx_n != ctx_n || s->tab_n != tab_n || (!s->ctx_n && !s->tab_n)) { ++ s->ctx_i = s->tab_i = -1; ++ for (uint32_t i = 0; i < ctx_n; i++) ++ if (g_ctx[i].nid == nid) { s->ctx_i = (int32_t)i; break; } ++ if (s->ctx_i < 0 && tab_n) { ++ const ps3_nid_entry* e = ps3_nid_table_find(&g_hle_nids, nid); ++ if (e) s->tab_i = (int32_t)(e - g_hle_nids.entries); ++ } ++ s->nid = nid; s->ctx_n = ctx_n; s->tab_n = tab_n; ++ } ++ return s; ++} ++ + extern "C" void ps3_hle_register_ctx(uint32_t nid, const char* name, hle_ctx_fn fn) + { + if (g_ctx_count < HLE_CTX_CAP) { +@@ -700,8 +727,9 @@ extern "C" void ps3_hle_call(uint32_t nid, ppu_context* ctx) + } + } + +- for (uint32_t i = 0; i < g_ctx_count; i++) +- if (g_ctx[i].nid == nid) { ++ const HleSlot* hs = hle_slot(nid); ++ if (hs->ctx_i >= 0) { ++ const uint32_t i = (uint32_t)hs->ctx_i; + ps3_msf("hle:%s", g_ctx[i].name); + /* Record the name here too. This loop dispatches every + * ps3_hle_register_ctx handler -- which is the whole sysPrxForUser +@@ -722,7 +750,7 @@ extern "C" void ps3_hle_call(uint32_t nid, ppu_context* ctx) + return; + } + +- ps3_nid_entry* e = g_hle_inited ? ps3_nid_table_find(&g_hle_nids, nid) : nullptr; ++ ps3_nid_entry* e = hs->tab_i >= 0 ? &g_hle_nids.entries[hs->tab_i] : nullptr; + if (!e || !e->handler) { + /* Recorded before the diagnostic paths below, several of which return + * early. An import moving between resolved and unresolved is exactly the +diff --git a/runtime/ppu/ppu_loader.cpp b/runtime/ppu/ppu_loader.cpp +index 9309f2d3..357dc2aa 100644 +--- a/runtime/ppu/ppu_loader.cpp ++++ b/runtime/ppu/ppu_loader.cpp +@@ -2139,6 +2139,7 @@ typedef void (*ppu_fn)(ppu_context*); + static uint32_t g_addr[PPU_HASH_SIZE]; + static ppu_fn g_fn[PPU_HASH_SIZE]; + static uint32_t g_fn_count = 0; ++static uint32_t g_fn_gen = 0; /* bumped by every registration; see ppu_lookup_icall */ + + extern "C" void ppu_register_function(uint64_t addr, ppu_fn fn) + { +@@ -2147,8 +2148,10 @@ extern "C" void ppu_register_function(uint64_t addr, ppu_fn fn) + /* Bounded probe: never loop past the whole table. A full table (function + * count >= PPU_HASH_SIZE) would otherwise spin forever here at startup. */ + for (uint32_t probes = 0; probes < PPU_HASH_SIZE; probes++) { +- if (g_fn[i] == nullptr) { g_addr[i] = a; g_fn[i] = fn; g_fn_count++; return; } +- if (g_addr[i] == a) { g_fn[i] = fn; return; } /* overwrite */ ++ if (g_fn[i] == nullptr) { g_addr[i] = a; g_fn[i] = fn; g_fn_count++; ++ __atomic_fetch_add(&g_fn_gen, 1u, __ATOMIC_RELEASE); return; } ++ if (g_addr[i] == a) { g_fn[i] = fn; /* overwrite */ ++ __atomic_fetch_add(&g_fn_gen, 1u, __ATOMIC_RELEASE); return; } + i = (i + 1) & PPU_HASH_MASK; + } + static int warned = 0; +@@ -2164,7 +2167,24 @@ extern "C" void ppu_register_function(uint64_t addr, ppu_fn fn) + * Built lazily on first use (registration is boot-time-only). */ + static struct { void* host; uint32_t guest; } g_inv[PPU_HASH_SIZE]; + static uint32_t g_inv_n = 0; ++static uint32_t ppu_prof_resolve_host_slow(void* ra); + extern "C" uint32_t ppu_prof_resolve_host(void* ra) ++{ ++ /* Every lv2 syscall and HLE call stamps its caller for the sampling ++ * profiler, and the binary search below missed the cache on most of its ++ * steps: in God of War HD gameplay it was a third of lv2_syscall. Call ++ * sites are few, so each thread keeps its last answer per site. The ++ * inverse table is built once, so an answer does not go stale. */ ++ struct RaSlot { void* ra; uint32_t guest; }; ++ static PPU_THREAD_LOCAL RaSlot t_ra[256]; ++ RaSlot& slot = t_ra[((uintptr_t)ra >> 2) & 255u]; ++ if (slot.ra == ra && g_inv_n) return slot.guest; ++ const uint32_t g = ppu_prof_resolve_host_slow(ra); ++ if (g_inv_n) { slot.ra = ra; slot.guest = g; } ++ return g; ++} ++ ++static uint32_t ppu_prof_resolve_host_slow(void* ra) + { + if (!g_inv_n) { + for (uint32_t i = 0; i < PPU_HASH_SIZE; i++) +@@ -2185,6 +2205,25 @@ extern "C" uint32_t ppu_prof_resolve_host(void* ra) + return lo ? g_inv[lo - 1].guest : 0; + } + ++static ppu_fn ppu_lookup(uint32_t a); ++ ++/* ppu_lookup for indirect calls. The table and its addresses are 3 MB, so the ++ * probe of an indirect call missed the cache: about a fifth of ++ * ps3_indirect_call_impl in God of War HD gameplay. Targets repeat (vtables, ++ * callbacks), so each thread keeps its last hits, tagged with the registration ++ * count they were found under; any later registration retires them. */ ++static ppu_fn ppu_lookup_icall(uint32_t a) ++{ ++ struct IcSlot { uint32_t addr, gen; ppu_fn fn; }; ++ static PPU_THREAD_LOCAL IcSlot t_ic[512]; ++ IcSlot& s = t_ic[(a >> 2) & 511u]; ++ const uint32_t gen = __atomic_load_n(&g_fn_gen, __ATOMIC_ACQUIRE); ++ if (s.fn && s.addr == a && s.gen == gen) return s.fn; ++ ppu_fn fn = ppu_lookup(a); ++ if (fn) { s.addr = a; s.gen = gen; s.fn = fn; } ++ return fn; ++} ++ + static ppu_fn ppu_lookup(uint32_t a) + { + uint32_t i = (a * 2654435761u) & PPU_HASH_MASK; +@@ -2844,7 +2883,7 @@ static void ps3_indirect_call_impl(ppu_context* ctx) + } + } + +- ppu_fn fn = ppu_lookup(addr); ++ ppu_fn fn = ppu_lookup_icall(addr); + if (!fn) { + /* OPD-swap clobber fixup: a malformed memcpy (game func_0036FA74) writes + * some handler/vtable OPDs as {TOC, func} (code & toc SWAPPED), so lifted +diff --git a/runtime/ppu/ppu_vmx.h b/runtime/ppu/ppu_vmx.h +index 35052c67..c278eb06 100644 +--- a/runtime/ppu/ppu_vmx.h ++++ b/runtime/ppu/ppu_vmx.h +@@ -300,20 +300,25 @@ VMX_FUN(vmx_vrfiz, truncf(f), 0, 2) + VMX_FUN(vmx_vrfip, ceilf(f), 1, 2) + VMX_FUN(vmx_vrfim, floorf(f), 1, 2) + +-/* int <-> float with a 2^uimm scale */ ++/* int <-> float with a 2^uimm scale. uimm is 5 bits, so 2^-uimm and 2^uimm are ++ * normal floats and the scaling is exact: the same results as ldexpf, without ++ * a libm call per lane (which also kept these helpers out of line). */ ++VMX_INL float vmx_pow2(int e) { return vmx_f((uint32_t)(127 + e) << 23); } + VMX_INL void vmx_vcfux(VMX_D, VMX_B, unsigned uimm) { const uint8_t* b = (const uint8_t*)b_; uint8_t r[16]; +- for (int i = 0; i < 4; i++) vmx_sw(r, i, vmx_u(ldexpf((float)vmx_w(b, i), -(int)uimm))); VMX_OUT; } ++ const float s = vmx_pow2(-(int)(uimm & 31u)); ++ for (int i = 0; i < 4; i++) vmx_sw(r, i, vmx_u((float)vmx_w(b, i) * s)); VMX_OUT; } + VMX_INL void vmx_vcfsx(VMX_D, VMX_B, unsigned uimm) { const uint8_t* b = (const uint8_t*)b_; uint8_t r[16]; +- for (int i = 0; i < 4; i++) vmx_sw(r, i, vmx_u(ldexpf((float)(int32_t)vmx_w(b, i), -(int)uimm))); VMX_OUT; } ++ const float s = vmx_pow2(-(int)(uimm & 31u)); ++ for (int i = 0; i < 4; i++) vmx_sw(r, i, vmx_u((float)(int32_t)vmx_w(b, i) * s)); VMX_OUT; } + VMX_INL void vmx_vctsxs(VMX_D, VMX_B, unsigned uimm, uint32_t* vscr) { const uint8_t* b = (const uint8_t*)b_; uint8_t r[16]; +- for (int i = 0; i < 4; i++) { float f = vmx_f(vmx_w(b, i)) * ldexpf(1.0f, (int)uimm); int32_t v; ++ for (int i = 0; i < 4; i++) { float f = vmx_f(vmx_w(b, i)) * vmx_pow2((int)(uimm & 31u)); int32_t v; + if (f != f) v = 0; + else if (f < -2147483648.0f) { v = INT32_MIN; *vscr |= VMX_SAT; } + else if (f >= 2147483648.0f) { v = INT32_MAX; *vscr |= VMX_SAT; } + else v = (int32_t)f; + vmx_sw(r, i, (uint32_t)v); } VMX_OUT; } + VMX_INL void vmx_vctuxs(VMX_D, VMX_B, unsigned uimm, uint32_t* vscr) { const uint8_t* b = (const uint8_t*)b_; uint8_t r[16]; +- for (int i = 0; i < 4; i++) { float f = vmx_f(vmx_w(b, i)) * ldexpf(1.0f, (int)uimm); uint32_t v; ++ for (int i = 0; i < 4; i++) { float f = vmx_f(vmx_w(b, i)) * vmx_pow2((int)(uimm & 31u)); uint32_t v; + if (f != f) v = 0; + else if (f < 0.0f) { v = 0; *vscr |= VMX_SAT; } + else if (f >= 4294967296.0f) { v = 0xFFFFFFFFu; *vscr |= VMX_SAT; } diff --git a/tasks/sp00nznet__ps3recomp-634/tests/test.sh b/tasks/sp00nznet__ps3recomp-634/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-634/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-634/tests/verifier.py b/tasks/sp00nznet__ps3recomp-634/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-634/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-636/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-636/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-636/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-636/instruction.md b/tasks/sp00nznet__ps3recomp-636/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1b858a592ae56670bb952e59ef3812c5a4a64ee --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-636/instruction.md @@ -0,0 +1,62 @@ +# Issue + +**Title:** spu: relocatable lifts for position-independent code placed anywhere in LS + +## Description + +## What + +Lift position-independent SPU code **once** and run it wherever a title copies it in local store. + +Some titles stage job code in LS at an address that changes from load to load. God of War: Ascension's `BatchJobList` jobs copy four EBOOT code blobs to a new 16-byte-aligned address every time: one capture saw 299 loads at 299 different addresses. A lift per placement (`spu_overlay_register_region_at`) cannot cover that. The code itself is position-independent: a `brsl $rX, .+4` pc-getter plus offsets, with no absolute branches and no `lqa`/`stqa` into itself. + +- **`tools/spu_lifter.py --reloc`**: + - Lifts at a canonical `--base` as usual. + - Every address the code derives from its own pc adds `ctx->reloc_delta`: link values of `brsl`/`bisl`/`bisled`, `lqr`/`stqr` addresses, `SPU_DIRECT` transfer pcs, `spu_drain_call` return pcs, and the indirect-dispatch stubs. + - All of these go through one helper (`SPULifter._pc`), so the generated code is unchanged without `--reloc`. + - Around nested `brsl`/`bisl` calls the generated code saves and restores `reloc_delta`, as it already does for the image id. +- **`spu_overlay_register_region_reloc(ea, span, canon, image_id)`**: + - A GET of that content at **any** LS address makes the copy resident. A relocatable image reuses its previous placement's resident slot. + - `spu_lifted_lookup` (which `spu_indirect_branch` resolves through) looks the function up at `canon + (pc - placement)` and sets `ctx->reloc_delta = placement - canon` before running it. + - The dispatch-cache entry stores the delta too, so a cache hit restores it. The entry is already dropped when a slot's placement changes. +- **`spu_context`**: `resident_code[].canon` (0 = an ordinary placed lift) and `int32_t reloc_delta`. +- **`SPU_INTERP_STATS`**: interpreter entries inside resident relocatable code are counted at the **canonical** pc, so they can be passed back as `--extra-funcs`. +- **Test**: `test_reloc_regions` in `runtime/spu/tests/test_spu_lifted_start.c`. It covers refused registrations, a GET at any address making the copy resident, lookup at canon + offset setting the delta, a cache hit restoring it, and a new placement taking over the slot while the old one stops being served. +- **`SPU_RELOC_OFF=1`**: skips the registration and leaves that code interpreted, for A/B tests. + +Nothing changes for a title that does not call `spu_overlay_register_region_reloc`. + +## Evidence (God of War: Ascension, Windows, Vulkan backend) + +Measured in our port on our v0.17-based fork, whose diagnostics (`SPU_INTERP_MISS`, `SPURS_PM_PROF`, `PS3_FTRACE`) are not part of this PR. + +Interpreter time, `SPU_INTERP_MISS=1`, same scene. These are real log lines from the two runs. + +``` +before: [interp-miss] 13590.8 ms interpreted in 20 s, top targets: +after: [interp-miss] 4536.1 ms interpreted in 20 s, top targets: +``` + +`SPURS_PM_PROF` for the workload: `w7=77%/23390i87%` before, `w7=29%/21063i64%` after. That is busy 77% → 29%, and the interpreted share 87% → 64%. The rest comes from code outside the four blobs. + +The main thread's wait on that workload, per 60 s, from a `PS3_FTRACE` timeline of one build with and without the lifts: + +``` +SPU_RELOC_OFF=1: site 00464F84: 9.55 s waited in 60 s (787 spans) +SPU_RELOC_OFF=0: site 00464F84: 4.00 s waited in 60 s (691 spans) +``` + +No hang, and clean frame dumps in every run. + +The frame rate is **neutral on this title**: the frame then waits on another workload. So the port ships with `SPU_RELOC_OFF=1` for now. The value of this PR is coverage of the code itself. + +**Not yet verified:** +- other titles; +- the Linux build; +- code that materializes its own address through `ila`/`il` constants, which `--reloc` does not rewrite. The code here never does that. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-636/solution/patch.diff b/tasks/sp00nznet__ps3recomp-636/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..56232dcbe99ec1186fa5412c6c6e629dd5dd6258 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-636/solution/patch.diff @@ -0,0 +1,418 @@ +diff --git a/runtime/spu/spu_channels.c b/runtime/spu/spu_channels.c +index 5fc50208..2b32d1b0 100644 +--- a/runtime/spu/spu_channels.c ++++ b/runtime/spu/spu_channels.c +@@ -1715,7 +1715,7 @@ int spu_have_function(uint32_t addr) + * through would execute stale code registered under another image. Task and + * unbounded overlay misses retain their existing primary-image fallback. */ + static int spu_overlay_resident_verified(spu_context* ctx, unsigned slot); +-static spu_lifted_fn spu_lifted_lookup_full(const spu_context* ctx, uint32_t lsa) ++static spu_lifted_fn spu_lifted_lookup_full(const spu_context* ctx, uint32_t lsa, int* reloc) + { + /* Every probe below goes through #436's per-thread memo rather than + * spu_lookup() directly: the resolver makes up to three of them per +@@ -1730,7 +1730,18 @@ static spu_lifted_fn spu_lifted_lookup_full(const spu_context* ctx, uint32_t lsa + * unverified: other images' functions there would be stale. */ + if (ctx->resident_code[slot].verify_state && + !spu_overlay_resident_verified((spu_context*)ctx, slot)) return NULL; +- return (spu_lifted_fn)spu_lookup_memoized(lsa, ctx->resident_code[slot].image_id); ++ const uint32_t canon = ctx->resident_code[slot].canon; ++ if (!canon) ++ return (spu_lifted_fn)spu_lookup_memoized(lsa, ctx->resident_code[slot].image_id); ++ /* Relocatable code (spu_overlay_register_region_reloc): its lift sits at ++ * canon + offset. The caller runs the function next, so set its delta now. */ ++ spu_fn f = spu_lookup_memoized(lsa - ctx->resident_code[slot].lsa + canon, ++ ctx->resident_code[slot].image_id); ++ if (f) { ++ ((spu_context*)ctx)->reloc_delta = (int32_t)(ctx->resident_code[slot].lsa - canon); ++ if (reloc) *reloc = 1; ++ } ++ return (spu_lifted_fn)f; + } + spu_fn fn = NULL; + if (ctx->resident_task) fn = spu_lookup_memoized(lsa, ctx->resident_task); +@@ -1762,6 +1773,10 @@ typedef struct { + spu_lifted_fn fn; + uint32_t id, lsa, rgen, residency; + int image, ovl, task; ++ /* A relocatable resolution also sets ctx->reloc_delta, which a hit must ++ * repeat: residency fixes the placement, so the delta is part of the answer. */ ++ int reloc; ++ int32_t reloc_delta; + } spu_dcache_ent; + #define SPU_DCACHE_ENTRIES 512u + static SPU_TLS spu_dcache_ent t_dcache[SPU_DCACHE_ENTRIES]; +@@ -1792,7 +1807,7 @@ static void spu_dcache_shadow_stats(void) + spu_lifted_fn spu_lifted_lookup(const spu_context* ctx, uint32_t lsa) + { + const int mode = spu_dcache_mode(); +- if (!mode || !ctx) return spu_lifted_lookup_full(ctx, lsa); ++ if (!mode || !ctx) return spu_lifted_lookup_full(ctx, lsa, NULL); + spu_context* c = (spu_context*)ctx; + uint32_t id = c->dcache_id; + if (!id) { +@@ -1806,9 +1821,10 @@ spu_lifted_fn spu_lifted_lookup(const spu_context* ctx, uint32_t lsa) + if (e->fn && e->id == id && e->lsa == lsa && e->rgen == rgen && + e->residency == c->dcache_residency && e->image == c->image_id && + e->ovl == c->resident_ovl && e->task == c->resident_task) { ++ if (e->reloc) c->reloc_delta = e->reloc_delta; + if (mode == 2) { + __atomic_fetch_add(&s_dcache_hits, 1, __ATOMIC_RELAXED); +- const spu_lifted_fn full = spu_lifted_lookup_full(ctx, lsa); ++ const spu_lifted_fn full = spu_lifted_lookup_full(ctx, lsa, NULL); + if (full != e->fn) { + if (__atomic_fetch_add(&s_dcache_shadow_bad, 1, __ATOMIC_RELAXED) < 16) + fprintf(stderr, "[spu-dcache] shadow mismatch img=%d ovl=%d task=%d lsa=0x%05X " +@@ -1825,13 +1841,15 @@ spu_lifted_fn spu_lifted_lookup(const spu_context* ctx, uint32_t lsa) + __atomic_fetch_add(&s_dcache_misses, 1, __ATOMIC_RELAXED); + spu_dcache_shadow_stats(); + } +- const spu_lifted_fn fn = spu_lifted_lookup_full(ctx, lsa); ++ int reloc = 0; ++ const spu_lifted_fn fn = spu_lifted_lookup_full(ctx, lsa, &reloc); + if (fn) { + /* The resolver may have verified a pending slot; the entry records the + * residency it resolved against, read after it. */ + e->fn = fn; e->id = id; e->lsa = lsa; e->rgen = rgen; + e->residency = c->dcache_residency; e->image = c->image_id; + e->ovl = c->resident_ovl; e->task = c->resident_task; ++ e->reloc = reloc; e->reloc_delta = c->reloc_delta; + } + return fn; + } +@@ -1842,7 +1860,8 @@ spu_lifted_fn spu_lifted_lookup(const spu_context* ctx, uint32_t lsa) + * marks that overlay resident in the streaming context; dispatch retries a + * primary-image miss against the resident overlay's registry. */ + typedef struct { uint32_t src_ea; int image_id; uint8_t sig[16]; int has_sig; uint32_t span; +- uint32_t load_lsa; unsigned code_count; spu_overlay_code_segment* code; } spu_ovl_src; ++ uint32_t load_lsa; unsigned code_count; spu_overlay_code_segment* code; ++ uint32_t canon; } spu_ovl_src; + /* 6 FMOD codec/DSP overlays + up to 89 WWS job-code modules (all stream into + * the same job code buffer at LS 0x4000, dispatched by content signature). */ + #define SPU_OVL_SRC_MAX 128 +@@ -1894,6 +1913,7 @@ void spu_overlay_register_source(uint32_t content_ea, int image_id) + s_ovl_src[s_ovl_src_count].src_ea = content_ea; + s_ovl_src[s_ovl_src_count].image_id = image_id; + s_ovl_src[s_ovl_src_count].has_sig = 0; ++ s_ovl_src[s_ovl_src_count].canon = 0; + __atomic_store_n(&s_ovl_src_count, s_ovl_src_count + 1, __ATOMIC_RELEASE); + } + } +@@ -1907,6 +1927,22 @@ void spu_overlay_register_region(uint32_t content_ea, uint32_t span, int image_i + s_ovl_src[s_ovl_src_count - 1].span = span; + } + ++/* And for position-independent code the title copies to a different LS address at each ++ * load (GoW:A's BatchJobList jobs place four EBOOT blobs at a new 16-byte-aligned address ++ * every time): lifted ONCE at a canonical base with spu_lifter.py --reloc. A GET of the ++ * content at any address makes that copy resident; dispatch then looks the function up at ++ * canon + offset and sets ctx->reloc_delta, which the lifted code adds to every address ++ * it derives from its own pc. */ ++void spu_overlay_register_region_reloc(uint32_t content_ea, uint32_t span, uint32_t canon, int image_id) ++{ ++ if (!canon || canon >= SPU_LS_SIZE || span > SPU_LS_SIZE - canon) return; ++ { static int s_off = -1; if (s_off < 0) { const char* e = getenv("SPU_RELOC_OFF"); s_off = e && e[0] == '1'; } ++ if (s_off) return; } /* SPU_RELOC_OFF=1: leave that code to the interpreter (A/B) */ ++ const int n = s_ovl_src_count; ++ spu_overlay_register_region(content_ea, span, image_id); ++ if (s_ovl_src_count == n + 1) s_ovl_src[n].canon = canon; ++} ++ + /* Residency proves which load happened, not what the bytes are: the source EA + * could hold different content than was lifted. Compare the lifted segments + * once per load, at the first dispatch into the span, instead of at every +@@ -2159,7 +2195,10 @@ void spu_overlay_note_get(spu_context* ctx, uint32_t ea, const uint8_t* ls, uint + /* Verified code was lifted for one load address. */ + if (o->code && lsa != o->load_lsa) continue; + for (unsigned slot = 0; slot < 4; ++slot) { +- if (ctx->resident_code[slot].image_id && ctx->resident_code[slot].lsa != lsa) ++ /* A relocatable image takes over its own previous placement's slot: each load ++ * lands somewhere new, and stale copies would fill the slots. */ ++ if (ctx->resident_code[slot].image_id && ctx->resident_code[slot].lsa != lsa && ++ !(o->canon && ctx->resident_code[slot].image_id == o->image_id)) + continue; + ctx->resident_code[slot].lsa = lsa; + ctx->resident_code[slot].size = o->span; +@@ -2167,6 +2206,7 @@ void spu_overlay_note_get(spu_context* ctx, uint32_t ea, const uint8_t* ls, uint + ctx->resident_code[slot].image_id = o->image_id; + ctx->resident_code[slot].verify_state = o->code ? SPU_OVERLAY_PENDING : 0; + ctx->resident_code[slot].source_index = i; ++ ctx->resident_code[slot].canon = o->canon; + spu_dcache_residency_changed(ctx); + return; + } +diff --git a/runtime/spu/spu_context.h b/runtime/spu/spu_context.h +index c5ccbec7..84c0120a 100644 +--- a/runtime/spu/spu_context.h ++++ b/runtime/spu/spu_context.h +@@ -302,7 +302,15 @@ typedef struct spu_context { + /* 0: unchecked legacy region; otherwise SPU_OVERLAY_* state of a + * region registered with its code bytes (spu_overlay_residency.h). */ + int verify_state, source_index; ++ /* Nonzero for position-independent code lifted once at this canonical LS base ++ * (spu_overlay_register_region_reloc): its functions are registered at ++ * canon + offset, wherever the title placed this copy. 0 = ordinary placed lift. */ ++ uint32_t canon; + } resident_code[4]; ++ /* Placement minus canonical base of the relocatable code running now (spu_lifter.py ++ * --reloc): lifted relocatable code adds it to every address it derives from its own ++ * pc. Set by the dispatcher on entry into such code; only that code reads it. */ ++ int32_t reloc_delta; + + /* Dispatch cache (spu_lifted_lookup, spu_channels.c). dcache_id names this + * context's current lifetime: 0 after spu_context_init (or a zeroed +diff --git a/runtime/spu/spu_interp.c b/runtime/spu/spu_interp.c +index e9b8f613..1412607f 100644 +--- a/runtime/spu/spu_interp.c ++++ b/runtime/spu/spu_interp.c +@@ -454,12 +454,17 @@ uint32_t spu_interp_run_until(spu_context* ctx, uint32_t start_lsa, uint32_t sto + if (interp_stats_on()) { + /* Credit an entry inside a resident code region to the image that + * owns it, so the list names the lift that's missing the entry. */ +- uint32_t pc = start_lsa & 0x3FFFC; int owner = ctx->image_id; ++ uint32_t pc = start_lsa & 0x3FFFC, key = pc; int owner = ctx->image_id; + for (unsigned s = 0; s < 4; ++s) + if (ctx->resident_code[s].image_id && pc >= ctx->resident_code[s].lsa && +- pc - ctx->resident_code[s].lsa < ctx->resident_code[s].size) ++ pc - ctx->resident_code[s].lsa < ctx->resident_code[s].size) { + owner = ctx->resident_code[s].image_id; +- interp_stats_bump(s_ie_img, s_ie_pc, s_ie_cnt, owner, pc); ++ /* Relocatable code: the CANONICAL pc (placement-independent), which ++ * is the entry its --reloc lift needs. */ ++ key = ctx->resident_code[s].canon ++ ? pc - ctx->resident_code[s].lsa + ctx->resident_code[s].canon : pc; ++ } ++ interp_stats_bump(s_ie_img, s_ie_pc, s_ie_cnt, owner, key); + } + ctx->pc = start_lsa & 0x3FFFC; + ctx->status = SPU_STATUS_RUNNING; +diff --git a/runtime/spu/tests/test_spu_lifted_start.c b/runtime/spu/tests/test_spu_lifted_start.c +index ce11d991..e252a415 100644 +--- a/runtime/spu/tests/test_spu_lifted_start.c ++++ b/runtime/spu/tests/test_spu_lifted_start.c +@@ -105,6 +105,7 @@ int64_t lv2_spu_lock_line_classify(uint32_t a, uint64_t f) { (void)a; (void)f; r + #include "../spu_helpers.h" + void spu_wrch(spu_context*, uint32_t, u128); + void spu_overlay_register_region(uint32_t, uint32_t, int); ++void spu_overlay_register_region_reloc(uint32_t, uint32_t, uint32_t, int); + void spu_overlay_note_get(spu_context*, uint32_t, const uint8_t*, uint32_t); + void spu_overlay_register_source(uint32_t, int); + void spu_overlay_register_sig(const uint8_t sig[16], int); +@@ -386,6 +387,43 @@ static void test_smc_xori(void) + static void code_a(spu_context* ctx) { ctx->gpr[3]._u32[0] = 81; } + static void code_b(spu_context* ctx) { ctx->gpr[3]._u32[0] = 82; } + static void code_stale(spu_context* ctx) { ctx->gpr[3]._u32[0] = 83; } ++/* Relocatable resident code (spu_overlay_register_region_reloc): one canonical lift ++ * served wherever the title copies the code, with ctx->reloc_delta set. */ ++static void rl_fn0(spu_context* c) { c->gpr[9]._u32[0] = 0x40; } ++static void rl_fn1(spu_context* c) { c->gpr[9]._u32[0] = 0x41; } ++static void test_reloc_regions(void) ++{ ++ spu_context* c = calloc(1, sizeof *c); ++ if (!c) { check(0, "reloc: allocate"); return; } ++ spu_context_init(c, 0); c->image_id = 121; ++ spu_begin_image(140); spu_register_function(0x10000, rl_fn0); spu_register_function(0x10040, rl_fn1); ++ spu_begin_image(0); ++ spu_overlay_register_region_reloc(0x910000, 0x100, 0, 141); /* rejected: canon 0 */ ++ spu_overlay_register_region_reloc(0x920000, 0x100, 0x3FF80, 142); /* rejected: past LS */ ++ spu_overlay_note_get(c, 0x910000, c->ls + 0x5000, 16); ++ spu_overlay_note_get(c, 0x920000, c->ls + 0x6000, 16); ++ check(!c->resident_code[0].image_id, "reloc: invalid canon registrations are refused"); ++ spu_overlay_register_region_reloc(0x900000, 0x100, 0x10000, 140); ++ spu_overlay_note_get(c, 0x900000, c->ls + 0x23450, 16); ++ check(c->resident_code[0].image_id == 140 && c->resident_code[0].canon == 0x10000, "reloc: GET at any LSA makes the copy resident"); ++ c->reloc_delta = 0; ++ check(spu_lifted_lookup(c, 0x23450) == rl_fn0, "reloc: placed entry runs the canonical lift"); ++ check(c->reloc_delta == 0x13450, "reloc: lookup sets placement - canon"); ++ check(spu_lifted_lookup(c, 0x23490) == rl_fn1, "reloc: second function at canon + offset"); ++ c->reloc_delta = 0; ++ check(spu_lifted_lookup(c, 0x23450) == rl_fn0, "reloc: repeated lookup (cache hit)"); ++ check(c->reloc_delta == 0x13450, "reloc: a cache hit restores the delta"); ++ check(spu_lifted_lookup(c, 0x10000) == NULL, "reloc: the canonical address itself is not served"); ++ spu_overlay_note_get(c, 0x900000, c->ls + 0x30000, 16); ++ int n = 0; for (unsigned s = 0; s < 4; ++s) n += c->resident_code[s].image_id == 140; ++ check(n == 1, "reloc: a new placement takes over the image's slot"); ++ check(spu_lifted_lookup(c, 0x30040) == rl_fn1 && c->reloc_delta == 0x20000, "reloc: new placement, new delta"); ++ check(spu_lifted_lookup(c, 0x23450) == NULL, "reloc: the old placement is no longer resident"); ++ c->reloc_delta = 7; ++ check(spu_lifted_lookup(c, 0x30000) == rl_fn0 && c->reloc_delta == 0x20000, "reloc: delta after placement change"); ++ free(c); ++} ++ + static void test_resident_code_regions(void) + { + spu_context* ctx = (spu_context*)calloc(1, sizeof *ctx); +@@ -1058,6 +1096,7 @@ int main(void) + test_smc_branch_hints(); + test_smc_xori(); + test_resident_code_regions(); ++ test_reloc_regions(); + test_verified_resident_code_regions(); + test_registry_lookup_memo(); + test_resident_interpreter_rejoin(); +diff --git a/tools/spu_lifter.py b/tools/spu_lifter.py +index 35d8d428..4610a361 100644 +--- a/tools/spu_lifter.py ++++ b/tools/spu_lifter.py +@@ -520,6 +520,12 @@ class SPULifter: + f"underscore; using {prefix + chr(95)!r}"+chr(10)) + prefix += "_" + self.prefix = prefix ++ # --reloc: position-independent code a title copies to a different LS address ++ # at each load (GoW:A's BatchJobList job code). It is lifted once at a canonical ++ # base, and every local-store address the code materializes from its own pc ++ # (links, lqr/stqr, transfer and return pcs) adds ctx->reloc_delta, which the ++ # dispatcher sets to placement - canonical base on entry (spu_overlay_register_region_reloc). ++ self.reloc = False + # Addresses of `bi/biz/... $r0` that are COMPUTED TAIL JUMPS (r0 reloaded + # via lqa/lqr), not function returns -- see compute_bi_r0_jumps(). Empty + # set => every `bi $r0` is a return (the prior behaviour). +@@ -559,12 +565,12 @@ class SPULifter: + if insn.addr in merged_starts: + func.body_lines.append( + f" if (ctx->int_enable && (ctx->event_status & ctx->event_mask)) " +- f"{{ ctx->pc = 0x{insn.addr:X}; g_spu_trampoline_fn = " ++ f"{{ ctx->pc = {self._pc(insn.addr)}; g_spu_trampoline_fn = " + f"{self.prefix}spu_func_{insn.addr:08X}; return; }}") + c = self._translate(insn, func) + if c: + if self.trace: +- func.body_lines.append(f" spu_trace_pc(ctx, 0x{insn.addr:X});") ++ func.body_lines.append(f" spu_trace_pc(ctx, {self._pc(insn.addr)});") + func.body_lines.append(f" {c}") + if self.trace and insn.mnemonic not in _NO_RT_WRITE: + rt_idx = insn.raw & 0x7F +@@ -583,7 +589,7 @@ class SPULifter: + and (last_insn.raw & 0x3FFF) in LV2_RESUMING_STOPS)) + and end in getattr(self, "func_starts", set())): + func.body_lines.append( +- f" {{ SPU_DIRECT(ctx, 0x{end:X}, {self.prefix}spu_func_{end:08X}); }}") ++ f" {{ SPU_DIRECT(ctx, {self._pc(end)}, {self.prefix}spu_func_{end:08X}); }}") + + # Infinite no-op self-loop (the SPU `br .` halt idiom): a function whose + # whole body is nops + an unconditional branch back into itself does +@@ -606,6 +612,13 @@ class SPULifter: + self.functions.append(func) + return func + ++ def _pc(self, a: int) -> str: ++ """A local-store address derived from the code's own placement: a constant, or ++ under --reloc the canonical address plus ctx->reloc_delta (wrapped to LS).""" ++ if self.reloc: ++ return f"((0x{a:X}u + (uint32_t)ctx->reloc_delta) & 0x3FFFFu)" ++ return f"0x{a:X}" ++ + @staticmethod + def _branch_target(insn: SPUInstruction): + """The literal target of a direct branch, or None if it has none. +@@ -866,9 +879,12 @@ class SPULifter: + if disp is not None: + return f"spu_ls_write128(ctx, {g(base)}._u32[0] + {disp}, {g(rt())});" + if mn in ("lqa", "lqr"): +- return f"{g(rt())} = spu_ls_read128(ctx, {_imm(ops[1])});" ++ # lqr's address is pc-relative (the disassembler gives it absolute): under --reloc it moves with the code ++ a = self._pc(int(_imm(ops[1]), 0)) if mn == "lqr" and self.reloc else _imm(ops[1]) ++ return f"{g(rt())} = spu_ls_read128(ctx, {a});" + if mn in ("stqa", "stqr"): +- return f"spu_ls_write128(ctx, {_imm(ops[1])}, {g(rt())});" ++ a = self._pc(int(_imm(ops[1]), 0)) if mn == "stqr" and self.reloc else _imm(ops[1]) ++ return f"spu_ls_write128(ctx, {a}, {g(rt())});" + if mn == "lqx": + return f"{g(rt())} = spu_ls_read128(ctx, {g(ra())}._u32[0] + {g(rb())}._u32[0]);" + if mn == "stqx": +@@ -902,7 +918,7 @@ class SPULifter: + tgt = self._branch_target(insn) + # Link register: preferred word only, other slots ZERO (real HW / + # RPCS3 v128::from32r) -- splatting corrupts full-quadword link use. +- link = f"{g(link_rt)} = spu_link(0x{(addr + 4) & 0x3FFFC:X});" # wraps at the end of LS ++ link = f"{g(link_rt)} = spu_link({self._pc((addr + 4) & 0x3FFFC)});" # wraps at the end of LS + # SELF-LOOP TRAP: `brsl rX, .` (target == this instruction) is an + # infinite loop on real SPU (re-sets the link each pass, never + # advances) -- a trap, NOT a call. Emitting a host call recurses +@@ -927,9 +943,12 @@ class SPULifter: + # `bi $r0` returns via host return) + SPU_DRAIN (drains the + # callee's own tail-chains so they don't grow the caller frame) + # + image save/restore (adopt-on-serve cannot leak upward). +- return (f"{link} {{ int32_t _si = (int32_t)ctx->image_id; " ++ # --reloc: the callee's drain may dispatch into other placed code, which sets ++ # ctx->reloc_delta for itself; put this placement's back on return. ++ rs, rr = ("const int32_t _rd = ctx->reloc_delta; ", " ctx->reloc_delta = _rd;") if self.reloc else ("", "") ++ return (f"{link} {{ int32_t _si = (int32_t)ctx->image_id; {rs}" + f"ctx->host_depth++; {self.prefix}spu_func_{tgt:08X}(ctx); " +- f"spu_drain_call(ctx, 0x{addr + 4:X}); ctx->host_depth--; spu_img_restore(ctx, _si); }}") ++ f"spu_drain_call(ctx, {self._pc(addr + 4)}); ctx->host_depth--; spu_img_restore(ctx, _si);{rr} }}") + return f"{link} /* TODO spu: brsl unresolved target */;" + if mn in _COND_BR: + tgt = self._branch_target(insn) +@@ -943,7 +962,7 @@ class SPULifter: + # Cross-function conditional branch = conditional tail: a direct + # tail call when the drain has nothing to do on this step, else + # the trampoline and unwind (SPU_DIRECT, spu_context.h). +- return (f"if ({cond}) {{ SPU_DIRECT(ctx, 0x{tgt:X}, " ++ return (f"if ({cond}) {{ SPU_DIRECT(ctx, {self._pc(tgt)}, " + f"{self.prefix}spu_func_{tgt:08X}); }}") + # Interrupt enable/disable bits on the bi family (bie/bid, irete/iretd, + # bisle(d)...): bit 0x40000 = E (enable), 0x80000 = D (disable), taking +@@ -991,17 +1010,18 @@ class SPULifter: + # SPU_DRAIN + image save/restore) so the callee's tail-chains drain + # here and its `bi $r0` returns via host return. + # read the target BEFORE writing the link: rt may be the same register as ra +- return (f"{{ uint32_t _tg = {g(tgt_reg)}._u32[0]; {g(link_rt)} = spu_link(0x{(addr + 4) & 0x3FFFC:X}); " +- f"int32_t _si = (int32_t)ctx->image_id; " ++ rs, rr = ("const int32_t _rd = ctx->reloc_delta; ", " ctx->reloc_delta = _rd;") if self.reloc else ("", "") ++ return (f"{{ uint32_t _tg = {g(tgt_reg)}._u32[0]; {g(link_rt)} = spu_link({self._pc((addr + 4) & 0x3FFFC)}); " ++ f"int32_t _si = (int32_t)ctx->image_id; {rs}" + f"{_ied}ctx->pc = _tg; ctx->host_depth++; " +- f"spu_indirect_branch(ctx); spu_drain_call(ctx, 0x{addr + 4:X}); " +- f"ctx->host_depth--; spu_img_restore(ctx, _si); }}") ++ f"spu_indirect_branch(ctx); spu_drain_call(ctx, {self._pc(addr + 4)}); " ++ f"ctx->host_depth--; spu_img_restore(ctx, _si);{rr} }}") + # bisled: set link, branch to RA only if an external event is pending. + if mn in ("bisled",): + link_rt = insn.raw & 0x7F # rt = link + tgt_reg = (insn.raw >> 7) & 0x7F # ra = target (the disassembler's last operand is rb, not the target) + # read the target before writing the link: rt may alias ra +- return (f"{{ uint32_t _tg = {g(tgt_reg)}._u32[0]; {g(link_rt)} = spu_link(0x{(addr + 4) & 0x3FFFC:X}); " ++ return (f"{{ uint32_t _tg = {g(tgt_reg)}._u32[0]; {g(link_rt)} = spu_link({self._pc((addr + 4) & 0x3FFFC)}); " + f"if ((ctx->event_status & ctx->event_mask) != 0) {{ " + f"{_ied}ctx->pc = _tg; " + f"g_spu_trampoline_fn = spu_indirect_branch; return; }} }}") +@@ -1057,7 +1077,7 @@ class SPULifter: + # drain has nothing to do on this step, else hand the target to the + # trampoline and unwind so the enclosing SPU_DRAIN re-enters (no + # host-stack growth either way; SPU_DIRECT, spu_context.h). +- return (f"{{ SPU_DIRECT(ctx, 0x{tgt:X}, {self.prefix}spu_func_{tgt:08X}); }}") ++ return (f"{{ SPU_DIRECT(ctx, {self._pc(tgt)}, {self.prefix}spu_func_{tgt:08X}); }}") + + # ------------------------------------------------------------------ # + def emit_header(self) -> str: +@@ -1101,7 +1121,8 @@ class SPULifter: + lines.append(" * branches that escape a function's range). */") + for t in externs: + lines.append(f"void {self.prefix}spu_func_{t:08X}(spu_context* ctx) {{") +- lines.append(f" ctx->pc = 0x{t:X}u; " ++ pc = self._pc(t) if self.reloc else f"0x{t:X}u" ++ lines.append(f" ctx->pc = {pc}; " + f"g_spu_trampoline_fn = spu_indirect_branch; return;") + lines.append("}") + lines.append("") +@@ -1186,6 +1207,11 @@ def main() -> None: + "by trampolines. Every chunk is still emitted and " + "registered on its own for indirect entry, so this only " + "changes speed, not which code can be reached.") ++ p.add_argument("--reloc", action="store_true", ++ help="Position-independent code the title places at a different LS " ++ "address per load: lift once at --base, and offset every " ++ "pc-derived address by ctx->reloc_delta at run time (register " ++ "with spu_overlay_register_region_reloc).") + p.add_argument("--max-group-insns", type=int, default=4000, + help="Cap on instructions per merged group (keeps clang fast).") + p.add_argument("--force-indirect", default="", +@@ -1311,6 +1337,7 @@ def main() -> None: + insns = disassemble_spu(data, base) + + lifter = SPULifter(trace=args.trace, prefix=args.symbol_prefix) ++ lifter.reloc = args.reloc + lifter.bi_r0_jump = compute_bi_r0_jumps(insns, bounds) + if lifter.bi_r0_jump: + print(f" {len(lifter.bi_r0_jump)} `bi $r0` computed-jump site(s) " diff --git a/tasks/sp00nznet__ps3recomp-636/solution/solve.sh b/tasks/sp00nznet__ps3recomp-636/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-636/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-636/task.toml b/tasks/sp00nznet__ps3recomp-636/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d4f1fdaab51d86a1bddf898db077c3776db837bf --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-636/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-636" +description = "spu: relocatable lifts for position-independent code placed anywhere in LS" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/636" +source_access = "auto" +built_at = "2026-11-16T16:09:59.662211+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e3a5cfdf6f19ec398b6fd3bc5aae51ededb74675b23e84d969902fcef7f08633" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:43Z" +diff_format = "unified" +context_files = [ + "runtime/spu/spu_channels.c", + "runtime/spu/spu_context.h", + "runtime/spu/spu_interp.c", + "runtime/spu/tests/test_spu_lifted_start.c", + "tools/spu_lifter.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 171 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.139022+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-636/tests/capture.py b/tasks/sp00nznet__ps3recomp-636/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-636/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-636/tests/instruction.md b/tasks/sp00nznet__ps3recomp-636/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1b858a592ae56670bb952e59ef3812c5a4a64ee --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-636/tests/instruction.md @@ -0,0 +1,62 @@ +# Issue + +**Title:** spu: relocatable lifts for position-independent code placed anywhere in LS + +## Description + +## What + +Lift position-independent SPU code **once** and run it wherever a title copies it in local store. + +Some titles stage job code in LS at an address that changes from load to load. God of War: Ascension's `BatchJobList` jobs copy four EBOOT code blobs to a new 16-byte-aligned address every time: one capture saw 299 loads at 299 different addresses. A lift per placement (`spu_overlay_register_region_at`) cannot cover that. The code itself is position-independent: a `brsl $rX, .+4` pc-getter plus offsets, with no absolute branches and no `lqa`/`stqa` into itself. + +- **`tools/spu_lifter.py --reloc`**: + - Lifts at a canonical `--base` as usual. + - Every address the code derives from its own pc adds `ctx->reloc_delta`: link values of `brsl`/`bisl`/`bisled`, `lqr`/`stqr` addresses, `SPU_DIRECT` transfer pcs, `spu_drain_call` return pcs, and the indirect-dispatch stubs. + - All of these go through one helper (`SPULifter._pc`), so the generated code is unchanged without `--reloc`. + - Around nested `brsl`/`bisl` calls the generated code saves and restores `reloc_delta`, as it already does for the image id. +- **`spu_overlay_register_region_reloc(ea, span, canon, image_id)`**: + - A GET of that content at **any** LS address makes the copy resident. A relocatable image reuses its previous placement's resident slot. + - `spu_lifted_lookup` (which `spu_indirect_branch` resolves through) looks the function up at `canon + (pc - placement)` and sets `ctx->reloc_delta = placement - canon` before running it. + - The dispatch-cache entry stores the delta too, so a cache hit restores it. The entry is already dropped when a slot's placement changes. +- **`spu_context`**: `resident_code[].canon` (0 = an ordinary placed lift) and `int32_t reloc_delta`. +- **`SPU_INTERP_STATS`**: interpreter entries inside resident relocatable code are counted at the **canonical** pc, so they can be passed back as `--extra-funcs`. +- **Test**: `test_reloc_regions` in `runtime/spu/tests/test_spu_lifted_start.c`. It covers refused registrations, a GET at any address making the copy resident, lookup at canon + offset setting the delta, a cache hit restoring it, and a new placement taking over the slot while the old one stops being served. +- **`SPU_RELOC_OFF=1`**: skips the registration and leaves that code interpreted, for A/B tests. + +Nothing changes for a title that does not call `spu_overlay_register_region_reloc`. + +## Evidence (God of War: Ascension, Windows, Vulkan backend) + +Measured in our port on our v0.17-based fork, whose diagnostics (`SPU_INTERP_MISS`, `SPURS_PM_PROF`, `PS3_FTRACE`) are not part of this PR. + +Interpreter time, `SPU_INTERP_MISS=1`, same scene. These are real log lines from the two runs. + +``` +before: [interp-miss] 13590.8 ms interpreted in 20 s, top targets: +after: [interp-miss] 4536.1 ms interpreted in 20 s, top targets: +``` + +`SPURS_PM_PROF` for the workload: `w7=77%/23390i87%` before, `w7=29%/21063i64%` after. That is busy 77% → 29%, and the interpreted share 87% → 64%. The rest comes from code outside the four blobs. + +The main thread's wait on that workload, per 60 s, from a `PS3_FTRACE` timeline of one build with and without the lifts: + +``` +SPU_RELOC_OFF=1: site 00464F84: 9.55 s waited in 60 s (787 spans) +SPU_RELOC_OFF=0: site 00464F84: 4.00 s waited in 60 s (691 spans) +``` + +No hang, and clean frame dumps in every run. + +The frame rate is **neutral on this title**: the frame then waits on another workload. So the port ships with `SPU_RELOC_OFF=1` for now. The value of this PR is coverage of the code itself. + +**Not yet verified:** +- other titles; +- the Linux build; +- code that materializes its own address through `ila`/`il` constants, which `--reloc` does not rewrite. The code here never does that. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-636/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-636/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..56232dcbe99ec1186fa5412c6c6e629dd5dd6258 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-636/tests/oracle.patch @@ -0,0 +1,418 @@ +diff --git a/runtime/spu/spu_channels.c b/runtime/spu/spu_channels.c +index 5fc50208..2b32d1b0 100644 +--- a/runtime/spu/spu_channels.c ++++ b/runtime/spu/spu_channels.c +@@ -1715,7 +1715,7 @@ int spu_have_function(uint32_t addr) + * through would execute stale code registered under another image. Task and + * unbounded overlay misses retain their existing primary-image fallback. */ + static int spu_overlay_resident_verified(spu_context* ctx, unsigned slot); +-static spu_lifted_fn spu_lifted_lookup_full(const spu_context* ctx, uint32_t lsa) ++static spu_lifted_fn spu_lifted_lookup_full(const spu_context* ctx, uint32_t lsa, int* reloc) + { + /* Every probe below goes through #436's per-thread memo rather than + * spu_lookup() directly: the resolver makes up to three of them per +@@ -1730,7 +1730,18 @@ static spu_lifted_fn spu_lifted_lookup_full(const spu_context* ctx, uint32_t lsa + * unverified: other images' functions there would be stale. */ + if (ctx->resident_code[slot].verify_state && + !spu_overlay_resident_verified((spu_context*)ctx, slot)) return NULL; +- return (spu_lifted_fn)spu_lookup_memoized(lsa, ctx->resident_code[slot].image_id); ++ const uint32_t canon = ctx->resident_code[slot].canon; ++ if (!canon) ++ return (spu_lifted_fn)spu_lookup_memoized(lsa, ctx->resident_code[slot].image_id); ++ /* Relocatable code (spu_overlay_register_region_reloc): its lift sits at ++ * canon + offset. The caller runs the function next, so set its delta now. */ ++ spu_fn f = spu_lookup_memoized(lsa - ctx->resident_code[slot].lsa + canon, ++ ctx->resident_code[slot].image_id); ++ if (f) { ++ ((spu_context*)ctx)->reloc_delta = (int32_t)(ctx->resident_code[slot].lsa - canon); ++ if (reloc) *reloc = 1; ++ } ++ return (spu_lifted_fn)f; + } + spu_fn fn = NULL; + if (ctx->resident_task) fn = spu_lookup_memoized(lsa, ctx->resident_task); +@@ -1762,6 +1773,10 @@ typedef struct { + spu_lifted_fn fn; + uint32_t id, lsa, rgen, residency; + int image, ovl, task; ++ /* A relocatable resolution also sets ctx->reloc_delta, which a hit must ++ * repeat: residency fixes the placement, so the delta is part of the answer. */ ++ int reloc; ++ int32_t reloc_delta; + } spu_dcache_ent; + #define SPU_DCACHE_ENTRIES 512u + static SPU_TLS spu_dcache_ent t_dcache[SPU_DCACHE_ENTRIES]; +@@ -1792,7 +1807,7 @@ static void spu_dcache_shadow_stats(void) + spu_lifted_fn spu_lifted_lookup(const spu_context* ctx, uint32_t lsa) + { + const int mode = spu_dcache_mode(); +- if (!mode || !ctx) return spu_lifted_lookup_full(ctx, lsa); ++ if (!mode || !ctx) return spu_lifted_lookup_full(ctx, lsa, NULL); + spu_context* c = (spu_context*)ctx; + uint32_t id = c->dcache_id; + if (!id) { +@@ -1806,9 +1821,10 @@ spu_lifted_fn spu_lifted_lookup(const spu_context* ctx, uint32_t lsa) + if (e->fn && e->id == id && e->lsa == lsa && e->rgen == rgen && + e->residency == c->dcache_residency && e->image == c->image_id && + e->ovl == c->resident_ovl && e->task == c->resident_task) { ++ if (e->reloc) c->reloc_delta = e->reloc_delta; + if (mode == 2) { + __atomic_fetch_add(&s_dcache_hits, 1, __ATOMIC_RELAXED); +- const spu_lifted_fn full = spu_lifted_lookup_full(ctx, lsa); ++ const spu_lifted_fn full = spu_lifted_lookup_full(ctx, lsa, NULL); + if (full != e->fn) { + if (__atomic_fetch_add(&s_dcache_shadow_bad, 1, __ATOMIC_RELAXED) < 16) + fprintf(stderr, "[spu-dcache] shadow mismatch img=%d ovl=%d task=%d lsa=0x%05X " +@@ -1825,13 +1841,15 @@ spu_lifted_fn spu_lifted_lookup(const spu_context* ctx, uint32_t lsa) + __atomic_fetch_add(&s_dcache_misses, 1, __ATOMIC_RELAXED); + spu_dcache_shadow_stats(); + } +- const spu_lifted_fn fn = spu_lifted_lookup_full(ctx, lsa); ++ int reloc = 0; ++ const spu_lifted_fn fn = spu_lifted_lookup_full(ctx, lsa, &reloc); + if (fn) { + /* The resolver may have verified a pending slot; the entry records the + * residency it resolved against, read after it. */ + e->fn = fn; e->id = id; e->lsa = lsa; e->rgen = rgen; + e->residency = c->dcache_residency; e->image = c->image_id; + e->ovl = c->resident_ovl; e->task = c->resident_task; ++ e->reloc = reloc; e->reloc_delta = c->reloc_delta; + } + return fn; + } +@@ -1842,7 +1860,8 @@ spu_lifted_fn spu_lifted_lookup(const spu_context* ctx, uint32_t lsa) + * marks that overlay resident in the streaming context; dispatch retries a + * primary-image miss against the resident overlay's registry. */ + typedef struct { uint32_t src_ea; int image_id; uint8_t sig[16]; int has_sig; uint32_t span; +- uint32_t load_lsa; unsigned code_count; spu_overlay_code_segment* code; } spu_ovl_src; ++ uint32_t load_lsa; unsigned code_count; spu_overlay_code_segment* code; ++ uint32_t canon; } spu_ovl_src; + /* 6 FMOD codec/DSP overlays + up to 89 WWS job-code modules (all stream into + * the same job code buffer at LS 0x4000, dispatched by content signature). */ + #define SPU_OVL_SRC_MAX 128 +@@ -1894,6 +1913,7 @@ void spu_overlay_register_source(uint32_t content_ea, int image_id) + s_ovl_src[s_ovl_src_count].src_ea = content_ea; + s_ovl_src[s_ovl_src_count].image_id = image_id; + s_ovl_src[s_ovl_src_count].has_sig = 0; ++ s_ovl_src[s_ovl_src_count].canon = 0; + __atomic_store_n(&s_ovl_src_count, s_ovl_src_count + 1, __ATOMIC_RELEASE); + } + } +@@ -1907,6 +1927,22 @@ void spu_overlay_register_region(uint32_t content_ea, uint32_t span, int image_i + s_ovl_src[s_ovl_src_count - 1].span = span; + } + ++/* And for position-independent code the title copies to a different LS address at each ++ * load (GoW:A's BatchJobList jobs place four EBOOT blobs at a new 16-byte-aligned address ++ * every time): lifted ONCE at a canonical base with spu_lifter.py --reloc. A GET of the ++ * content at any address makes that copy resident; dispatch then looks the function up at ++ * canon + offset and sets ctx->reloc_delta, which the lifted code adds to every address ++ * it derives from its own pc. */ ++void spu_overlay_register_region_reloc(uint32_t content_ea, uint32_t span, uint32_t canon, int image_id) ++{ ++ if (!canon || canon >= SPU_LS_SIZE || span > SPU_LS_SIZE - canon) return; ++ { static int s_off = -1; if (s_off < 0) { const char* e = getenv("SPU_RELOC_OFF"); s_off = e && e[0] == '1'; } ++ if (s_off) return; } /* SPU_RELOC_OFF=1: leave that code to the interpreter (A/B) */ ++ const int n = s_ovl_src_count; ++ spu_overlay_register_region(content_ea, span, image_id); ++ if (s_ovl_src_count == n + 1) s_ovl_src[n].canon = canon; ++} ++ + /* Residency proves which load happened, not what the bytes are: the source EA + * could hold different content than was lifted. Compare the lifted segments + * once per load, at the first dispatch into the span, instead of at every +@@ -2159,7 +2195,10 @@ void spu_overlay_note_get(spu_context* ctx, uint32_t ea, const uint8_t* ls, uint + /* Verified code was lifted for one load address. */ + if (o->code && lsa != o->load_lsa) continue; + for (unsigned slot = 0; slot < 4; ++slot) { +- if (ctx->resident_code[slot].image_id && ctx->resident_code[slot].lsa != lsa) ++ /* A relocatable image takes over its own previous placement's slot: each load ++ * lands somewhere new, and stale copies would fill the slots. */ ++ if (ctx->resident_code[slot].image_id && ctx->resident_code[slot].lsa != lsa && ++ !(o->canon && ctx->resident_code[slot].image_id == o->image_id)) + continue; + ctx->resident_code[slot].lsa = lsa; + ctx->resident_code[slot].size = o->span; +@@ -2167,6 +2206,7 @@ void spu_overlay_note_get(spu_context* ctx, uint32_t ea, const uint8_t* ls, uint + ctx->resident_code[slot].image_id = o->image_id; + ctx->resident_code[slot].verify_state = o->code ? SPU_OVERLAY_PENDING : 0; + ctx->resident_code[slot].source_index = i; ++ ctx->resident_code[slot].canon = o->canon; + spu_dcache_residency_changed(ctx); + return; + } +diff --git a/runtime/spu/spu_context.h b/runtime/spu/spu_context.h +index c5ccbec7..84c0120a 100644 +--- a/runtime/spu/spu_context.h ++++ b/runtime/spu/spu_context.h +@@ -302,7 +302,15 @@ typedef struct spu_context { + /* 0: unchecked legacy region; otherwise SPU_OVERLAY_* state of a + * region registered with its code bytes (spu_overlay_residency.h). */ + int verify_state, source_index; ++ /* Nonzero for position-independent code lifted once at this canonical LS base ++ * (spu_overlay_register_region_reloc): its functions are registered at ++ * canon + offset, wherever the title placed this copy. 0 = ordinary placed lift. */ ++ uint32_t canon; + } resident_code[4]; ++ /* Placement minus canonical base of the relocatable code running now (spu_lifter.py ++ * --reloc): lifted relocatable code adds it to every address it derives from its own ++ * pc. Set by the dispatcher on entry into such code; only that code reads it. */ ++ int32_t reloc_delta; + + /* Dispatch cache (spu_lifted_lookup, spu_channels.c). dcache_id names this + * context's current lifetime: 0 after spu_context_init (or a zeroed +diff --git a/runtime/spu/spu_interp.c b/runtime/spu/spu_interp.c +index e9b8f613..1412607f 100644 +--- a/runtime/spu/spu_interp.c ++++ b/runtime/spu/spu_interp.c +@@ -454,12 +454,17 @@ uint32_t spu_interp_run_until(spu_context* ctx, uint32_t start_lsa, uint32_t sto + if (interp_stats_on()) { + /* Credit an entry inside a resident code region to the image that + * owns it, so the list names the lift that's missing the entry. */ +- uint32_t pc = start_lsa & 0x3FFFC; int owner = ctx->image_id; ++ uint32_t pc = start_lsa & 0x3FFFC, key = pc; int owner = ctx->image_id; + for (unsigned s = 0; s < 4; ++s) + if (ctx->resident_code[s].image_id && pc >= ctx->resident_code[s].lsa && +- pc - ctx->resident_code[s].lsa < ctx->resident_code[s].size) ++ pc - ctx->resident_code[s].lsa < ctx->resident_code[s].size) { + owner = ctx->resident_code[s].image_id; +- interp_stats_bump(s_ie_img, s_ie_pc, s_ie_cnt, owner, pc); ++ /* Relocatable code: the CANONICAL pc (placement-independent), which ++ * is the entry its --reloc lift needs. */ ++ key = ctx->resident_code[s].canon ++ ? pc - ctx->resident_code[s].lsa + ctx->resident_code[s].canon : pc; ++ } ++ interp_stats_bump(s_ie_img, s_ie_pc, s_ie_cnt, owner, key); + } + ctx->pc = start_lsa & 0x3FFFC; + ctx->status = SPU_STATUS_RUNNING; +diff --git a/runtime/spu/tests/test_spu_lifted_start.c b/runtime/spu/tests/test_spu_lifted_start.c +index ce11d991..e252a415 100644 +--- a/runtime/spu/tests/test_spu_lifted_start.c ++++ b/runtime/spu/tests/test_spu_lifted_start.c +@@ -105,6 +105,7 @@ int64_t lv2_spu_lock_line_classify(uint32_t a, uint64_t f) { (void)a; (void)f; r + #include "../spu_helpers.h" + void spu_wrch(spu_context*, uint32_t, u128); + void spu_overlay_register_region(uint32_t, uint32_t, int); ++void spu_overlay_register_region_reloc(uint32_t, uint32_t, uint32_t, int); + void spu_overlay_note_get(spu_context*, uint32_t, const uint8_t*, uint32_t); + void spu_overlay_register_source(uint32_t, int); + void spu_overlay_register_sig(const uint8_t sig[16], int); +@@ -386,6 +387,43 @@ static void test_smc_xori(void) + static void code_a(spu_context* ctx) { ctx->gpr[3]._u32[0] = 81; } + static void code_b(spu_context* ctx) { ctx->gpr[3]._u32[0] = 82; } + static void code_stale(spu_context* ctx) { ctx->gpr[3]._u32[0] = 83; } ++/* Relocatable resident code (spu_overlay_register_region_reloc): one canonical lift ++ * served wherever the title copies the code, with ctx->reloc_delta set. */ ++static void rl_fn0(spu_context* c) { c->gpr[9]._u32[0] = 0x40; } ++static void rl_fn1(spu_context* c) { c->gpr[9]._u32[0] = 0x41; } ++static void test_reloc_regions(void) ++{ ++ spu_context* c = calloc(1, sizeof *c); ++ if (!c) { check(0, "reloc: allocate"); return; } ++ spu_context_init(c, 0); c->image_id = 121; ++ spu_begin_image(140); spu_register_function(0x10000, rl_fn0); spu_register_function(0x10040, rl_fn1); ++ spu_begin_image(0); ++ spu_overlay_register_region_reloc(0x910000, 0x100, 0, 141); /* rejected: canon 0 */ ++ spu_overlay_register_region_reloc(0x920000, 0x100, 0x3FF80, 142); /* rejected: past LS */ ++ spu_overlay_note_get(c, 0x910000, c->ls + 0x5000, 16); ++ spu_overlay_note_get(c, 0x920000, c->ls + 0x6000, 16); ++ check(!c->resident_code[0].image_id, "reloc: invalid canon registrations are refused"); ++ spu_overlay_register_region_reloc(0x900000, 0x100, 0x10000, 140); ++ spu_overlay_note_get(c, 0x900000, c->ls + 0x23450, 16); ++ check(c->resident_code[0].image_id == 140 && c->resident_code[0].canon == 0x10000, "reloc: GET at any LSA makes the copy resident"); ++ c->reloc_delta = 0; ++ check(spu_lifted_lookup(c, 0x23450) == rl_fn0, "reloc: placed entry runs the canonical lift"); ++ check(c->reloc_delta == 0x13450, "reloc: lookup sets placement - canon"); ++ check(spu_lifted_lookup(c, 0x23490) == rl_fn1, "reloc: second function at canon + offset"); ++ c->reloc_delta = 0; ++ check(spu_lifted_lookup(c, 0x23450) == rl_fn0, "reloc: repeated lookup (cache hit)"); ++ check(c->reloc_delta == 0x13450, "reloc: a cache hit restores the delta"); ++ check(spu_lifted_lookup(c, 0x10000) == NULL, "reloc: the canonical address itself is not served"); ++ spu_overlay_note_get(c, 0x900000, c->ls + 0x30000, 16); ++ int n = 0; for (unsigned s = 0; s < 4; ++s) n += c->resident_code[s].image_id == 140; ++ check(n == 1, "reloc: a new placement takes over the image's slot"); ++ check(spu_lifted_lookup(c, 0x30040) == rl_fn1 && c->reloc_delta == 0x20000, "reloc: new placement, new delta"); ++ check(spu_lifted_lookup(c, 0x23450) == NULL, "reloc: the old placement is no longer resident"); ++ c->reloc_delta = 7; ++ check(spu_lifted_lookup(c, 0x30000) == rl_fn0 && c->reloc_delta == 0x20000, "reloc: delta after placement change"); ++ free(c); ++} ++ + static void test_resident_code_regions(void) + { + spu_context* ctx = (spu_context*)calloc(1, sizeof *ctx); +@@ -1058,6 +1096,7 @@ int main(void) + test_smc_branch_hints(); + test_smc_xori(); + test_resident_code_regions(); ++ test_reloc_regions(); + test_verified_resident_code_regions(); + test_registry_lookup_memo(); + test_resident_interpreter_rejoin(); +diff --git a/tools/spu_lifter.py b/tools/spu_lifter.py +index 35d8d428..4610a361 100644 +--- a/tools/spu_lifter.py ++++ b/tools/spu_lifter.py +@@ -520,6 +520,12 @@ class SPULifter: + f"underscore; using {prefix + chr(95)!r}"+chr(10)) + prefix += "_" + self.prefix = prefix ++ # --reloc: position-independent code a title copies to a different LS address ++ # at each load (GoW:A's BatchJobList job code). It is lifted once at a canonical ++ # base, and every local-store address the code materializes from its own pc ++ # (links, lqr/stqr, transfer and return pcs) adds ctx->reloc_delta, which the ++ # dispatcher sets to placement - canonical base on entry (spu_overlay_register_region_reloc). ++ self.reloc = False + # Addresses of `bi/biz/... $r0` that are COMPUTED TAIL JUMPS (r0 reloaded + # via lqa/lqr), not function returns -- see compute_bi_r0_jumps(). Empty + # set => every `bi $r0` is a return (the prior behaviour). +@@ -559,12 +565,12 @@ class SPULifter: + if insn.addr in merged_starts: + func.body_lines.append( + f" if (ctx->int_enable && (ctx->event_status & ctx->event_mask)) " +- f"{{ ctx->pc = 0x{insn.addr:X}; g_spu_trampoline_fn = " ++ f"{{ ctx->pc = {self._pc(insn.addr)}; g_spu_trampoline_fn = " + f"{self.prefix}spu_func_{insn.addr:08X}; return; }}") + c = self._translate(insn, func) + if c: + if self.trace: +- func.body_lines.append(f" spu_trace_pc(ctx, 0x{insn.addr:X});") ++ func.body_lines.append(f" spu_trace_pc(ctx, {self._pc(insn.addr)});") + func.body_lines.append(f" {c}") + if self.trace and insn.mnemonic not in _NO_RT_WRITE: + rt_idx = insn.raw & 0x7F +@@ -583,7 +589,7 @@ class SPULifter: + and (last_insn.raw & 0x3FFF) in LV2_RESUMING_STOPS)) + and end in getattr(self, "func_starts", set())): + func.body_lines.append( +- f" {{ SPU_DIRECT(ctx, 0x{end:X}, {self.prefix}spu_func_{end:08X}); }}") ++ f" {{ SPU_DIRECT(ctx, {self._pc(end)}, {self.prefix}spu_func_{end:08X}); }}") + + # Infinite no-op self-loop (the SPU `br .` halt idiom): a function whose + # whole body is nops + an unconditional branch back into itself does +@@ -606,6 +612,13 @@ class SPULifter: + self.functions.append(func) + return func + ++ def _pc(self, a: int) -> str: ++ """A local-store address derived from the code's own placement: a constant, or ++ under --reloc the canonical address plus ctx->reloc_delta (wrapped to LS).""" ++ if self.reloc: ++ return f"((0x{a:X}u + (uint32_t)ctx->reloc_delta) & 0x3FFFFu)" ++ return f"0x{a:X}" ++ + @staticmethod + def _branch_target(insn: SPUInstruction): + """The literal target of a direct branch, or None if it has none. +@@ -866,9 +879,12 @@ class SPULifter: + if disp is not None: + return f"spu_ls_write128(ctx, {g(base)}._u32[0] + {disp}, {g(rt())});" + if mn in ("lqa", "lqr"): +- return f"{g(rt())} = spu_ls_read128(ctx, {_imm(ops[1])});" ++ # lqr's address is pc-relative (the disassembler gives it absolute): under --reloc it moves with the code ++ a = self._pc(int(_imm(ops[1]), 0)) if mn == "lqr" and self.reloc else _imm(ops[1]) ++ return f"{g(rt())} = spu_ls_read128(ctx, {a});" + if mn in ("stqa", "stqr"): +- return f"spu_ls_write128(ctx, {_imm(ops[1])}, {g(rt())});" ++ a = self._pc(int(_imm(ops[1]), 0)) if mn == "stqr" and self.reloc else _imm(ops[1]) ++ return f"spu_ls_write128(ctx, {a}, {g(rt())});" + if mn == "lqx": + return f"{g(rt())} = spu_ls_read128(ctx, {g(ra())}._u32[0] + {g(rb())}._u32[0]);" + if mn == "stqx": +@@ -902,7 +918,7 @@ class SPULifter: + tgt = self._branch_target(insn) + # Link register: preferred word only, other slots ZERO (real HW / + # RPCS3 v128::from32r) -- splatting corrupts full-quadword link use. +- link = f"{g(link_rt)} = spu_link(0x{(addr + 4) & 0x3FFFC:X});" # wraps at the end of LS ++ link = f"{g(link_rt)} = spu_link({self._pc((addr + 4) & 0x3FFFC)});" # wraps at the end of LS + # SELF-LOOP TRAP: `brsl rX, .` (target == this instruction) is an + # infinite loop on real SPU (re-sets the link each pass, never + # advances) -- a trap, NOT a call. Emitting a host call recurses +@@ -927,9 +943,12 @@ class SPULifter: + # `bi $r0` returns via host return) + SPU_DRAIN (drains the + # callee's own tail-chains so they don't grow the caller frame) + # + image save/restore (adopt-on-serve cannot leak upward). +- return (f"{link} {{ int32_t _si = (int32_t)ctx->image_id; " ++ # --reloc: the callee's drain may dispatch into other placed code, which sets ++ # ctx->reloc_delta for itself; put this placement's back on return. ++ rs, rr = ("const int32_t _rd = ctx->reloc_delta; ", " ctx->reloc_delta = _rd;") if self.reloc else ("", "") ++ return (f"{link} {{ int32_t _si = (int32_t)ctx->image_id; {rs}" + f"ctx->host_depth++; {self.prefix}spu_func_{tgt:08X}(ctx); " +- f"spu_drain_call(ctx, 0x{addr + 4:X}); ctx->host_depth--; spu_img_restore(ctx, _si); }}") ++ f"spu_drain_call(ctx, {self._pc(addr + 4)}); ctx->host_depth--; spu_img_restore(ctx, _si);{rr} }}") + return f"{link} /* TODO spu: brsl unresolved target */;" + if mn in _COND_BR: + tgt = self._branch_target(insn) +@@ -943,7 +962,7 @@ class SPULifter: + # Cross-function conditional branch = conditional tail: a direct + # tail call when the drain has nothing to do on this step, else + # the trampoline and unwind (SPU_DIRECT, spu_context.h). +- return (f"if ({cond}) {{ SPU_DIRECT(ctx, 0x{tgt:X}, " ++ return (f"if ({cond}) {{ SPU_DIRECT(ctx, {self._pc(tgt)}, " + f"{self.prefix}spu_func_{tgt:08X}); }}") + # Interrupt enable/disable bits on the bi family (bie/bid, irete/iretd, + # bisle(d)...): bit 0x40000 = E (enable), 0x80000 = D (disable), taking +@@ -991,17 +1010,18 @@ class SPULifter: + # SPU_DRAIN + image save/restore) so the callee's tail-chains drain + # here and its `bi $r0` returns via host return. + # read the target BEFORE writing the link: rt may be the same register as ra +- return (f"{{ uint32_t _tg = {g(tgt_reg)}._u32[0]; {g(link_rt)} = spu_link(0x{(addr + 4) & 0x3FFFC:X}); " +- f"int32_t _si = (int32_t)ctx->image_id; " ++ rs, rr = ("const int32_t _rd = ctx->reloc_delta; ", " ctx->reloc_delta = _rd;") if self.reloc else ("", "") ++ return (f"{{ uint32_t _tg = {g(tgt_reg)}._u32[0]; {g(link_rt)} = spu_link({self._pc((addr + 4) & 0x3FFFC)}); " ++ f"int32_t _si = (int32_t)ctx->image_id; {rs}" + f"{_ied}ctx->pc = _tg; ctx->host_depth++; " +- f"spu_indirect_branch(ctx); spu_drain_call(ctx, 0x{addr + 4:X}); " +- f"ctx->host_depth--; spu_img_restore(ctx, _si); }}") ++ f"spu_indirect_branch(ctx); spu_drain_call(ctx, {self._pc(addr + 4)}); " ++ f"ctx->host_depth--; spu_img_restore(ctx, _si);{rr} }}") + # bisled: set link, branch to RA only if an external event is pending. + if mn in ("bisled",): + link_rt = insn.raw & 0x7F # rt = link + tgt_reg = (insn.raw >> 7) & 0x7F # ra = target (the disassembler's last operand is rb, not the target) + # read the target before writing the link: rt may alias ra +- return (f"{{ uint32_t _tg = {g(tgt_reg)}._u32[0]; {g(link_rt)} = spu_link(0x{(addr + 4) & 0x3FFFC:X}); " ++ return (f"{{ uint32_t _tg = {g(tgt_reg)}._u32[0]; {g(link_rt)} = spu_link({self._pc((addr + 4) & 0x3FFFC)}); " + f"if ((ctx->event_status & ctx->event_mask) != 0) {{ " + f"{_ied}ctx->pc = _tg; " + f"g_spu_trampoline_fn = spu_indirect_branch; return; }} }}") +@@ -1057,7 +1077,7 @@ class SPULifter: + # drain has nothing to do on this step, else hand the target to the + # trampoline and unwind so the enclosing SPU_DRAIN re-enters (no + # host-stack growth either way; SPU_DIRECT, spu_context.h). +- return (f"{{ SPU_DIRECT(ctx, 0x{tgt:X}, {self.prefix}spu_func_{tgt:08X}); }}") ++ return (f"{{ SPU_DIRECT(ctx, {self._pc(tgt)}, {self.prefix}spu_func_{tgt:08X}); }}") + + # ------------------------------------------------------------------ # + def emit_header(self) -> str: +@@ -1101,7 +1121,8 @@ class SPULifter: + lines.append(" * branches that escape a function's range). */") + for t in externs: + lines.append(f"void {self.prefix}spu_func_{t:08X}(spu_context* ctx) {{") +- lines.append(f" ctx->pc = 0x{t:X}u; " ++ pc = self._pc(t) if self.reloc else f"0x{t:X}u" ++ lines.append(f" ctx->pc = {pc}; " + f"g_spu_trampoline_fn = spu_indirect_branch; return;") + lines.append("}") + lines.append("") +@@ -1186,6 +1207,11 @@ def main() -> None: + "by trampolines. Every chunk is still emitted and " + "registered on its own for indirect entry, so this only " + "changes speed, not which code can be reached.") ++ p.add_argument("--reloc", action="store_true", ++ help="Position-independent code the title places at a different LS " ++ "address per load: lift once at --base, and offset every " ++ "pc-derived address by ctx->reloc_delta at run time (register " ++ "with spu_overlay_register_region_reloc).") + p.add_argument("--max-group-insns", type=int, default=4000, + help="Cap on instructions per merged group (keeps clang fast).") + p.add_argument("--force-indirect", default="", +@@ -1311,6 +1337,7 @@ def main() -> None: + insns = disassemble_spu(data, base) + + lifter = SPULifter(trace=args.trace, prefix=args.symbol_prefix) ++ lifter.reloc = args.reloc + lifter.bi_r0_jump = compute_bi_r0_jumps(insns, bounds) + if lifter.bi_r0_jump: + print(f" {len(lifter.bi_r0_jump)} `bi $r0` computed-jump site(s) " diff --git a/tasks/sp00nznet__ps3recomp-636/tests/test.sh b/tasks/sp00nznet__ps3recomp-636/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-636/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-636/tests/verifier.py b/tasks/sp00nznet__ps3recomp-636/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-636/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-637/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-637/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-637/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-637/instruction.md b/tasks/sp00nznet__ps3recomp-637/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a3ce46029c15afd2a735b93494b502f309ae58d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-637/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** spu_context: quadword LS access as one load/store and a word-swap pshufb on SSSE3 x86 (SPU_LS_VEC) + +## Description + +## What + +On x86, `spu_ls_read128` / `spu_ls_write128` (`SPU_LS_FAST`) swap each word with a `bswap` through four 32-bit memory accesses. In lifted code, the next 16-byte load reads back the register those four stores just wrote. A 16-byte load can't be store-forwarded from four narrower stores, so every `lqd`/`lqx`/`stqd` pays a forwarding stall. + +With `SPU_LS_VEC` (on by default when `__SSSE3__` is defined on x86-64), the quadword is one 16-byte load or store plus one `pshufb` that byte-swaps each word. This is the x86 counterpart of the existing NEON `rev32` path. The block comment above the accessors already described this form; this PR makes the code match it. + +- Per-lane `_u32` semantics are the same as before. +- `-DSPU_LS_VEC=0` keeps the scalar form. +- MSVC builds without `__SSSE3__` also keep the scalar form. +- NEON is unchanged. + +## Tests + +The `test_spu_helpers` cases for `lqd`/`stqd` (big-endian words, aligned and wrapped addresses) ran with gcc 9.4 (WSL): + +| flags | SPU_LS_VEC | result | +|---|---|---| +| default | 0 | `SPU helper tests: 72 passed, 0 failed` | +| `-mssse3` | 1 | `SPU helper tests: 72 passed, 0 failed` | +| `-mssse3 -DSPU_LS_VEC=0` | 0 | `SPU helper tests: 72 passed, 0 failed` | +| `-march=haswell -O2` | 1 | `SPU helper tests: 72 passed, 0 failed` | + +I added one line to the test's build comment saying that `-mssse3` covers the vector path. + +## Performance + +Measured on a v0.17.0-based tree, a game port built with clang-cl at `-march=x86-64-v3`. I used a job replay of 300 captured SPU jobs from one hot job module, which are float/shuffle-heavy: + +- all 300 results identical with and without the change; +- minimum time per job 2.17 → 2.12 ms (~2%). + +Not yet verified on master or on other titles. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-637/solution/patch.diff b/tasks/sp00nznet__ps3recomp-637/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5e3226603a3a82775d22a4622087dc93507bcd2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-637/solution/patch.diff @@ -0,0 +1,68 @@ +diff --git a/runtime/spu/spu_context.h b/runtime/spu/spu_context.h +index c5ccbec7..46f8c389 100644 +--- a/runtime/spu/spu_context.h ++++ b/runtime/spu/spu_context.h +@@ -519,9 +519,9 @@ static inline void spu_ls_write32(spu_context* ctx, uint32_t lsa, uint32_t val) + * helpers in `spu_helpers.h` were written against. */ + /* The 128-bit LS accessors are THE hot primitive of lifted SPU execution + * (every load/store in a Bink movie frame's ~millions of lifted instructions +- * runs through here). On x86 the whole BE<->LE quadword swizzle is one +- * SSSE3 byte-shuffle instead of 16 scalar byte ops -- measured against the +- * scalar path with the same per-lane _u32 semantics. */ ++ * runs through here). SPU_LS_FAST swaps each word with a bswap; on an SSSE3 ++ * x86 host SPU_LS_VEC (below) does the whole BE<->LE quadword swizzle as one ++ * byte-shuffle, as rev32 does on NEON, with the same per-lane _u32 semantics. */ + #if defined(_MSC_VER) + #include <stdlib.h> + #define SPU_BSWAP32(x) _byteswap_ulong(x) +@@ -533,6 +533,20 @@ static inline void spu_ls_write32(spu_context* ctx, uint32_t lsa, uint32_t val) + #if defined(__ARM_NEON) + #include <arm_neon.h> /* the quadword swap is one rev32 */ + #endif ++/* SPU_LS_VEC: the quadword as one 16-byte load or store and one pshufb that ++ * byte-swaps each word. The four 32-bit stores of the scalar form, read back by ++ * the next 16-byte load of the register, cannot be store-forwarded: a stall on ++ * every lqd/lqx of lifted code. Define SPU_LS_VEC=0 to keep the scalar form. */ ++#if !defined(SPU_LS_VEC) && !defined(__ARM_NEON) && defined(__SSSE3__) && \ ++ (defined(__x86_64__) || defined(_M_X64)) ++#define SPU_LS_VEC 1 ++#endif ++#if SPU_LS_VEC ++#include <tmmintrin.h> ++static inline __m128i spu_ls_bswap_words(__m128i x) { ++ return _mm_shuffle_epi8(x, _mm_setr_epi8(3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12)); ++} ++#endif + + /* Debug probes of spu_ls_read128/write128, out of line: inlined they kept + * every LS load a real call (~10% of GH3's FMOD mixer task). +@@ -628,6 +642,8 @@ static inline u128 spu_ls_read128(const spu_context* ctx, uint32_t lsa) + const uint8_t* p = &ctx->ls[lsa]; + #if defined(__ARM_NEON) + vst1q_u8(v._u8, vrev32q_u8(vld1q_u8(p))); /* ldr q; rev32 */ ++#elif SPU_LS_VEC ++ _mm_storeu_si128((__m128i*)v._u8, spu_ls_bswap_words(_mm_loadu_si128((const __m128i*)p))); + #elif SPU_LS_FAST + uint32_t w0, w1, w2, w3; + memcpy(&w0, p, 4); memcpy(&w1, p + 4, 4); +@@ -725,6 +741,8 @@ static inline void spu_ls_write128(spu_context* ctx, uint32_t lsa, u128 val) + uint8_t* p = &ctx->ls[lsa]; + #if defined(__ARM_NEON) + vst1q_u8(p, vrev32q_u8(vld1q_u8(val._u8))); /* rev32; str q */ ++#elif SPU_LS_VEC ++ _mm_storeu_si128((__m128i*)p, spu_ls_bswap_words(_mm_loadu_si128((const __m128i*)val._u8))); + #elif SPU_LS_FAST + uint32_t w0 = SPU_BSWAP32(val._u32[0]), w1 = SPU_BSWAP32(val._u32[1]); + uint32_t w2 = SPU_BSWAP32(val._u32[2]), w3 = SPU_BSWAP32(val._u32[3]); +diff --git a/runtime/spu/tests/test_spu_helpers.c b/runtime/spu/tests/test_spu_helpers.c +index 1c95a40b..2c7d567a 100644 +--- a/runtime/spu/tests/test_spu_helpers.c ++++ b/runtime/spu/tests/test_spu_helpers.c +@@ -9,6 +9,7 @@ + * + * Build: + * gcc -std=c11 -I../.. test_spu_helpers.c -o test_spu_helpers ++ * (add -mssse3 on x86 to cover the SPU_LS_VEC quadword path of spu_context.h) + * + * Exit code: 0 if all passed, 1 if any failed. Final line prints summary. + */ diff --git a/tasks/sp00nznet__ps3recomp-637/solution/solve.sh b/tasks/sp00nznet__ps3recomp-637/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-637/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-637/task.toml b/tasks/sp00nznet__ps3recomp-637/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5a8461218793012e2c69dbbd7c2422563ac5d47b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-637/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-637" +description = "spu_context: quadword LS access as one load/store and a word-swap pshufb on SSSE3 x86 (SPU_LS_VEC)" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/637" +source_access = "auto" +built_at = "2026-11-16T16:09:59.660123+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:143b293c49cf5e460aa018782a868ccd26c8ff9f3bdb5e37d008fb6e97b106a2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "runtime/spu/spu_context.h", + "runtime/spu/tests/test_spu_helpers.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 25 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.139880+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-637/tests/capture.py b/tasks/sp00nznet__ps3recomp-637/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-637/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-637/tests/instruction.md b/tasks/sp00nznet__ps3recomp-637/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a3ce46029c15afd2a735b93494b502f309ae58d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-637/tests/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** spu_context: quadword LS access as one load/store and a word-swap pshufb on SSSE3 x86 (SPU_LS_VEC) + +## Description + +## What + +On x86, `spu_ls_read128` / `spu_ls_write128` (`SPU_LS_FAST`) swap each word with a `bswap` through four 32-bit memory accesses. In lifted code, the next 16-byte load reads back the register those four stores just wrote. A 16-byte load can't be store-forwarded from four narrower stores, so every `lqd`/`lqx`/`stqd` pays a forwarding stall. + +With `SPU_LS_VEC` (on by default when `__SSSE3__` is defined on x86-64), the quadword is one 16-byte load or store plus one `pshufb` that byte-swaps each word. This is the x86 counterpart of the existing NEON `rev32` path. The block comment above the accessors already described this form; this PR makes the code match it. + +- Per-lane `_u32` semantics are the same as before. +- `-DSPU_LS_VEC=0` keeps the scalar form. +- MSVC builds without `__SSSE3__` also keep the scalar form. +- NEON is unchanged. + +## Tests + +The `test_spu_helpers` cases for `lqd`/`stqd` (big-endian words, aligned and wrapped addresses) ran with gcc 9.4 (WSL): + +| flags | SPU_LS_VEC | result | +|---|---|---| +| default | 0 | `SPU helper tests: 72 passed, 0 failed` | +| `-mssse3` | 1 | `SPU helper tests: 72 passed, 0 failed` | +| `-mssse3 -DSPU_LS_VEC=0` | 0 | `SPU helper tests: 72 passed, 0 failed` | +| `-march=haswell -O2` | 1 | `SPU helper tests: 72 passed, 0 failed` | + +I added one line to the test's build comment saying that `-mssse3` covers the vector path. + +## Performance + +Measured on a v0.17.0-based tree, a game port built with clang-cl at `-march=x86-64-v3`. I used a job replay of 300 captured SPU jobs from one hot job module, which are float/shuffle-heavy: + +- all 300 results identical with and without the change; +- minimum time per job 2.17 → 2.12 ms (~2%). + +Not yet verified on master or on other titles. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-637/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-637/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5e3226603a3a82775d22a4622087dc93507bcd2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-637/tests/oracle.patch @@ -0,0 +1,68 @@ +diff --git a/runtime/spu/spu_context.h b/runtime/spu/spu_context.h +index c5ccbec7..46f8c389 100644 +--- a/runtime/spu/spu_context.h ++++ b/runtime/spu/spu_context.h +@@ -519,9 +519,9 @@ static inline void spu_ls_write32(spu_context* ctx, uint32_t lsa, uint32_t val) + * helpers in `spu_helpers.h` were written against. */ + /* The 128-bit LS accessors are THE hot primitive of lifted SPU execution + * (every load/store in a Bink movie frame's ~millions of lifted instructions +- * runs through here). On x86 the whole BE<->LE quadword swizzle is one +- * SSSE3 byte-shuffle instead of 16 scalar byte ops -- measured against the +- * scalar path with the same per-lane _u32 semantics. */ ++ * runs through here). SPU_LS_FAST swaps each word with a bswap; on an SSSE3 ++ * x86 host SPU_LS_VEC (below) does the whole BE<->LE quadword swizzle as one ++ * byte-shuffle, as rev32 does on NEON, with the same per-lane _u32 semantics. */ + #if defined(_MSC_VER) + #include <stdlib.h> + #define SPU_BSWAP32(x) _byteswap_ulong(x) +@@ -533,6 +533,20 @@ static inline void spu_ls_write32(spu_context* ctx, uint32_t lsa, uint32_t val) + #if defined(__ARM_NEON) + #include <arm_neon.h> /* the quadword swap is one rev32 */ + #endif ++/* SPU_LS_VEC: the quadword as one 16-byte load or store and one pshufb that ++ * byte-swaps each word. The four 32-bit stores of the scalar form, read back by ++ * the next 16-byte load of the register, cannot be store-forwarded: a stall on ++ * every lqd/lqx of lifted code. Define SPU_LS_VEC=0 to keep the scalar form. */ ++#if !defined(SPU_LS_VEC) && !defined(__ARM_NEON) && defined(__SSSE3__) && \ ++ (defined(__x86_64__) || defined(_M_X64)) ++#define SPU_LS_VEC 1 ++#endif ++#if SPU_LS_VEC ++#include <tmmintrin.h> ++static inline __m128i spu_ls_bswap_words(__m128i x) { ++ return _mm_shuffle_epi8(x, _mm_setr_epi8(3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12)); ++} ++#endif + + /* Debug probes of spu_ls_read128/write128, out of line: inlined they kept + * every LS load a real call (~10% of GH3's FMOD mixer task). +@@ -628,6 +642,8 @@ static inline u128 spu_ls_read128(const spu_context* ctx, uint32_t lsa) + const uint8_t* p = &ctx->ls[lsa]; + #if defined(__ARM_NEON) + vst1q_u8(v._u8, vrev32q_u8(vld1q_u8(p))); /* ldr q; rev32 */ ++#elif SPU_LS_VEC ++ _mm_storeu_si128((__m128i*)v._u8, spu_ls_bswap_words(_mm_loadu_si128((const __m128i*)p))); + #elif SPU_LS_FAST + uint32_t w0, w1, w2, w3; + memcpy(&w0, p, 4); memcpy(&w1, p + 4, 4); +@@ -725,6 +741,8 @@ static inline void spu_ls_write128(spu_context* ctx, uint32_t lsa, u128 val) + uint8_t* p = &ctx->ls[lsa]; + #if defined(__ARM_NEON) + vst1q_u8(p, vrev32q_u8(vld1q_u8(val._u8))); /* rev32; str q */ ++#elif SPU_LS_VEC ++ _mm_storeu_si128((__m128i*)p, spu_ls_bswap_words(_mm_loadu_si128((const __m128i*)val._u8))); + #elif SPU_LS_FAST + uint32_t w0 = SPU_BSWAP32(val._u32[0]), w1 = SPU_BSWAP32(val._u32[1]); + uint32_t w2 = SPU_BSWAP32(val._u32[2]), w3 = SPU_BSWAP32(val._u32[3]); +diff --git a/runtime/spu/tests/test_spu_helpers.c b/runtime/spu/tests/test_spu_helpers.c +index 1c95a40b..2c7d567a 100644 +--- a/runtime/spu/tests/test_spu_helpers.c ++++ b/runtime/spu/tests/test_spu_helpers.c +@@ -9,6 +9,7 @@ + * + * Build: + * gcc -std=c11 -I../.. test_spu_helpers.c -o test_spu_helpers ++ * (add -mssse3 on x86 to cover the SPU_LS_VEC quadword path of spu_context.h) + * + * Exit code: 0 if all passed, 1 if any failed. Final line prints summary. + */ diff --git a/tasks/sp00nznet__ps3recomp-637/tests/test.sh b/tasks/sp00nznet__ps3recomp-637/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-637/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-637/tests/verifier.py b/tasks/sp00nznet__ps3recomp-637/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-637/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-640/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-640/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-640/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-640/instruction.md b/tasks/sp00nznet__ps3recomp-640/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef3663adb5fdf7f54fe3200f4f618f9751225179 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-640/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** templates: use the Vulkan backend on Linux when built + +## Description + +## Why +`templates/project/main.cpp` selects D3D12 on Windows, Metal on macOS, and the null backend everywhere else. Consequently, a standalone project configured with `-DPS3RECOMP_RSX_VULKAN=ON` on Linux still defaults to running headless with the null backend. + +`runtime/host/host_posix.c` already selects Vulkan when `PS3RECOMP_RSX_VULKAN` is defined; this adds the corresponding case to the project template using `rsx_vulkan_backend_init`, `rsx_vulkan_backend_present`, and `rsx_vulkan_backend_pump_messages` from `rsx_vulkan_backend.h`. + +## What changed +- Added `#elif defined(PS3RECOMP_RSX_VULKAN)` block in `templates/project/main.cpp` mapping the generic `rsx_backend_*` macros to the Vulkan backend functions. + +## Testing & Verification +- Tested on Linux (Fedora 44, RTX 3060 Ti, Wayland): before this change, the template ran headless; with this change, the Vulkan window opens and renders guest frames with `PS3RECOMP_VK_GUEST_PROGRAMS=1`. +- Clean-room change, no game data or proprietary code included. + +Relates to #183. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-640/solution/patch.diff b/tasks/sp00nznet__ps3recomp-640/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..afe00edb86740952bff6ce1cc79633c0ef00d903 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-640/solution/patch.diff @@ -0,0 +1,19 @@ +diff --git a/templates/project/main.cpp b/templates/project/main.cpp +index f1f3243b..6715ca99 100644 +--- a/templates/project/main.cpp ++++ b/templates/project/main.cpp +@@ -136,6 +136,14 @@ extern "C" int rsx_metal_backend_pump_messages(void); + # define rsx_backend_present rsx_metal_backend_present + # define rsx_backend_pump rsx_metal_backend_pump_messages + # define RSX_BACKEND_NAME "Metal" ++#elif defined(PS3RECOMP_RSX_VULKAN) ++extern "C" int rsx_vulkan_backend_init(uint32_t w, uint32_t h, const char* title); ++extern "C" void rsx_vulkan_backend_present(void); ++extern "C" int rsx_vulkan_backend_pump_messages(void); ++# define rsx_backend_init rsx_vulkan_backend_init ++# define rsx_backend_present rsx_vulkan_backend_present ++# define rsx_backend_pump rsx_vulkan_backend_pump_messages ++# define RSX_BACKEND_NAME "Vulkan" + #else + extern "C" int rsx_null_backend_init(uint32_t w, uint32_t h, const char* title); + extern "C" void rsx_null_backend_present(void); diff --git a/tasks/sp00nznet__ps3recomp-640/solution/solve.sh b/tasks/sp00nznet__ps3recomp-640/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-640/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-640/task.toml b/tasks/sp00nznet__ps3recomp-640/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fd07a1c20e70e99ac1dea88f48df99d0193242e7 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-640/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-640" +description = "templates: use the Vulkan backend on Linux when built" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/640" +source_access = "auto" +built_at = "2026-11-16T16:09:59.743428+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:63d9516d1c971925e63cce1e3c3e40f2ddba418c5728718b991b9a4aa2fc27a6" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "templates/project/main.cpp", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.140584+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-640/tests/capture.py b/tasks/sp00nznet__ps3recomp-640/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-640/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-640/tests/instruction.md b/tasks/sp00nznet__ps3recomp-640/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef3663adb5fdf7f54fe3200f4f618f9751225179 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-640/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** templates: use the Vulkan backend on Linux when built + +## Description + +## Why +`templates/project/main.cpp` selects D3D12 on Windows, Metal on macOS, and the null backend everywhere else. Consequently, a standalone project configured with `-DPS3RECOMP_RSX_VULKAN=ON` on Linux still defaults to running headless with the null backend. + +`runtime/host/host_posix.c` already selects Vulkan when `PS3RECOMP_RSX_VULKAN` is defined; this adds the corresponding case to the project template using `rsx_vulkan_backend_init`, `rsx_vulkan_backend_present`, and `rsx_vulkan_backend_pump_messages` from `rsx_vulkan_backend.h`. + +## What changed +- Added `#elif defined(PS3RECOMP_RSX_VULKAN)` block in `templates/project/main.cpp` mapping the generic `rsx_backend_*` macros to the Vulkan backend functions. + +## Testing & Verification +- Tested on Linux (Fedora 44, RTX 3060 Ti, Wayland): before this change, the template ran headless; with this change, the Vulkan window opens and renders guest frames with `PS3RECOMP_VK_GUEST_PROGRAMS=1`. +- Clean-room change, no game data or proprietary code included. + +Relates to #183. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-640/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-640/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..afe00edb86740952bff6ce1cc79633c0ef00d903 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-640/tests/oracle.patch @@ -0,0 +1,19 @@ +diff --git a/templates/project/main.cpp b/templates/project/main.cpp +index f1f3243b..6715ca99 100644 +--- a/templates/project/main.cpp ++++ b/templates/project/main.cpp +@@ -136,6 +136,14 @@ extern "C" int rsx_metal_backend_pump_messages(void); + # define rsx_backend_present rsx_metal_backend_present + # define rsx_backend_pump rsx_metal_backend_pump_messages + # define RSX_BACKEND_NAME "Metal" ++#elif defined(PS3RECOMP_RSX_VULKAN) ++extern "C" int rsx_vulkan_backend_init(uint32_t w, uint32_t h, const char* title); ++extern "C" void rsx_vulkan_backend_present(void); ++extern "C" int rsx_vulkan_backend_pump_messages(void); ++# define rsx_backend_init rsx_vulkan_backend_init ++# define rsx_backend_present rsx_vulkan_backend_present ++# define rsx_backend_pump rsx_vulkan_backend_pump_messages ++# define RSX_BACKEND_NAME "Vulkan" + #else + extern "C" int rsx_null_backend_init(uint32_t w, uint32_t h, const char* title); + extern "C" void rsx_null_backend_present(void); diff --git a/tasks/sp00nznet__ps3recomp-640/tests/test.sh b/tasks/sp00nznet__ps3recomp-640/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-640/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-640/tests/verifier.py b/tasks/sp00nznet__ps3recomp-640/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-640/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-641/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-641/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-641/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-641/instruction.md b/tasks/sp00nznet__ps3recomp-641/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..08cfcf1129b3f3715d446e5870ea8304d11cb97b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-641/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** cellFs: implement cellFsAioWrite (0x4CEF342E) alongside cellFsAioRead + +## Description + +## Why +`cellFsAioWrite` (NID `0x4CEF342E`) was previously unregistered in `runtime/ppu/ppu_fs.cpp`. Unregistered NIDs take the unresolved fallthrough path returning `CELL_OK`, which meant nothing was written to disk and the completion callback never executed. + +In *MLB The Show 16* (BCUS01089) as well as *MLB 15 The Show* (, Bug 1), game data and cached assets are copied to `/dev_hdd1` in 64 KB blocks using `cellFsAioWrite`, and the title polls a completion status flag updated by the AIO callback. Without the callback firing, boot hangs indefinitely on the initial autosave/loading screen. + +## What changed +- Added `cellFsAioWrite` in `runtime/ppu/ppu_fs.cpp` alongside the existing `cellFsAioRead`, implementing the same contract and synchronous completion model: + - Validates and performs absolute seek/write using `HOST_LOCKFILE`, `HOST_FSEEK64`, and `fwrite`, restoring the file descriptor offset afterward. + - Updates the returned AIO ID. + - Dispatches the guest callback `ps3_invoke_guest(cb_opd, aio, err, id, n, ...)`. +- Registered `0x4CEF342Eu` in `ppu_fs_register()`. + +## Testing & Verification +- Tested in *MLB The Show 16*: the title makes ~500 asynchronous writes during initial cache generation and successfully transitions to the experience selection screen instead of freezing on the splash screen. +- Verified on macOS and Linux builds. +- Clean-room implementation per standard PS3 SDK `cellFsAioWrite` signature and semantics. No proprietary assets included. + +Resolves item 1 in #551. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-641/solution/patch.diff b/tasks/sp00nznet__ps3recomp-641/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..846a1455c83ff53aa13e28a7b03d614280fe3b32 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-641/solution/patch.diff @@ -0,0 +1,61 @@ +diff --git a/runtime/ppu/ppu_fs.cpp b/runtime/ppu/ppu_fs.cpp +index f73907c2..35f257e8 100644 +--- a/runtime/ppu/ppu_fs.cpp ++++ b/runtime/ppu/ppu_fs.cpp +@@ -978,6 +978,49 @@ static void cellFsAioRead(ppu_context* ctx) + (uint64_t)(int64_t)id, (uint64_t)n, 0, 0, 0, 0); + } + ++/* MLB The Show 16 copies files into its /dev_hdd1 cache in 64 KB chunks, each ++ * written with cellFsAioWrite, and polls a status word its completion callback ++ * sets. With the NID unresolved the submit "succeeded", nothing was written, the ++ * callback never ran, and the boot parked on the first screen. Same contract and ++ * the same synchronous-completion shortcut as cellFsAioRead above. */ ++static void cellFsAioWrite(ppu_context* ctx) ++{ ++ uint32_t aio = (uint32_t)ctx->gpr[3]; ++ uint32_t id_ptr = (uint32_t)ctx->gpr[4]; ++ uint32_t cb_opd = (uint32_t)ctx->gpr[5]; ++ ++ int fd = (int)guest_be32(aio + 0x00); ++ uint64_t offset = guest_be64(aio + 0x08); ++ uint32_t buf = guest_be32(aio + 0x10); ++ uint64_t size = guest_be64(aio + 0x18); ++ ++ static std::atomic<int32_t> s_next_id{1}; ++ int32_t id = s_next_id++; ++ if (id_ptr) vm_write32(id_ptr, (uint32_t)id); ++ ++ size_t n = 0; ++ int32_t err = CELL_FS_ENOENT; ++ if (FILE* f = fd_file(fd)) { ++ if (ppu_vm_size && (uint64_t)buf + size > ppu_vm_size) size = ppu_vm_size - buf; ++ /* Absolute, like the read: leave the fd's own position where it was. */ ++ HOST_LOCKFILE(f); ++ const int64_t pos = (int64_t)HOST_FTELL64(f); ++ if (HOST_FSEEK64(f, offset) == 0) ++ n = fwrite(vm_base + buf, 1, (size_t)size, f); ++ fflush(f); ++ if (pos >= 0) HOST_FSEEK64(f, pos); ++ HOST_UNLOCKFILE(f); ++ err = (n == size) ? CELL_OK : CELL_FS_EIO; ++ } ++ if (getenv("PS3_FSLOG")) ++ fprintf(stderr, "[fs] aio write id=%d fd=%d off=%llu size=%llu -> %zu\n", ++ id, fd, (unsigned long long)offset, (unsigned long long)size, n); ++ ++ ctx->gpr[3] = CELL_OK; ++ if (cb_opd) ps3_invoke_guest(cb_opd, aio, (uint64_t)(int64_t)err, ++ (uint64_t)(int64_t)id, (uint64_t)n, 0, 0, 0, 0); ++} ++ + extern "C" void ppu_fs_register(void) + { + ps3_hle_register_ctx(ps3_compute_nid("cellFsOpen"), "cellFsOpen", cellFsOpen); +@@ -1012,5 +1055,6 @@ extern "C" void ppu_fs_register(void) + ps3_hle_register_ctx(0xDB869F20u, "cellFsAioInit", cellFsAioInit); + ps3_hle_register_ctx(0x9F951810u, "cellFsAioFinish", cellFsAioFinish); + ps3_hle_register_ctx(0xC1C507E7u, "cellFsAioRead", cellFsAioRead); ++ ps3_hle_register_ctx(0x4CEF342Eu, "cellFsAioWrite", cellFsAioWrite); + ps3_hle_register_ctx(0x7F13FC8Cu, "cellFsAioCancel", cellFsAioCancel); + } diff --git a/tasks/sp00nznet__ps3recomp-641/solution/solve.sh b/tasks/sp00nznet__ps3recomp-641/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-641/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-641/task.toml b/tasks/sp00nznet__ps3recomp-641/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ea1a1f318e81ae14d88395ea1ee9e52473dace5d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-641/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-641" +description = "cellFs: implement cellFsAioWrite (0x4CEF342E) alongside cellFsAioRead" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/641" +source_access = "auto" +built_at = "2026-11-16T16:09:59.658203+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9ee3220f9573e24e1271f9ac16cadb3996ea38115b8e8e1d5b70b50f14b1a7b7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "runtime/ppu/ppu_fs.cpp", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 44 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.141178+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-641/tests/capture.py b/tasks/sp00nznet__ps3recomp-641/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-641/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-641/tests/instruction.md b/tasks/sp00nznet__ps3recomp-641/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..08cfcf1129b3f3715d446e5870ea8304d11cb97b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-641/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** cellFs: implement cellFsAioWrite (0x4CEF342E) alongside cellFsAioRead + +## Description + +## Why +`cellFsAioWrite` (NID `0x4CEF342E`) was previously unregistered in `runtime/ppu/ppu_fs.cpp`. Unregistered NIDs take the unresolved fallthrough path returning `CELL_OK`, which meant nothing was written to disk and the completion callback never executed. + +In *MLB The Show 16* (BCUS01089) as well as *MLB 15 The Show* (, Bug 1), game data and cached assets are copied to `/dev_hdd1` in 64 KB blocks using `cellFsAioWrite`, and the title polls a completion status flag updated by the AIO callback. Without the callback firing, boot hangs indefinitely on the initial autosave/loading screen. + +## What changed +- Added `cellFsAioWrite` in `runtime/ppu/ppu_fs.cpp` alongside the existing `cellFsAioRead`, implementing the same contract and synchronous completion model: + - Validates and performs absolute seek/write using `HOST_LOCKFILE`, `HOST_FSEEK64`, and `fwrite`, restoring the file descriptor offset afterward. + - Updates the returned AIO ID. + - Dispatches the guest callback `ps3_invoke_guest(cb_opd, aio, err, id, n, ...)`. +- Registered `0x4CEF342Eu` in `ppu_fs_register()`. + +## Testing & Verification +- Tested in *MLB The Show 16*: the title makes ~500 asynchronous writes during initial cache generation and successfully transitions to the experience selection screen instead of freezing on the splash screen. +- Verified on macOS and Linux builds. +- Clean-room implementation per standard PS3 SDK `cellFsAioWrite` signature and semantics. No proprietary assets included. + +Resolves item 1 in #551. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-641/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-641/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..846a1455c83ff53aa13e28a7b03d614280fe3b32 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-641/tests/oracle.patch @@ -0,0 +1,61 @@ +diff --git a/runtime/ppu/ppu_fs.cpp b/runtime/ppu/ppu_fs.cpp +index f73907c2..35f257e8 100644 +--- a/runtime/ppu/ppu_fs.cpp ++++ b/runtime/ppu/ppu_fs.cpp +@@ -978,6 +978,49 @@ static void cellFsAioRead(ppu_context* ctx) + (uint64_t)(int64_t)id, (uint64_t)n, 0, 0, 0, 0); + } + ++/* MLB The Show 16 copies files into its /dev_hdd1 cache in 64 KB chunks, each ++ * written with cellFsAioWrite, and polls a status word its completion callback ++ * sets. With the NID unresolved the submit "succeeded", nothing was written, the ++ * callback never ran, and the boot parked on the first screen. Same contract and ++ * the same synchronous-completion shortcut as cellFsAioRead above. */ ++static void cellFsAioWrite(ppu_context* ctx) ++{ ++ uint32_t aio = (uint32_t)ctx->gpr[3]; ++ uint32_t id_ptr = (uint32_t)ctx->gpr[4]; ++ uint32_t cb_opd = (uint32_t)ctx->gpr[5]; ++ ++ int fd = (int)guest_be32(aio + 0x00); ++ uint64_t offset = guest_be64(aio + 0x08); ++ uint32_t buf = guest_be32(aio + 0x10); ++ uint64_t size = guest_be64(aio + 0x18); ++ ++ static std::atomic<int32_t> s_next_id{1}; ++ int32_t id = s_next_id++; ++ if (id_ptr) vm_write32(id_ptr, (uint32_t)id); ++ ++ size_t n = 0; ++ int32_t err = CELL_FS_ENOENT; ++ if (FILE* f = fd_file(fd)) { ++ if (ppu_vm_size && (uint64_t)buf + size > ppu_vm_size) size = ppu_vm_size - buf; ++ /* Absolute, like the read: leave the fd's own position where it was. */ ++ HOST_LOCKFILE(f); ++ const int64_t pos = (int64_t)HOST_FTELL64(f); ++ if (HOST_FSEEK64(f, offset) == 0) ++ n = fwrite(vm_base + buf, 1, (size_t)size, f); ++ fflush(f); ++ if (pos >= 0) HOST_FSEEK64(f, pos); ++ HOST_UNLOCKFILE(f); ++ err = (n == size) ? CELL_OK : CELL_FS_EIO; ++ } ++ if (getenv("PS3_FSLOG")) ++ fprintf(stderr, "[fs] aio write id=%d fd=%d off=%llu size=%llu -> %zu\n", ++ id, fd, (unsigned long long)offset, (unsigned long long)size, n); ++ ++ ctx->gpr[3] = CELL_OK; ++ if (cb_opd) ps3_invoke_guest(cb_opd, aio, (uint64_t)(int64_t)err, ++ (uint64_t)(int64_t)id, (uint64_t)n, 0, 0, 0, 0); ++} ++ + extern "C" void ppu_fs_register(void) + { + ps3_hle_register_ctx(ps3_compute_nid("cellFsOpen"), "cellFsOpen", cellFsOpen); +@@ -1012,5 +1055,6 @@ extern "C" void ppu_fs_register(void) + ps3_hle_register_ctx(0xDB869F20u, "cellFsAioInit", cellFsAioInit); + ps3_hle_register_ctx(0x9F951810u, "cellFsAioFinish", cellFsAioFinish); + ps3_hle_register_ctx(0xC1C507E7u, "cellFsAioRead", cellFsAioRead); ++ ps3_hle_register_ctx(0x4CEF342Eu, "cellFsAioWrite", cellFsAioWrite); + ps3_hle_register_ctx(0x7F13FC8Cu, "cellFsAioCancel", cellFsAioCancel); + } diff --git a/tasks/sp00nznet__ps3recomp-641/tests/test.sh b/tasks/sp00nznet__ps3recomp-641/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-641/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-641/tests/verifier.py b/tasks/sp00nznet__ps3recomp-641/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-641/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-642/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-642/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-642/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-642/instruction.md b/tasks/sp00nznet__ps3recomp-642/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3fbd7efaa90c749526fda8cf3a534fa90b3b196a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-642/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** cellVideoOut: report stereoscopic 3D resolutions (0x80+) unavailable + +## Description + +## Why +`cellVideoOutGetResolutionAvailability` previously returned 1 for every queried resolution ID on the primary display, including stereoscopic 3D and dual-view packing modes (IDs `0x80` and higher; e.g., `0x81` is 720p 3D frame packing). + +This falsely signaled to games that a 3D-capable TV was connected. In *MLB The Show 16* (and potentially other Sony first-party stereoscopic 3D titles), the game detects the 3D display at boot, displays a prompt to enable stereoscopic 3D mode, and if accepted, renders every frame twice in an over-under stereoscopic viewport. + +## What changed +- In `libs/video/cellVideoOut.c`, filter resolution availability so that IDs `>= 0x80` return 0 (unavailable), while standard 2D primary display resolutions continue returning 1. + +## Testing & Verification +- Tested in *MLB The Show 16*: the game no longer prompts for 3D TV configuration on boot and renders in standard 2D. +- Builds and passes CI tests on macOS and Linux. +- Clean-room change, no proprietary data included. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-642/solution/patch.diff b/tasks/sp00nznet__ps3recomp-642/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..48b83ba832eb68dea372c17a470d89a853adc7ff --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-642/solution/patch.diff @@ -0,0 +1,20 @@ +diff --git a/libs/video/cellVideoOut.c b/libs/video/cellVideoOut.c +index c67a6eaa..f3274b39 100644 +--- a/libs/video/cellVideoOut.c ++++ b/libs/video/cellVideoOut.c +@@ -249,7 +249,12 @@ s32 cellVideoOutGetResolutionAvailability(u32 videoOut, u32 resolutionId, + u32 aspect, u32 option) + { + (void)aspect; (void)option; +- printf("[cellVideoOut] GetResolutionAvailability(out=%u, res=%u) -> 1\n", +- videoOut, resolutionId); +- return (videoOut == CELL_VIDEO_OUT_PRIMARY) ? 1 : 0; ++ /* Stereoscopic 3D and dual-view modes have ids from 0x80 up (0x81 is 720p ++ * frame packing). Reporting them available tells the title a 3D TV is ++ * attached: MLB The Show 16 then asks to switch to 3D and, on yes, renders ++ * every frame twice, stacked over-under. No host display here is one. */ ++ const s32 avail = (videoOut == CELL_VIDEO_OUT_PRIMARY && resolutionId < 0x80) ? 1 : 0; ++ printf("[cellVideoOut] GetResolutionAvailability(out=%u, res=%u) -> %d\n", ++ videoOut, resolutionId, avail); ++ return avail; + } diff --git a/tasks/sp00nznet__ps3recomp-642/solution/solve.sh b/tasks/sp00nznet__ps3recomp-642/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-642/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-642/task.toml b/tasks/sp00nznet__ps3recomp-642/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..675c3dfade619aec4c9656417379e5a7ff27671d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-642/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-642" +description = "cellVideoOut: report stereoscopic 3D resolutions (0x80+) unavailable" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/642" +source_access = "auto" +built_at = "2026-11-16T16:09:59.656491+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4580ac7385ed4ee0f44ba8fb52485a3450ca58122c52af0846e5aa188d0be3f0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/video/cellVideoOut.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 11 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.141875+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-642/tests/capture.py b/tasks/sp00nznet__ps3recomp-642/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-642/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-642/tests/instruction.md b/tasks/sp00nznet__ps3recomp-642/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3fbd7efaa90c749526fda8cf3a534fa90b3b196a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-642/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** cellVideoOut: report stereoscopic 3D resolutions (0x80+) unavailable + +## Description + +## Why +`cellVideoOutGetResolutionAvailability` previously returned 1 for every queried resolution ID on the primary display, including stereoscopic 3D and dual-view packing modes (IDs `0x80` and higher; e.g., `0x81` is 720p 3D frame packing). + +This falsely signaled to games that a 3D-capable TV was connected. In *MLB The Show 16* (and potentially other Sony first-party stereoscopic 3D titles), the game detects the 3D display at boot, displays a prompt to enable stereoscopic 3D mode, and if accepted, renders every frame twice in an over-under stereoscopic viewport. + +## What changed +- In `libs/video/cellVideoOut.c`, filter resolution availability so that IDs `>= 0x80` return 0 (unavailable), while standard 2D primary display resolutions continue returning 1. + +## Testing & Verification +- Tested in *MLB The Show 16*: the game no longer prompts for 3D TV configuration on boot and renders in standard 2D. +- Builds and passes CI tests on macOS and Linux. +- Clean-room change, no proprietary data included. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-642/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-642/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..48b83ba832eb68dea372c17a470d89a853adc7ff --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-642/tests/oracle.patch @@ -0,0 +1,20 @@ +diff --git a/libs/video/cellVideoOut.c b/libs/video/cellVideoOut.c +index c67a6eaa..f3274b39 100644 +--- a/libs/video/cellVideoOut.c ++++ b/libs/video/cellVideoOut.c +@@ -249,7 +249,12 @@ s32 cellVideoOutGetResolutionAvailability(u32 videoOut, u32 resolutionId, + u32 aspect, u32 option) + { + (void)aspect; (void)option; +- printf("[cellVideoOut] GetResolutionAvailability(out=%u, res=%u) -> 1\n", +- videoOut, resolutionId); +- return (videoOut == CELL_VIDEO_OUT_PRIMARY) ? 1 : 0; ++ /* Stereoscopic 3D and dual-view modes have ids from 0x80 up (0x81 is 720p ++ * frame packing). Reporting them available tells the title a 3D TV is ++ * attached: MLB The Show 16 then asks to switch to 3D and, on yes, renders ++ * every frame twice, stacked over-under. No host display here is one. */ ++ const s32 avail = (videoOut == CELL_VIDEO_OUT_PRIMARY && resolutionId < 0x80) ? 1 : 0; ++ printf("[cellVideoOut] GetResolutionAvailability(out=%u, res=%u) -> %d\n", ++ videoOut, resolutionId, avail); ++ return avail; + } diff --git a/tasks/sp00nznet__ps3recomp-642/tests/test.sh b/tasks/sp00nznet__ps3recomp-642/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-642/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-642/tests/verifier.py b/tasks/sp00nznet__ps3recomp-642/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-642/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-643/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-643/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-643/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-643/instruction.md b/tasks/sp00nznet__ps3recomp-643/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..27a839ed7ded5457d8dd747b54c8c6df7f5af72d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-643/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** cellSpurs: carry argTaskset through the taskset attribute + +## Description + +## Why +In `_cellSpursTasksetAttributeInitialize`, the `argTaskset` parameter was ignored and the attribute was zeroed without saving it. Subsequently, `cellSpursCreateTasksetWithAttribute` invoked `spurs_create_taskset` with `args = 0`. + +Per the Cell SPURS specification, `argTaskset` is a 64-bit argument delivered to each SPU task in register `r4`. In titles that pass initialization structures via taskset arguments (such as *MLB The Show 16*'s Bink video SPU task, which DMAs its configuration and event flag address from `r4`, or *Puppeteer* where tasksets initialize with null arguments as noted in #464), receiving 0 caused immediate null pointer dereferences and failure (e.g., `cellSpursEventFlagWait` failing with `0x80410911`), resulting in task retry spin-loops that peg a host core at 100%. + +## What changed +- In `libs/spurs/cellSpurs.c`: + - Store `argTaskset` in `attr->args` within `_cellSpursTasksetAttributeInitialize`. + - Pass `attr_h->args` into `spurs_create_taskset` in `cellSpursCreateTasksetWithAttribute`. + +## Testing & Verification +- Tested in *MLB The Show 16*: the Bink SPU task properly receives its taskset parameter in `r4`, initializes its event flag, and sleeps waiting for work instead of spin-looping at 100% CPU. +- Builds and passes all runtime test suites on macOS and Linux. +- Clean-room implementation per standard Cell SPURS specifications. + +Relates to #464. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-643/solution/patch.diff b/tasks/sp00nznet__ps3recomp-643/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e4333da03f8ed492bb34e3670c9c2bc112f24f96 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-643/solution/patch.diff @@ -0,0 +1,37 @@ +diff --git a/libs/spurs/cellSpurs.c b/libs/spurs/cellSpurs.c +index 82ea66c6..57302177 100644 +--- a/libs/spurs/cellSpurs.c ++++ b/libs/spurs/cellSpurs.c +@@ -934,7 +934,7 @@ s32 cellSpursCreateTasksetWithAttribute(CellSpurs* spurs, + const CellSpursTasksetAttribute* attr_h = GUEST_PTR(attr, const CellSpursTasksetAttribute*); + u32 size = attr_h->tasksetSize; + if (size != 0x1900u && size != 0x2900u) return (s32)0x80410902u; +- return spurs_create_taskset(spurs, taskset, 0, NULL, 0, size); ++ return spurs_create_taskset(spurs, taskset, attr_h->args, NULL, 0, size); + } + + s32 cellSpursDestroyTaskset(CellSpursTaskset* taskset) +@@ -1286,17 +1286,20 @@ s32 cellSpursCreateTaskWithAttribute(CellSpursTaskset* taskset, + attr_h->lsPattern_ea, attr_h->argument_ea); + } + +-/* The SDK's versioned taskset-attribute initializer. We forward taskset creation +- * through CreateTaskset (which ignores the attribute), so just zero the struct. */ ++/* The SDK's versioned taskset-attribute initializer. Only argTaskset and the ++ * size are carried to creation: the taskset argument reaches every task in r4, ++ * and a task that reads its setup through it (MLB The Show 16's Bink task DMAs ++ * its event flag address from there) otherwise gets 0. */ + s32 _cellSpursTasksetAttributeInitialize(CellSpursTasksetAttribute* attr, + u32 revision, u32 sdkVersion, u64 argTaskset, + u64 priority, u32 maxContention) + { +- (void)sdkVersion; (void)argTaskset; (void)priority; (void)maxContention; ++ (void)sdkVersion; (void)priority; (void)maxContention; + if (!attr) return CELL_SPURS_TASK_ERROR_NULL_POINTER; + attr = GUEST_PTR(attr, CellSpursTasksetAttribute*); + memset(attr, 0, sizeof(CellSpursTasksetAttribute)); + attr->revision = revision ? revision : 1; ++ attr->args = argTaskset; + attr->tasksetSize = CSTS_STRUCT_END; + printf("[cellSpurs] _TasksetAttributeInitialize(rev=%u)\n", revision); + return CELL_OK; diff --git a/tasks/sp00nznet__ps3recomp-643/solution/solve.sh b/tasks/sp00nznet__ps3recomp-643/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-643/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-643/task.toml b/tasks/sp00nznet__ps3recomp-643/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9dac834251685809b799a9fb4f1361418ec80d0e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-643/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-643" +description = "cellSpurs: carry argTaskset through the taskset attribute" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/643" +source_access = "auto" +built_at = "2026-11-16T16:09:59.655000+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:703e7c4bce1dafc8241de1b1a9fdff22e7bb73f97a47220ef7defb8136977337" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/spurs/cellSpurs.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 11 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.142546+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-643/tests/capture.py b/tasks/sp00nznet__ps3recomp-643/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-643/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-643/tests/instruction.md b/tasks/sp00nznet__ps3recomp-643/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..27a839ed7ded5457d8dd747b54c8c6df7f5af72d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-643/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** cellSpurs: carry argTaskset through the taskset attribute + +## Description + +## Why +In `_cellSpursTasksetAttributeInitialize`, the `argTaskset` parameter was ignored and the attribute was zeroed without saving it. Subsequently, `cellSpursCreateTasksetWithAttribute` invoked `spurs_create_taskset` with `args = 0`. + +Per the Cell SPURS specification, `argTaskset` is a 64-bit argument delivered to each SPU task in register `r4`. In titles that pass initialization structures via taskset arguments (such as *MLB The Show 16*'s Bink video SPU task, which DMAs its configuration and event flag address from `r4`, or *Puppeteer* where tasksets initialize with null arguments as noted in #464), receiving 0 caused immediate null pointer dereferences and failure (e.g., `cellSpursEventFlagWait` failing with `0x80410911`), resulting in task retry spin-loops that peg a host core at 100%. + +## What changed +- In `libs/spurs/cellSpurs.c`: + - Store `argTaskset` in `attr->args` within `_cellSpursTasksetAttributeInitialize`. + - Pass `attr_h->args` into `spurs_create_taskset` in `cellSpursCreateTasksetWithAttribute`. + +## Testing & Verification +- Tested in *MLB The Show 16*: the Bink SPU task properly receives its taskset parameter in `r4`, initializes its event flag, and sleeps waiting for work instead of spin-looping at 100% CPU. +- Builds and passes all runtime test suites on macOS and Linux. +- Clean-room implementation per standard Cell SPURS specifications. + +Relates to #464. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-643/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-643/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e4333da03f8ed492bb34e3670c9c2bc112f24f96 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-643/tests/oracle.patch @@ -0,0 +1,37 @@ +diff --git a/libs/spurs/cellSpurs.c b/libs/spurs/cellSpurs.c +index 82ea66c6..57302177 100644 +--- a/libs/spurs/cellSpurs.c ++++ b/libs/spurs/cellSpurs.c +@@ -934,7 +934,7 @@ s32 cellSpursCreateTasksetWithAttribute(CellSpurs* spurs, + const CellSpursTasksetAttribute* attr_h = GUEST_PTR(attr, const CellSpursTasksetAttribute*); + u32 size = attr_h->tasksetSize; + if (size != 0x1900u && size != 0x2900u) return (s32)0x80410902u; +- return spurs_create_taskset(spurs, taskset, 0, NULL, 0, size); ++ return spurs_create_taskset(spurs, taskset, attr_h->args, NULL, 0, size); + } + + s32 cellSpursDestroyTaskset(CellSpursTaskset* taskset) +@@ -1286,17 +1286,20 @@ s32 cellSpursCreateTaskWithAttribute(CellSpursTaskset* taskset, + attr_h->lsPattern_ea, attr_h->argument_ea); + } + +-/* The SDK's versioned taskset-attribute initializer. We forward taskset creation +- * through CreateTaskset (which ignores the attribute), so just zero the struct. */ ++/* The SDK's versioned taskset-attribute initializer. Only argTaskset and the ++ * size are carried to creation: the taskset argument reaches every task in r4, ++ * and a task that reads its setup through it (MLB The Show 16's Bink task DMAs ++ * its event flag address from there) otherwise gets 0. */ + s32 _cellSpursTasksetAttributeInitialize(CellSpursTasksetAttribute* attr, + u32 revision, u32 sdkVersion, u64 argTaskset, + u64 priority, u32 maxContention) + { +- (void)sdkVersion; (void)argTaskset; (void)priority; (void)maxContention; ++ (void)sdkVersion; (void)priority; (void)maxContention; + if (!attr) return CELL_SPURS_TASK_ERROR_NULL_POINTER; + attr = GUEST_PTR(attr, CellSpursTasksetAttribute*); + memset(attr, 0, sizeof(CellSpursTasksetAttribute)); + attr->revision = revision ? revision : 1; ++ attr->args = argTaskset; + attr->tasksetSize = CSTS_STRUCT_END; + printf("[cellSpurs] _TasksetAttributeInitialize(rev=%u)\n", revision); + return CELL_OK; diff --git a/tasks/sp00nznet__ps3recomp-643/tests/test.sh b/tasks/sp00nznet__ps3recomp-643/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-643/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-643/tests/verifier.py b/tasks/sp00nznet__ps3recomp-643/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-643/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-644/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-644/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-644/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-644/instruction.md b/tasks/sp00nznet__ps3recomp-644/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2167224ea0c962d6feee45bea7ef3b3a6910d6d6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-644/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** sys_memory: fix sys_memory_container_get_size semantics and register syscall 350 + +## Description + +## Why +In `runtime/syscalls/sys_memory.c`, several discrepancies existed in the memory container implementation relative to real PS3 LV2 kernel behavior: +1. **Argument order in `sys_memory_container_get_size`**: The kernel signature is `sys_memory_container_get_size(sys_memory_info_t* mem_info, sys_memory_container_t id)`. The implementation expected `id` in `r3` and `out_addr` in `r4`, causing argument inversion. +2. **Output structure layout**: `sys_memory_info_t` holds `{ uint32_t total_user_memory; uint32_t available_user_memory; }`. The implementation previously stored `used_size` rather than `total - used`. +3. **Default container query**: `SYS_MEMORY_CONTAINER_ID_INVALID` (`0xFFFFFFFF`) represents the process's default container. Querying it previously returned `CELL_ESRCH`. Titles routinely query the default container to calculate available memory and carve out custom sub-containers. +4. **Missing `sys_memory_allocate_from_container` (syscall 350)**: Titles allocating memory pools inside carved containers hit unhandled syscall fallthrough. + +In *MLB The Show 16* (and related engine games like *MLB 15* in #551), the engine carves custom memory containers out of the default container for its animation and movie pools (`SharedMemContAnim`, `SharedMemContMovie`). Due to these issues, container creation and allocation failed, leaving buffer pools empty and triggering crashes on subsequent NULL-buffer method calls during match loading. + +## What changed +- In `runtime/syscalls/sys_memory.c` and `sys_memory.h`: + - Adjusted `sys_memory_container_get_size` parameter order: `out_addr` in `r3`, `container_id` in `r4`. + - Added support for `SYS_MEMORY_CONTAINER_DEFAULT` (`0xFFFFFFFF`), returning total and available user memory. + - Calculated and wrote available size (`total_size - used_size`) to `out_addr + 4`. + - Implemented `sys_memory_allocate_from_container` (syscall 350), charging allocations against the container's quota and total user memory. + - Updated `sys_memory_free` to credit freed allocations back to their owning container. + - Registered `SYS_MEMORY_ALLOCATE_FROM_CONTAINER` in `sys_memory_init`. + +## Testing & Verification +- Tested in *MLB The Show 16*: container allocations (25 MB and 7 MB pools) succeed, eliminating NULL buffer crashes during game load. +- Builds and passes all runtime unit tests on macOS and Linux. +- Clean-room implementation per standard PS3 LV2 syscall ABI. + +Relates to #551. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-644/solution/patch.diff b/tasks/sp00nznet__ps3recomp-644/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..806583638cf36cdada75c2efd9481dab8e4462b5 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-644/solution/patch.diff @@ -0,0 +1,161 @@ +diff --git a/runtime/syscalls/sys_memory.c b/runtime/syscalls/sys_memory.c +index 66eef25c..9d112f64 100644 +--- a/runtime/syscalls/sys_memory.c ++++ b/runtime/syscalls/sys_memory.c +@@ -20,6 +20,7 @@ uint32_t g_sys_mem_bump_ptr = 0; + + /* Total user memory size (default 213 MB, after kernel reservation) */ + #define SYS_MEM_USER_TOTAL (213 * 1024 * 1024) ++#define SYS_MEMORY_CONTAINER_DEFAULT 0xFFFFFFFFu /* SYS_MEMORY_CONTAINER_ID_INVALID: the default container */ + + /* LV2 user memory and mapper reservations occupy separate address domains. + * User allocations start above the executable region. Mapper addresses may +@@ -101,11 +102,11 @@ static uint32_t user_address(uint32_t size, uint32_t alignment) + } + } + +-int64_t sys_memory_allocate(ppu_context* ctx) ++/* sys_memory_allocate and sys_memory_allocate_from_container share this. cid 0 ++ * is the process's main pool; a container's allocations are also charged to ++ * that container (its used_size), checked against its total. */ ++static int64_t memory_allocate(uint64_t requested, uint32_t flags, uint32_t cid, uint32_t addr_out) + { +- uint64_t requested = LV2_ARG_U64(ctx, 0); +- uint32_t flags = LV2_ARG_U32(ctx, 1); +- uint32_t addr_out = LV2_ARG_PTR(ctx, 2); + uint32_t alignment = (flags & SYS_MEMORY_PAGE_SIZE_1M) ? 0x100000u : 0x10000u; + uint64_t rounded = (requested + alignment - 1u) & ~(uint64_t)(alignment - 1u); + if (!requested || requested > UINT32_MAX || !rounded || rounded > UINT32_MAX) +@@ -115,6 +116,13 @@ int64_t sys_memory_allocate(ppu_context* ctx) + if (size > SYS_MEM_USER_TOTAL - s_total_allocated) { + bump_unlock(); return (int64_t)(int32_t)CELL_ENOMEM; + } ++ sys_mem_container_info* ct = NULL; ++ if (cid) { ++ ct = &g_sys_mem_containers[cid - 1]; ++ if (size > ct->total_size - ct->used_size) { ++ bump_unlock(); return (int64_t)(int32_t)CELL_ENOMEM; ++ } ++ } + int slot = -1; + for (int i = 0; i < SYS_MEMORY_ALLOC_MAX; ++i) + if (!g_sys_mem_allocs[i].active) { slot = i; break; } +@@ -125,15 +133,41 @@ int64_t sys_memory_allocate(ppu_context* ctx) + memset(vm_to_host(addr), 0, size); + sys_mem_alloc_info* a = &g_sys_mem_allocs[slot]; + a->active = 1; a->addr = addr; a->size = size; +- a->container_id = 0; a->page_size = alignment; ++ a->container_id = (int32_t)cid; a->page_size = alignment; + s_total_allocated += size; ++ if (ct) ct->used_size += size; + if (addr + size > g_sys_mem_bump_ptr) g_sys_mem_bump_ptr = addr + size; + bump_unlock(); +- fprintf(stderr, "[sys_memory] allocate(size=0x%X, flags=0x%X) -> 0x%08X\n", size, flags, addr); ++ fprintf(stderr, "[sys_memory] allocate(size=0x%X, flags=0x%X, cid=%u) -> 0x%08X\n", size, flags, cid, addr); + if (addr_out) write_be32(addr_out, addr); + return CELL_OK; + } + ++int64_t sys_memory_allocate(ppu_context* ctx) ++{ ++ return memory_allocate(LV2_ARG_U64(ctx, 0), LV2_ARG_U32(ctx, 1), 0, LV2_ARG_PTR(ctx, 2)); ++} ++ ++/* --------------------------------------------------------------------------- ++ * sys_memory_allocate_from_container (syscall 350) ++ * ++ * r3 = size, r4 = container id, r5 = flags, r6 = pointer to receive the address ++ * ++ * Was unregistered. MLB The Show 16 builds its animation and movie buffer pools ++ * ("SharedMemContAnim", "SharedMemContMovie") in containers carved from the ++ * default one; with no allocation the pool stayed empty and loading a match ++ * called a method on a NULL buffer. ++ * -----------------------------------------------------------------------*/ ++int64_t sys_memory_allocate_from_container(ppu_context* ctx) ++{ ++ uint32_t cid = LV2_ARG_U32(ctx, 1); ++ if (cid == SYS_MEMORY_CONTAINER_DEFAULT) ++ return memory_allocate(LV2_ARG_U64(ctx, 0), LV2_ARG_U32(ctx, 2), 0, LV2_ARG_PTR(ctx, 3)); ++ if (cid == 0 || cid > SYS_MEMORY_CONTAINER_MAX || !g_sys_mem_containers[cid - 1].active) ++ return (int64_t)(int32_t)CELL_ESRCH; ++ return memory_allocate(LV2_ARG_U64(ctx, 0), LV2_ARG_U32(ctx, 2), cid, LV2_ARG_PTR(ctx, 3)); ++} ++ + /* --------------------------------------------------------------------------- + * sys_memory_free + * +@@ -146,6 +180,9 @@ int64_t sys_memory_free(ppu_context* ctx) + for (int i = 0; i < SYS_MEMORY_ALLOC_MAX; i++) { + if (g_sys_mem_allocs[i].active && g_sys_mem_allocs[i].addr == addr) { + s_total_allocated -= g_sys_mem_allocs[i].size; ++ const int32_t cid = g_sys_mem_allocs[i].container_id; ++ if (cid > 0 && cid <= SYS_MEMORY_CONTAINER_MAX && g_sys_mem_containers[cid - 1].active) ++ g_sys_mem_containers[cid - 1].used_size -= g_sys_mem_allocs[i].size; + g_sys_mem_allocs[i].active = 0; + bump_unlock(); return CELL_OK; + } +@@ -271,14 +308,30 @@ int64_t sys_memory_container_destroy(ppu_context* ctx) + /* --------------------------------------------------------------------------- + * sys_memory_container_get_size + * +- * r3 = container_id +- * r4 = pointer to output struct: { u32 total, u32 used } ++ * r3 = pointer to output struct: sys_memory_info_t { u32 total, u32 available } ++ * r4 = container_id; SYS_MEMORY_CONTAINER_ID_INVALID (0xFFFFFFFF) means the ++ * process's default container, i.e. the title's own user memory. ++ * ++ * The argument order and the second field were both wrong: the game passes the ++ * struct first, and the second word is what is still free, not what is used. A ++ * title carving a container out of the default one ("get the size, destroy, ++ * recreate smaller, create mine") got ESRCH, then a container id of 0. + * -----------------------------------------------------------------------*/ + int64_t sys_memory_container_get_size(ppu_context* ctx) + { +- uint32_t container_id = LV2_ARG_U32(ctx, 0); +- uint32_t out_addr = LV2_ARG_PTR(ctx, 1); +- ++ uint32_t out_addr = LV2_ARG_PTR(ctx, 0); ++ uint32_t container_id = LV2_ARG_U32(ctx, 1); ++ ++ if (container_id == SYS_MEMORY_CONTAINER_DEFAULT) { ++ if (out_addr != 0) { ++ bump_lock(); ++ const uint32_t avail = SYS_MEM_USER_TOTAL - s_total_allocated; ++ bump_unlock(); ++ write_be32(out_addr + 0, SYS_MEM_USER_TOTAL); ++ write_be32(out_addr + 4, avail); ++ } ++ return CELL_OK; ++ } + if (container_id == 0 || container_id > SYS_MEMORY_CONTAINER_MAX) + return (int64_t)(int32_t)CELL_ESRCH; + +@@ -288,7 +341,7 @@ int64_t sys_memory_container_get_size(ppu_context* ctx) + + if (out_addr != 0) { + write_be32(out_addr + 0, c->total_size); +- write_be32(out_addr + 4, c->used_size); ++ write_be32(out_addr + 4, c->total_size - c->used_size); + } + + return CELL_OK; +@@ -544,6 +597,7 @@ void sys_memory_init(lv2_syscall_table* tbl) + lv2_syscall_register(tbl, SYS_MEMORY_CONTAINER_CREATE, sys_memory_container_create); + lv2_syscall_register(tbl, SYS_MEMORY_CONTAINER_DESTROY, sys_memory_container_destroy); + lv2_syscall_register(tbl, SYS_MEMORY_CONTAINER_GET_SIZE, sys_memory_container_get_size); ++ lv2_syscall_register(tbl, SYS_MEMORY_ALLOCATE_FROM_CONTAINER, sys_memory_allocate_from_container); + lv2_syscall_register(tbl, SYS_MMAPPER_ALLOCATE_ADDRESS, sys_mmapper_allocate_address); + lv2_syscall_register(tbl, SYS_MMAPPER_FREE_ADDRESS, sys_mmapper_free_address); + lv2_syscall_register(tbl, SYS_MMAPPER_ALLOCATE_SHARED_MEMORY, sys_mmapper_allocate_shared_memory); +diff --git a/runtime/syscalls/sys_memory.h b/runtime/syscalls/sys_memory.h +index a20806ad..f394a033 100644 +--- a/runtime/syscalls/sys_memory.h ++++ b/runtime/syscalls/sys_memory.h +@@ -63,6 +63,7 @@ int64_t sys_memory_get_page_attribute(ppu_context* ctx); + int64_t sys_memory_container_create(ppu_context* ctx); + int64_t sys_memory_container_destroy(ppu_context* ctx); + int64_t sys_memory_container_get_size(ppu_context* ctx); ++int64_t sys_memory_allocate_from_container(ppu_context* ctx); + int64_t sys_mmapper_allocate_address(ppu_context* ctx); + int64_t sys_mmapper_search_map_address(uint32_t start, uint32_t size, uint32_t* out); + int64_t sys_mmapper_free_address(ppu_context* ctx); diff --git a/tasks/sp00nznet__ps3recomp-644/solution/solve.sh b/tasks/sp00nznet__ps3recomp-644/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-644/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-644/task.toml b/tasks/sp00nznet__ps3recomp-644/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5143583f756d5c14bc4dadcece1fff07c3435810 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-644/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-644" +description = "sys_memory: fix sys_memory_container_get_size semantics and register syscall 350" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/644" +source_access = "auto" +built_at = "2026-11-16T16:09:59.653379+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e941f5c79f49e985b6e5e115d5e93738e01d264dcd52a31608b67bffe96e0f09" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "runtime/syscalls/sys_memory.c", + "runtime/syscalls/sys_memory.h", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 79 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.143104+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-644/tests/capture.py b/tasks/sp00nznet__ps3recomp-644/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-644/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-644/tests/instruction.md b/tasks/sp00nznet__ps3recomp-644/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2167224ea0c962d6feee45bea7ef3b3a6910d6d6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-644/tests/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** sys_memory: fix sys_memory_container_get_size semantics and register syscall 350 + +## Description + +## Why +In `runtime/syscalls/sys_memory.c`, several discrepancies existed in the memory container implementation relative to real PS3 LV2 kernel behavior: +1. **Argument order in `sys_memory_container_get_size`**: The kernel signature is `sys_memory_container_get_size(sys_memory_info_t* mem_info, sys_memory_container_t id)`. The implementation expected `id` in `r3` and `out_addr` in `r4`, causing argument inversion. +2. **Output structure layout**: `sys_memory_info_t` holds `{ uint32_t total_user_memory; uint32_t available_user_memory; }`. The implementation previously stored `used_size` rather than `total - used`. +3. **Default container query**: `SYS_MEMORY_CONTAINER_ID_INVALID` (`0xFFFFFFFF`) represents the process's default container. Querying it previously returned `CELL_ESRCH`. Titles routinely query the default container to calculate available memory and carve out custom sub-containers. +4. **Missing `sys_memory_allocate_from_container` (syscall 350)**: Titles allocating memory pools inside carved containers hit unhandled syscall fallthrough. + +In *MLB The Show 16* (and related engine games like *MLB 15* in #551), the engine carves custom memory containers out of the default container for its animation and movie pools (`SharedMemContAnim`, `SharedMemContMovie`). Due to these issues, container creation and allocation failed, leaving buffer pools empty and triggering crashes on subsequent NULL-buffer method calls during match loading. + +## What changed +- In `runtime/syscalls/sys_memory.c` and `sys_memory.h`: + - Adjusted `sys_memory_container_get_size` parameter order: `out_addr` in `r3`, `container_id` in `r4`. + - Added support for `SYS_MEMORY_CONTAINER_DEFAULT` (`0xFFFFFFFF`), returning total and available user memory. + - Calculated and wrote available size (`total_size - used_size`) to `out_addr + 4`. + - Implemented `sys_memory_allocate_from_container` (syscall 350), charging allocations against the container's quota and total user memory. + - Updated `sys_memory_free` to credit freed allocations back to their owning container. + - Registered `SYS_MEMORY_ALLOCATE_FROM_CONTAINER` in `sys_memory_init`. + +## Testing & Verification +- Tested in *MLB The Show 16*: container allocations (25 MB and 7 MB pools) succeed, eliminating NULL buffer crashes during game load. +- Builds and passes all runtime unit tests on macOS and Linux. +- Clean-room implementation per standard PS3 LV2 syscall ABI. + +Relates to #551. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-644/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-644/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..806583638cf36cdada75c2efd9481dab8e4462b5 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-644/tests/oracle.patch @@ -0,0 +1,161 @@ +diff --git a/runtime/syscalls/sys_memory.c b/runtime/syscalls/sys_memory.c +index 66eef25c..9d112f64 100644 +--- a/runtime/syscalls/sys_memory.c ++++ b/runtime/syscalls/sys_memory.c +@@ -20,6 +20,7 @@ uint32_t g_sys_mem_bump_ptr = 0; + + /* Total user memory size (default 213 MB, after kernel reservation) */ + #define SYS_MEM_USER_TOTAL (213 * 1024 * 1024) ++#define SYS_MEMORY_CONTAINER_DEFAULT 0xFFFFFFFFu /* SYS_MEMORY_CONTAINER_ID_INVALID: the default container */ + + /* LV2 user memory and mapper reservations occupy separate address domains. + * User allocations start above the executable region. Mapper addresses may +@@ -101,11 +102,11 @@ static uint32_t user_address(uint32_t size, uint32_t alignment) + } + } + +-int64_t sys_memory_allocate(ppu_context* ctx) ++/* sys_memory_allocate and sys_memory_allocate_from_container share this. cid 0 ++ * is the process's main pool; a container's allocations are also charged to ++ * that container (its used_size), checked against its total. */ ++static int64_t memory_allocate(uint64_t requested, uint32_t flags, uint32_t cid, uint32_t addr_out) + { +- uint64_t requested = LV2_ARG_U64(ctx, 0); +- uint32_t flags = LV2_ARG_U32(ctx, 1); +- uint32_t addr_out = LV2_ARG_PTR(ctx, 2); + uint32_t alignment = (flags & SYS_MEMORY_PAGE_SIZE_1M) ? 0x100000u : 0x10000u; + uint64_t rounded = (requested + alignment - 1u) & ~(uint64_t)(alignment - 1u); + if (!requested || requested > UINT32_MAX || !rounded || rounded > UINT32_MAX) +@@ -115,6 +116,13 @@ int64_t sys_memory_allocate(ppu_context* ctx) + if (size > SYS_MEM_USER_TOTAL - s_total_allocated) { + bump_unlock(); return (int64_t)(int32_t)CELL_ENOMEM; + } ++ sys_mem_container_info* ct = NULL; ++ if (cid) { ++ ct = &g_sys_mem_containers[cid - 1]; ++ if (size > ct->total_size - ct->used_size) { ++ bump_unlock(); return (int64_t)(int32_t)CELL_ENOMEM; ++ } ++ } + int slot = -1; + for (int i = 0; i < SYS_MEMORY_ALLOC_MAX; ++i) + if (!g_sys_mem_allocs[i].active) { slot = i; break; } +@@ -125,15 +133,41 @@ int64_t sys_memory_allocate(ppu_context* ctx) + memset(vm_to_host(addr), 0, size); + sys_mem_alloc_info* a = &g_sys_mem_allocs[slot]; + a->active = 1; a->addr = addr; a->size = size; +- a->container_id = 0; a->page_size = alignment; ++ a->container_id = (int32_t)cid; a->page_size = alignment; + s_total_allocated += size; ++ if (ct) ct->used_size += size; + if (addr + size > g_sys_mem_bump_ptr) g_sys_mem_bump_ptr = addr + size; + bump_unlock(); +- fprintf(stderr, "[sys_memory] allocate(size=0x%X, flags=0x%X) -> 0x%08X\n", size, flags, addr); ++ fprintf(stderr, "[sys_memory] allocate(size=0x%X, flags=0x%X, cid=%u) -> 0x%08X\n", size, flags, cid, addr); + if (addr_out) write_be32(addr_out, addr); + return CELL_OK; + } + ++int64_t sys_memory_allocate(ppu_context* ctx) ++{ ++ return memory_allocate(LV2_ARG_U64(ctx, 0), LV2_ARG_U32(ctx, 1), 0, LV2_ARG_PTR(ctx, 2)); ++} ++ ++/* --------------------------------------------------------------------------- ++ * sys_memory_allocate_from_container (syscall 350) ++ * ++ * r3 = size, r4 = container id, r5 = flags, r6 = pointer to receive the address ++ * ++ * Was unregistered. MLB The Show 16 builds its animation and movie buffer pools ++ * ("SharedMemContAnim", "SharedMemContMovie") in containers carved from the ++ * default one; with no allocation the pool stayed empty and loading a match ++ * called a method on a NULL buffer. ++ * -----------------------------------------------------------------------*/ ++int64_t sys_memory_allocate_from_container(ppu_context* ctx) ++{ ++ uint32_t cid = LV2_ARG_U32(ctx, 1); ++ if (cid == SYS_MEMORY_CONTAINER_DEFAULT) ++ return memory_allocate(LV2_ARG_U64(ctx, 0), LV2_ARG_U32(ctx, 2), 0, LV2_ARG_PTR(ctx, 3)); ++ if (cid == 0 || cid > SYS_MEMORY_CONTAINER_MAX || !g_sys_mem_containers[cid - 1].active) ++ return (int64_t)(int32_t)CELL_ESRCH; ++ return memory_allocate(LV2_ARG_U64(ctx, 0), LV2_ARG_U32(ctx, 2), cid, LV2_ARG_PTR(ctx, 3)); ++} ++ + /* --------------------------------------------------------------------------- + * sys_memory_free + * +@@ -146,6 +180,9 @@ int64_t sys_memory_free(ppu_context* ctx) + for (int i = 0; i < SYS_MEMORY_ALLOC_MAX; i++) { + if (g_sys_mem_allocs[i].active && g_sys_mem_allocs[i].addr == addr) { + s_total_allocated -= g_sys_mem_allocs[i].size; ++ const int32_t cid = g_sys_mem_allocs[i].container_id; ++ if (cid > 0 && cid <= SYS_MEMORY_CONTAINER_MAX && g_sys_mem_containers[cid - 1].active) ++ g_sys_mem_containers[cid - 1].used_size -= g_sys_mem_allocs[i].size; + g_sys_mem_allocs[i].active = 0; + bump_unlock(); return CELL_OK; + } +@@ -271,14 +308,30 @@ int64_t sys_memory_container_destroy(ppu_context* ctx) + /* --------------------------------------------------------------------------- + * sys_memory_container_get_size + * +- * r3 = container_id +- * r4 = pointer to output struct: { u32 total, u32 used } ++ * r3 = pointer to output struct: sys_memory_info_t { u32 total, u32 available } ++ * r4 = container_id; SYS_MEMORY_CONTAINER_ID_INVALID (0xFFFFFFFF) means the ++ * process's default container, i.e. the title's own user memory. ++ * ++ * The argument order and the second field were both wrong: the game passes the ++ * struct first, and the second word is what is still free, not what is used. A ++ * title carving a container out of the default one ("get the size, destroy, ++ * recreate smaller, create mine") got ESRCH, then a container id of 0. + * -----------------------------------------------------------------------*/ + int64_t sys_memory_container_get_size(ppu_context* ctx) + { +- uint32_t container_id = LV2_ARG_U32(ctx, 0); +- uint32_t out_addr = LV2_ARG_PTR(ctx, 1); +- ++ uint32_t out_addr = LV2_ARG_PTR(ctx, 0); ++ uint32_t container_id = LV2_ARG_U32(ctx, 1); ++ ++ if (container_id == SYS_MEMORY_CONTAINER_DEFAULT) { ++ if (out_addr != 0) { ++ bump_lock(); ++ const uint32_t avail = SYS_MEM_USER_TOTAL - s_total_allocated; ++ bump_unlock(); ++ write_be32(out_addr + 0, SYS_MEM_USER_TOTAL); ++ write_be32(out_addr + 4, avail); ++ } ++ return CELL_OK; ++ } + if (container_id == 0 || container_id > SYS_MEMORY_CONTAINER_MAX) + return (int64_t)(int32_t)CELL_ESRCH; + +@@ -288,7 +341,7 @@ int64_t sys_memory_container_get_size(ppu_context* ctx) + + if (out_addr != 0) { + write_be32(out_addr + 0, c->total_size); +- write_be32(out_addr + 4, c->used_size); ++ write_be32(out_addr + 4, c->total_size - c->used_size); + } + + return CELL_OK; +@@ -544,6 +597,7 @@ void sys_memory_init(lv2_syscall_table* tbl) + lv2_syscall_register(tbl, SYS_MEMORY_CONTAINER_CREATE, sys_memory_container_create); + lv2_syscall_register(tbl, SYS_MEMORY_CONTAINER_DESTROY, sys_memory_container_destroy); + lv2_syscall_register(tbl, SYS_MEMORY_CONTAINER_GET_SIZE, sys_memory_container_get_size); ++ lv2_syscall_register(tbl, SYS_MEMORY_ALLOCATE_FROM_CONTAINER, sys_memory_allocate_from_container); + lv2_syscall_register(tbl, SYS_MMAPPER_ALLOCATE_ADDRESS, sys_mmapper_allocate_address); + lv2_syscall_register(tbl, SYS_MMAPPER_FREE_ADDRESS, sys_mmapper_free_address); + lv2_syscall_register(tbl, SYS_MMAPPER_ALLOCATE_SHARED_MEMORY, sys_mmapper_allocate_shared_memory); +diff --git a/runtime/syscalls/sys_memory.h b/runtime/syscalls/sys_memory.h +index a20806ad..f394a033 100644 +--- a/runtime/syscalls/sys_memory.h ++++ b/runtime/syscalls/sys_memory.h +@@ -63,6 +63,7 @@ int64_t sys_memory_get_page_attribute(ppu_context* ctx); + int64_t sys_memory_container_create(ppu_context* ctx); + int64_t sys_memory_container_destroy(ppu_context* ctx); + int64_t sys_memory_container_get_size(ppu_context* ctx); ++int64_t sys_memory_allocate_from_container(ppu_context* ctx); + int64_t sys_mmapper_allocate_address(ppu_context* ctx); + int64_t sys_mmapper_search_map_address(uint32_t start, uint32_t size, uint32_t* out); + int64_t sys_mmapper_free_address(ppu_context* ctx); diff --git a/tasks/sp00nznet__ps3recomp-644/tests/test.sh b/tasks/sp00nznet__ps3recomp-644/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-644/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-644/tests/verifier.py b/tasks/sp00nznet__ps3recomp-644/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-644/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-645/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-645/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-645/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-645/instruction.md b/tasks/sp00nznet__ps3recomp-645/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..167b51ee335dba1814765cb46856a09e20605e10 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-645/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** cellFs: implement cellFsFtruncate on the active fd table + +## Description + +## Why +`cellFsFtruncate` (NID `0x0E2939E5`) was previously handled by `libs/filesystem/cellFs.c`, which maintains an internal file descriptor table independent of `runtime/ppu/ppu_fs.cpp`. Because active guest file descriptors are opened via `cellFsOpen` in `ppu_fs.cpp` (managed via `fd_file()`), any call to `cellFsFtruncate` failed with `CELL_FS_EBADF`, leaving file sizes unmodified. + +In *MLB The Show 16* (BCUS01089) as well as *MLB 15 The Show* (), the game pre-allocates and resizes its player head/face cache (`HeadFaceCacheFile`, ~300 MB) and arena logo cache (~9 MB) using `cellFsFtruncate` prior to loading an exhibition game. Failing with EBADF prevented the files from acquiring their expected geometry, leading to downstream read/write errors. + +## What changed +- In `runtime/ppu/ppu_fs.cpp`: + - Added `cellFsFtruncate` operating directly on the active file table via `fd_file()`. + - Dispatches to `_chsize_s` on Windows and `ftruncate` on POSIX platforms. + - Registered `ps3_compute_nid("cellFsFtruncate")` in `ppu_fs_register()`. + +## Testing & Verification +- Tested in *MLB The Show 16*: cache files resize to their requested dimensions without error, returning `CELL_OK`. +- Builds and passes CI tests on macOS and Linux. +- Clean-room implementation per standard PS3 SDK `cellFsFtruncate` specification. + +Relates to #551. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-645/solution/patch.diff b/tasks/sp00nznet__ps3recomp-645/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..769541224bdd5e3c1e86f390cdb49f9a156ca4b0 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-645/solution/patch.diff @@ -0,0 +1,43 @@ +diff --git a/runtime/ppu/ppu_fs.cpp b/runtime/ppu/ppu_fs.cpp +index f73907c2..e9edfe8e 100644 +--- a/runtime/ppu/ppu_fs.cpp ++++ b/runtime/ppu/ppu_fs.cpp +@@ -89,6 +89,7 @@ extern "C" const char* ppu_vfs_root = "."; + #define CELL_FS_EISDIR (-2147418094) /* 0x80010012 */ + #define CELL_FS_EIO (-2147418111) + #define CELL_FS_ENOSYS (-2147418109) /* 0x80010003 */ ++#define CELL_FS_EBADF (-2147418070) /* 0x8001002A */ + #define CELL_FS_S_IFDIR 0x4000u + #define CELL_FS_S_IFREG 0x8000u + #define CELL_FS_O_RDONLY 0 +@@ -861,6 +862,22 @@ static void cellFsFsync(ppu_context* ctx) + if (FILE* f = fd_file(fd)) fflush(f); + ctx->gpr[3] = CELL_OK; + } ++/* (fd, u64 size). The libs/filesystem version looks fds up in its own table, ++ * which cellFsOpen here never fills, so it always returned EBADF. */ ++static void cellFsFtruncate(ppu_context* ctx) ++{ ++ FILE* f = fd_file((int)(uint32_t)ctx->gpr[3]); ++ if (!f) { ctx->gpr[3] = (uint64_t)(int64_t)CELL_FS_EBADF; return; } ++ fflush(f); ++#ifdef _WIN32 ++ int rc = _chsize_s(_fileno(f), (long long)ctx->gpr[4]); ++#else ++ int rc = ftruncate(fileno(f), (off_t)ctx->gpr[4]); ++#endif ++ if (getenv("PS3_FSLOG")) fprintf(stderr, "[FSDBG] cellFsFtruncate(fd=%d, size=0x%llX) -> %d\n", ++ (int)(uint32_t)ctx->gpr[3], (unsigned long long)ctx->gpr[4], rc); ++ ctx->gpr[3] = rc == 0 ? CELL_OK : (uint64_t)(int64_t)CELL_FS_EIO; ++} + /* File-area preallocation (LBP cache warm-up spams this): host filesystems + * grow files on write, so accepting is correct -- no preallocation needed. */ + static void cellFsAllocateFileAreaWithoutZeroFill(ppu_context* ctx) { ctx->gpr[3] = CELL_OK; } +@@ -1001,6 +1018,7 @@ extern "C" void ppu_fs_register(void) + ps3_hle_register_ctx(ps3_compute_nid("cellFsRmdir"), "cellFsRmdir", cellFsRmdir); + ps3_hle_register_ctx(ps3_compute_nid("cellFsUnlink"), "cellFsUnlink", cellFsUnlink); + ps3_hle_register_ctx(ps3_compute_nid("cellFsFsync"), "cellFsFsync", cellFsFsync); ++ ps3_hle_register_ctx(ps3_compute_nid("cellFsFtruncate"), "cellFsFtruncate", cellFsFtruncate); + ps3_hle_register_ctx(ps3_compute_nid("cellFsGetFreeSize"), "cellFsGetFreeSize", cellFsGetFreeSize); + ps3_hle_register_ctx(ps3_compute_nid("cellFsChmod"), "cellFsChmod", cellFsChmod); + ps3_hle_register_ctx(ps3_compute_nid("cellFsUtime"), "cellFsUtime", cellFsUtime); diff --git a/tasks/sp00nznet__ps3recomp-645/solution/solve.sh b/tasks/sp00nznet__ps3recomp-645/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-645/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-645/task.toml b/tasks/sp00nznet__ps3recomp-645/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7709063cf6845c37786836f16efcfd14cb53ce87 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-645/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-645" +description = "cellFs: implement cellFsFtruncate on the active fd table" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/645" +source_access = "auto" +built_at = "2026-11-16T16:09:59.651693+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f16c6d0f3b50a372ca69b9937a5112593033e2e8ebbbb781ef616fcb482f7968" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "runtime/ppu/ppu_fs.cpp", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 18 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.143648+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-645/tests/capture.py b/tasks/sp00nznet__ps3recomp-645/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-645/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-645/tests/instruction.md b/tasks/sp00nznet__ps3recomp-645/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..167b51ee335dba1814765cb46856a09e20605e10 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-645/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** cellFs: implement cellFsFtruncate on the active fd table + +## Description + +## Why +`cellFsFtruncate` (NID `0x0E2939E5`) was previously handled by `libs/filesystem/cellFs.c`, which maintains an internal file descriptor table independent of `runtime/ppu/ppu_fs.cpp`. Because active guest file descriptors are opened via `cellFsOpen` in `ppu_fs.cpp` (managed via `fd_file()`), any call to `cellFsFtruncate` failed with `CELL_FS_EBADF`, leaving file sizes unmodified. + +In *MLB The Show 16* (BCUS01089) as well as *MLB 15 The Show* (), the game pre-allocates and resizes its player head/face cache (`HeadFaceCacheFile`, ~300 MB) and arena logo cache (~9 MB) using `cellFsFtruncate` prior to loading an exhibition game. Failing with EBADF prevented the files from acquiring their expected geometry, leading to downstream read/write errors. + +## What changed +- In `runtime/ppu/ppu_fs.cpp`: + - Added `cellFsFtruncate` operating directly on the active file table via `fd_file()`. + - Dispatches to `_chsize_s` on Windows and `ftruncate` on POSIX platforms. + - Registered `ps3_compute_nid("cellFsFtruncate")` in `ppu_fs_register()`. + +## Testing & Verification +- Tested in *MLB The Show 16*: cache files resize to their requested dimensions without error, returning `CELL_OK`. +- Builds and passes CI tests on macOS and Linux. +- Clean-room implementation per standard PS3 SDK `cellFsFtruncate` specification. + +Relates to #551. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-645/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-645/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..769541224bdd5e3c1e86f390cdb49f9a156ca4b0 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-645/tests/oracle.patch @@ -0,0 +1,43 @@ +diff --git a/runtime/ppu/ppu_fs.cpp b/runtime/ppu/ppu_fs.cpp +index f73907c2..e9edfe8e 100644 +--- a/runtime/ppu/ppu_fs.cpp ++++ b/runtime/ppu/ppu_fs.cpp +@@ -89,6 +89,7 @@ extern "C" const char* ppu_vfs_root = "."; + #define CELL_FS_EISDIR (-2147418094) /* 0x80010012 */ + #define CELL_FS_EIO (-2147418111) + #define CELL_FS_ENOSYS (-2147418109) /* 0x80010003 */ ++#define CELL_FS_EBADF (-2147418070) /* 0x8001002A */ + #define CELL_FS_S_IFDIR 0x4000u + #define CELL_FS_S_IFREG 0x8000u + #define CELL_FS_O_RDONLY 0 +@@ -861,6 +862,22 @@ static void cellFsFsync(ppu_context* ctx) + if (FILE* f = fd_file(fd)) fflush(f); + ctx->gpr[3] = CELL_OK; + } ++/* (fd, u64 size). The libs/filesystem version looks fds up in its own table, ++ * which cellFsOpen here never fills, so it always returned EBADF. */ ++static void cellFsFtruncate(ppu_context* ctx) ++{ ++ FILE* f = fd_file((int)(uint32_t)ctx->gpr[3]); ++ if (!f) { ctx->gpr[3] = (uint64_t)(int64_t)CELL_FS_EBADF; return; } ++ fflush(f); ++#ifdef _WIN32 ++ int rc = _chsize_s(_fileno(f), (long long)ctx->gpr[4]); ++#else ++ int rc = ftruncate(fileno(f), (off_t)ctx->gpr[4]); ++#endif ++ if (getenv("PS3_FSLOG")) fprintf(stderr, "[FSDBG] cellFsFtruncate(fd=%d, size=0x%llX) -> %d\n", ++ (int)(uint32_t)ctx->gpr[3], (unsigned long long)ctx->gpr[4], rc); ++ ctx->gpr[3] = rc == 0 ? CELL_OK : (uint64_t)(int64_t)CELL_FS_EIO; ++} + /* File-area preallocation (LBP cache warm-up spams this): host filesystems + * grow files on write, so accepting is correct -- no preallocation needed. */ + static void cellFsAllocateFileAreaWithoutZeroFill(ppu_context* ctx) { ctx->gpr[3] = CELL_OK; } +@@ -1001,6 +1018,7 @@ extern "C" void ppu_fs_register(void) + ps3_hle_register_ctx(ps3_compute_nid("cellFsRmdir"), "cellFsRmdir", cellFsRmdir); + ps3_hle_register_ctx(ps3_compute_nid("cellFsUnlink"), "cellFsUnlink", cellFsUnlink); + ps3_hle_register_ctx(ps3_compute_nid("cellFsFsync"), "cellFsFsync", cellFsFsync); ++ ps3_hle_register_ctx(ps3_compute_nid("cellFsFtruncate"), "cellFsFtruncate", cellFsFtruncate); + ps3_hle_register_ctx(ps3_compute_nid("cellFsGetFreeSize"), "cellFsGetFreeSize", cellFsGetFreeSize); + ps3_hle_register_ctx(ps3_compute_nid("cellFsChmod"), "cellFsChmod", cellFsChmod); + ps3_hle_register_ctx(ps3_compute_nid("cellFsUtime"), "cellFsUtime", cellFsUtime); diff --git a/tasks/sp00nznet__ps3recomp-645/tests/test.sh b/tasks/sp00nznet__ps3recomp-645/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-645/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-645/tests/verifier.py b/tasks/sp00nznet__ps3recomp-645/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-645/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-647/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-647/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-647/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-647/instruction.md b/tasks/sp00nznet__ps3recomp-647/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f55701b358f61ed69ee57ef8ba1502aaa4200514 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-647/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** cellGcmSys: opt-in dedicated thread for handler delivery (GCM_HANDLER_THREAD=1) + +## Description + +## Why +In `libs/video/cellGcmSys.c`, `ppu_gcm_pump` delivers pending vblank/flip and user handlers on whatever guest thread happens to execute an HLE call or wait pump. When invoking the callback, `ppu_guest_call` passes the calling thread's own thread ID. + +If the guest thread already holds a game-engine lock that the handler also attempts to acquire, the handler sees the matching thread ID and re-enters the lock. When the handler unlocks and clears the owner record, the original thread's subsequent unlock sees an unowned/zero lock record and fails or skips unlocking, permanently leaking the lock and deadlocking the engine. + +In *MLB The Show 16* (BCUS01089) and *MLB 15 The Show* (, item 4), lock wrappers record the owner's thread ID at `+0x8` alongside the `sys_lwmutex`. Delivering the flip handler inside the `DisplayFlip` thread caused this exact lock leak, freezing the display loop and stopping all subsequent vblank/flip callbacks. + +On a physical PS3, these handlers are dispatched asynchronously from GCM's interrupt thread rather than synchronously inside arbitrary guest threads. + +## What changed +- Added an opt-in mode behind `GCM_HANDLER_THREAD=1`: + - When enabled, `ppu_gcm_pump` spawns and routes delivery through a dedicated host worker thread (`gcm_intr_main`). + - Calls to `ppu_gcm_pump` from other threads simply ensure the interrupt thread is running and return immediately. + - Leaves default behavior unchanged when `GCM_HANDLER_THREAD` is unset or 0. + +## Testing & Verification +- Tested in *MLB The Show 16*: completely resolves random freezes on boot screens, allowing reliable progression past the intro sequence (verified across multiple consecutive runs). +- Opt-in behavior ensures zero regressions for existing titles that rely on synchronous in-thread delivery. +- Clean-room implementation, no proprietary code included. + +Addresses item 4 in #551. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-647/solution/patch.diff b/tasks/sp00nznet__ps3recomp-647/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b5c373104b243f973cf405eef28078615de54a64 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-647/solution/patch.diff @@ -0,0 +1,47 @@ +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..8c6874cd 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -838,8 +838,42 @@ void* ppu_gcm_wait_pump(void (**pump)(void)) + } + #endif + ++/* GCM_HANDLER_THREAD=1: deliver the guest's vblank/flip/user handlers only on a ++ * dedicated host thread, as the PS3 does on its GCM interrupt thread. Pumped at ++ * an HLE boundary, a handler runs nested in whatever guest thread made the call ++ * and inherits its thread id, so a handler taking a lock that thread already ++ * holds re-enters it instead of waiting. MLB The Show 16's lock wrappers record ++ * the owner id and unlock only for the recorded owner: its flip handler, ++ * delivered inside its DisplayFlip thread, cleared that record, DisplayFlip's ++ * own unlock was skipped and the lock leaked, freezing the game. */ ++void ppu_gcm_pump(void); ++static unsigned long s_gcm_intr_tid = 0; ++static int gcm_handler_thread_on(void) ++{ ++ static int v = -1; ++ if (v < 0) { const char* e = getenv("GCM_HANDLER_THREAD"); v = (e && *e && *e != '0') ? 1 : 0; } ++ return v; ++} ++static DWORD WINAPI gcm_intr_main(LPVOID unused) ++{ ++ (void)unused; ++ s_gcm_intr_tid = (unsigned long)GetCurrentThreadId(); ++#ifdef _WIN32 ++ for (;;) { ppu_gcm_pump(); Sleep(1); } ++#else ++ for (;;) { ppu_gcm_pump(); usleep(250); } ++#endif ++ return 0; ++} ++ + void ppu_gcm_pump(void) + { ++ if (gcm_handler_thread_on() && (unsigned long)GetCurrentThreadId() != s_gcm_intr_tid) { ++ static volatile long started = 0; ++ if (!started && InterlockedCompareExchange(&started, 1, 0) == 0) ++ CreateThread(NULL, 1u << 20, gcm_intr_main, NULL, 0, NULL); ++ return; /* only the interrupt thread delivers */ ++ } + if (!GCM_PUMP_TRY_ENTER()) return; + long p = (long)GCM_PENDING_TAKE(); + u64 user = GCM_USER_PENDING_TAKE(); diff --git a/tasks/sp00nznet__ps3recomp-647/solution/solve.sh b/tasks/sp00nznet__ps3recomp-647/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-647/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-647/task.toml b/tasks/sp00nznet__ps3recomp-647/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e7febe9ce9da60320598443f22080aaba3c0677f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-647/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-647" +description = "cellGcmSys: opt-in dedicated thread for handler delivery (GCM_HANDLER_THREAD=1)" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/647" +source_access = "auto" +built_at = "2026-11-16T16:09:59.650138+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d28a429a317f9d5b9c12f89843cdc3bf73c5d1b98955bd7a5a279fdf6cfb496c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/video/cellGcmSys.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 34 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.144170+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-647/tests/capture.py b/tasks/sp00nznet__ps3recomp-647/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-647/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-647/tests/instruction.md b/tasks/sp00nznet__ps3recomp-647/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f55701b358f61ed69ee57ef8ba1502aaa4200514 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-647/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** cellGcmSys: opt-in dedicated thread for handler delivery (GCM_HANDLER_THREAD=1) + +## Description + +## Why +In `libs/video/cellGcmSys.c`, `ppu_gcm_pump` delivers pending vblank/flip and user handlers on whatever guest thread happens to execute an HLE call or wait pump. When invoking the callback, `ppu_guest_call` passes the calling thread's own thread ID. + +If the guest thread already holds a game-engine lock that the handler also attempts to acquire, the handler sees the matching thread ID and re-enters the lock. When the handler unlocks and clears the owner record, the original thread's subsequent unlock sees an unowned/zero lock record and fails or skips unlocking, permanently leaking the lock and deadlocking the engine. + +In *MLB The Show 16* (BCUS01089) and *MLB 15 The Show* (, item 4), lock wrappers record the owner's thread ID at `+0x8` alongside the `sys_lwmutex`. Delivering the flip handler inside the `DisplayFlip` thread caused this exact lock leak, freezing the display loop and stopping all subsequent vblank/flip callbacks. + +On a physical PS3, these handlers are dispatched asynchronously from GCM's interrupt thread rather than synchronously inside arbitrary guest threads. + +## What changed +- Added an opt-in mode behind `GCM_HANDLER_THREAD=1`: + - When enabled, `ppu_gcm_pump` spawns and routes delivery through a dedicated host worker thread (`gcm_intr_main`). + - Calls to `ppu_gcm_pump` from other threads simply ensure the interrupt thread is running and return immediately. + - Leaves default behavior unchanged when `GCM_HANDLER_THREAD` is unset or 0. + +## Testing & Verification +- Tested in *MLB The Show 16*: completely resolves random freezes on boot screens, allowing reliable progression past the intro sequence (verified across multiple consecutive runs). +- Opt-in behavior ensures zero regressions for existing titles that rely on synchronous in-thread delivery. +- Clean-room implementation, no proprietary code included. + +Addresses item 4 in #551. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-647/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-647/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b5c373104b243f973cf405eef28078615de54a64 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-647/tests/oracle.patch @@ -0,0 +1,47 @@ +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..8c6874cd 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -838,8 +838,42 @@ void* ppu_gcm_wait_pump(void (**pump)(void)) + } + #endif + ++/* GCM_HANDLER_THREAD=1: deliver the guest's vblank/flip/user handlers only on a ++ * dedicated host thread, as the PS3 does on its GCM interrupt thread. Pumped at ++ * an HLE boundary, a handler runs nested in whatever guest thread made the call ++ * and inherits its thread id, so a handler taking a lock that thread already ++ * holds re-enters it instead of waiting. MLB The Show 16's lock wrappers record ++ * the owner id and unlock only for the recorded owner: its flip handler, ++ * delivered inside its DisplayFlip thread, cleared that record, DisplayFlip's ++ * own unlock was skipped and the lock leaked, freezing the game. */ ++void ppu_gcm_pump(void); ++static unsigned long s_gcm_intr_tid = 0; ++static int gcm_handler_thread_on(void) ++{ ++ static int v = -1; ++ if (v < 0) { const char* e = getenv("GCM_HANDLER_THREAD"); v = (e && *e && *e != '0') ? 1 : 0; } ++ return v; ++} ++static DWORD WINAPI gcm_intr_main(LPVOID unused) ++{ ++ (void)unused; ++ s_gcm_intr_tid = (unsigned long)GetCurrentThreadId(); ++#ifdef _WIN32 ++ for (;;) { ppu_gcm_pump(); Sleep(1); } ++#else ++ for (;;) { ppu_gcm_pump(); usleep(250); } ++#endif ++ return 0; ++} ++ + void ppu_gcm_pump(void) + { ++ if (gcm_handler_thread_on() && (unsigned long)GetCurrentThreadId() != s_gcm_intr_tid) { ++ static volatile long started = 0; ++ if (!started && InterlockedCompareExchange(&started, 1, 0) == 0) ++ CreateThread(NULL, 1u << 20, gcm_intr_main, NULL, 0, NULL); ++ return; /* only the interrupt thread delivers */ ++ } + if (!GCM_PUMP_TRY_ENTER()) return; + long p = (long)GCM_PENDING_TAKE(); + u64 user = GCM_USER_PENDING_TAKE(); diff --git a/tasks/sp00nznet__ps3recomp-647/tests/test.sh b/tasks/sp00nznet__ps3recomp-647/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-647/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-647/tests/verifier.py b/tasks/sp00nznet__ps3recomp-647/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-647/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-648/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-648/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-648/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-648/instruction.md b/tasks/sp00nznet__ps3recomp-648/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e9626d4ccd66444a2a34e6ef334086d0549fc7f3 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-648/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** cellGcm: set context end to wrap JUMP slot (begin + size - 4) + +## Description + +## Why + +In `cellGcmSetupContext`, the `CellGcmContextData` structure's `end` pointer (`cdata + 0x4`) was initialized to `cmdbuf + cmdSize`. + +Per the Cell GCM specification and official SDK headers, the last 4 bytes (1 word) of the command buffer are reserved for the closing wrap `JUMP` packet back to `begin`. Titles that manage their command ring and append their own wrap `JUMP` instruction when nearing or reaching `end` (such as *MLB The Show 16*) write the 4-byte jump packet directly at `end`. With `end` pointing to `cmdbuf + cmdSize`, the instruction was written 4 bytes past the end of the allocated command buffer into adjoining memory. When that adjoining memory was subsequently overwritten by subsequent heap allocations, the RSX command walker never took the jump, stepped off into arbitrary data, and hung until timeout. + +Additionally, in the RSX FIFO drain loop: +- A ring filled exactly to `end` represents a completely full, valid buffer awaiting wrap rather than a corrupted overrun, so check `cur > end`. +- When the drain loop generates a wrap `JUMP`, `end` itself is the last valid 32-bit slot, so jump target offset should be `(cur <= end) ? cur : end` rather than subtracting 4 from an already adjusted `end`. + +## What changed + +- In `libs/video/cellGcmSys.c`: + - `cellGcmSetupContext`: initialize `end` to `cmdbuf + cmdSize - 4`. + - `gcm_rsx_process_fifo_unlocked`: adjust overrun check to `cur > end` and wrap jump slot to `(cur <= end) ? cur : end`. +- In `libs/video/tests/test_gcm_flip_wrap.c`: + - Added assertion verifying that `cellGcmSetupContext` configures `end == begin + cmdSize - 4`. + +## Testing & Verification + +- Built and ran `test_gcm_flip_wrap` (`clang -std=gnu17 ... libs/video/tests/test_gcm_flip_wrap.c`): PASS (0 failed). +- Verified in *MLB The Show 16*: completely eliminates 5.9 s RSX command buffer hang timeouts where the walker ran past the ring buffer end. +- Standard clean-room implementation based on documented Cell GCM ring buffer mechanics. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-648/solution/patch.diff b/tasks/sp00nznet__ps3recomp-648/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ace45d5bae9bad2826dc3ad5d99ea781d82f3eb1 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-648/solution/patch.diff @@ -0,0 +1,51 @@ +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..59fa3253 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -612,7 +612,11 @@ u32 cellGcmSetupContext(u32 ctx_out_addr, u32 cmdSize, u32 ioSize, u32 ioAddress + u32 cdata = galloc ? galloc(16, 16) : 0; + if (cdata && gwrite32) { + gwrite32(cdata + 0x0, cmdbuf); /* begin */ +- gwrite32(cdata + 0x4, cmdbuf + cmdSize); /* end */ ++ /* The last word is the wrap JUMP's slot, as in the SDK: a title that ++ * writes its JUMP-to-begin AT `end` (MLB 16) otherwise puts it in the ++ * memory after the ring, and when that is overwritten the walker runs ++ * on into data. */ ++ gwrite32(cdata + 0x4, cmdbuf + cmdSize - 4); /* end */ + gwrite32(cdata + 0x8, cmdbuf); /* current */ + /* Command-buffer-full callback: a guest OPD {func, toc} routed to + * hle_gcm_callback -> cellGcm_fifo_recycle. Without a real callback the +@@ -2841,12 +2845,12 @@ static void gcm_rsx_process_fifo_unlocked(void) + * and near-end recycling is enabled from then on. */ + static int s_title_overran = 0; + if (s_fifo_recycle_waiting) head_consumed = 0; /* its callback is recycling */ +- else if (begin && end > begin && cur >= end) { head_consumed = 1; s_title_overran = 1; } ++ else if (begin && end > begin && cur > end) { head_consumed = 1; s_title_overran = 1; } /* `end` is the last word: cur == end is full, not overrun */ + if (begin && end > begin && cur >= begin && cur + GCM_RECYCLE_SLACK >= end + && head_consumed && s_title_overran) { + u32 io_begin = gcm_ea2io(begin); + if (io_begin != 0xFFFFFFFFu) { +- u32 jmp_at = (cur + 4 <= end) ? cur : end - 4; ++ u32 jmp_at = (cur <= end) ? cur : end; /* `end` is the JUMP's own slot */ + vm_write32(jmp_at, 0x20000000u | io_begin); /* JUMP -> begin */ + vm_write32(ctx + 0x8, begin); /* current = begin */ + vm_write32(GCM_CONTROL_GUEST_ADDR + 0, io_begin); /* put */ +diff --git a/libs/video/tests/test_gcm_flip_wrap.c b/libs/video/tests/test_gcm_flip_wrap.c +index b4667524..f4118511 100644 +--- a/libs/video/tests/test_gcm_flip_wrap.c ++++ b/libs/video/tests/test_gcm_flip_wrap.c +@@ -103,6 +103,14 @@ int main(void) + u32 rt = cellGcmSetupContext(ctx_out, CMD_SIZE, IO_SIZE, IO_ADDR, host_alloc, host_w32); + s_display_buffer_set[1] = 1; + ++ /* CellGcmContextData: end reserves the last word for the wrap JUMP */ ++ const u32 rt_begin = vm_read32(rt); ++ const u32 rt_end = vm_read32(rt + 4); ++ if (rt_end != rt_begin + CMD_SIZE - 4) { ++ printf("FAIL: rt_end (0x%08X) != rt_begin + CMD_SIZE - 4 (0x%08X)\n", rt_end, rt_begin + CMD_SIZE - 4); ++ fails++; ++ } ++ + /* The title's draw context: 0x30000 bytes inside the IO window, with its + * own callback descriptor. */ + const u32 tctx = host_alloc(0x18, 16), tbuf = IO_ADDR + 0x200000u; diff --git a/tasks/sp00nznet__ps3recomp-648/solution/solve.sh b/tasks/sp00nznet__ps3recomp-648/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-648/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-648/task.toml b/tasks/sp00nznet__ps3recomp-648/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..491ad6e0cc5d4f3493bfaacad95fc1cc3c9eab1d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-648/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-648" +description = "cellGcm: set context end to wrap JUMP slot (begin + size - 4)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/648" +source_access = "auto" +built_at = "2026-11-16T16:09:59.648551+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:176896719a1714d1ecbdc3fefc0862cc92af4a3af08df8e1d5c4024f4c6f87c7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/video/cellGcmSys.c", + "libs/video/tests/test_gcm_flip_wrap.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 18 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.144710+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-648/tests/capture.py b/tasks/sp00nznet__ps3recomp-648/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-648/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-648/tests/instruction.md b/tasks/sp00nznet__ps3recomp-648/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e9626d4ccd66444a2a34e6ef334086d0549fc7f3 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-648/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** cellGcm: set context end to wrap JUMP slot (begin + size - 4) + +## Description + +## Why + +In `cellGcmSetupContext`, the `CellGcmContextData` structure's `end` pointer (`cdata + 0x4`) was initialized to `cmdbuf + cmdSize`. + +Per the Cell GCM specification and official SDK headers, the last 4 bytes (1 word) of the command buffer are reserved for the closing wrap `JUMP` packet back to `begin`. Titles that manage their command ring and append their own wrap `JUMP` instruction when nearing or reaching `end` (such as *MLB The Show 16*) write the 4-byte jump packet directly at `end`. With `end` pointing to `cmdbuf + cmdSize`, the instruction was written 4 bytes past the end of the allocated command buffer into adjoining memory. When that adjoining memory was subsequently overwritten by subsequent heap allocations, the RSX command walker never took the jump, stepped off into arbitrary data, and hung until timeout. + +Additionally, in the RSX FIFO drain loop: +- A ring filled exactly to `end` represents a completely full, valid buffer awaiting wrap rather than a corrupted overrun, so check `cur > end`. +- When the drain loop generates a wrap `JUMP`, `end` itself is the last valid 32-bit slot, so jump target offset should be `(cur <= end) ? cur : end` rather than subtracting 4 from an already adjusted `end`. + +## What changed + +- In `libs/video/cellGcmSys.c`: + - `cellGcmSetupContext`: initialize `end` to `cmdbuf + cmdSize - 4`. + - `gcm_rsx_process_fifo_unlocked`: adjust overrun check to `cur > end` and wrap jump slot to `(cur <= end) ? cur : end`. +- In `libs/video/tests/test_gcm_flip_wrap.c`: + - Added assertion verifying that `cellGcmSetupContext` configures `end == begin + cmdSize - 4`. + +## Testing & Verification + +- Built and ran `test_gcm_flip_wrap` (`clang -std=gnu17 ... libs/video/tests/test_gcm_flip_wrap.c`): PASS (0 failed). +- Verified in *MLB The Show 16*: completely eliminates 5.9 s RSX command buffer hang timeouts where the walker ran past the ring buffer end. +- Standard clean-room implementation based on documented Cell GCM ring buffer mechanics. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-648/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-648/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ace45d5bae9bad2826dc3ad5d99ea781d82f3eb1 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-648/tests/oracle.patch @@ -0,0 +1,51 @@ +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..59fa3253 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -612,7 +612,11 @@ u32 cellGcmSetupContext(u32 ctx_out_addr, u32 cmdSize, u32 ioSize, u32 ioAddress + u32 cdata = galloc ? galloc(16, 16) : 0; + if (cdata && gwrite32) { + gwrite32(cdata + 0x0, cmdbuf); /* begin */ +- gwrite32(cdata + 0x4, cmdbuf + cmdSize); /* end */ ++ /* The last word is the wrap JUMP's slot, as in the SDK: a title that ++ * writes its JUMP-to-begin AT `end` (MLB 16) otherwise puts it in the ++ * memory after the ring, and when that is overwritten the walker runs ++ * on into data. */ ++ gwrite32(cdata + 0x4, cmdbuf + cmdSize - 4); /* end */ + gwrite32(cdata + 0x8, cmdbuf); /* current */ + /* Command-buffer-full callback: a guest OPD {func, toc} routed to + * hle_gcm_callback -> cellGcm_fifo_recycle. Without a real callback the +@@ -2841,12 +2845,12 @@ static void gcm_rsx_process_fifo_unlocked(void) + * and near-end recycling is enabled from then on. */ + static int s_title_overran = 0; + if (s_fifo_recycle_waiting) head_consumed = 0; /* its callback is recycling */ +- else if (begin && end > begin && cur >= end) { head_consumed = 1; s_title_overran = 1; } ++ else if (begin && end > begin && cur > end) { head_consumed = 1; s_title_overran = 1; } /* `end` is the last word: cur == end is full, not overrun */ + if (begin && end > begin && cur >= begin && cur + GCM_RECYCLE_SLACK >= end + && head_consumed && s_title_overran) { + u32 io_begin = gcm_ea2io(begin); + if (io_begin != 0xFFFFFFFFu) { +- u32 jmp_at = (cur + 4 <= end) ? cur : end - 4; ++ u32 jmp_at = (cur <= end) ? cur : end; /* `end` is the JUMP's own slot */ + vm_write32(jmp_at, 0x20000000u | io_begin); /* JUMP -> begin */ + vm_write32(ctx + 0x8, begin); /* current = begin */ + vm_write32(GCM_CONTROL_GUEST_ADDR + 0, io_begin); /* put */ +diff --git a/libs/video/tests/test_gcm_flip_wrap.c b/libs/video/tests/test_gcm_flip_wrap.c +index b4667524..f4118511 100644 +--- a/libs/video/tests/test_gcm_flip_wrap.c ++++ b/libs/video/tests/test_gcm_flip_wrap.c +@@ -103,6 +103,14 @@ int main(void) + u32 rt = cellGcmSetupContext(ctx_out, CMD_SIZE, IO_SIZE, IO_ADDR, host_alloc, host_w32); + s_display_buffer_set[1] = 1; + ++ /* CellGcmContextData: end reserves the last word for the wrap JUMP */ ++ const u32 rt_begin = vm_read32(rt); ++ const u32 rt_end = vm_read32(rt + 4); ++ if (rt_end != rt_begin + CMD_SIZE - 4) { ++ printf("FAIL: rt_end (0x%08X) != rt_begin + CMD_SIZE - 4 (0x%08X)\n", rt_end, rt_begin + CMD_SIZE - 4); ++ fails++; ++ } ++ + /* The title's draw context: 0x30000 bytes inside the IO window, with its + * own callback descriptor. */ + const u32 tctx = host_alloc(0x18, 16), tbuf = IO_ADDR + 0x200000u; diff --git a/tasks/sp00nznet__ps3recomp-648/tests/test.sh b/tasks/sp00nznet__ps3recomp-648/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-648/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-648/tests/verifier.py b/tasks/sp00nznet__ps3recomp-648/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-648/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-649/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-649/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-649/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-649/instruction.md b/tasks/sp00nznet__ps3recomp-649/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9045f67fff77380d7d91bb3cf2011f34fb4b6224 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-649/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** cellSpurs: clamp maxContention and implement cellSpursRequestIdleSpu + +## Description + +## Why + +1. `cellSpursSetMaxContention` and `cellSpursAddWorkload`: The SPURS instance stores per-workload maximum contention in an 8-bit unsigned integer (`SPURS_WKL_MAXCONT`). In titles or wrappers that pass high default contention values (such as 256), a bare `(u8)` cast wrapped the value to `0`. A contention cap of 0 meant the workload was never dispatched by `spurs_kernel_thread` (`if (!maxcont || si->active[wid] >= maxcont) continue;`). Per the Cell SPURS specification, a workload cannot use more than `CELL_SPURS_MAX_SPU` (8) SPUs, so contention values above 8 must clamp to 8 instead of wrapping. + +2. `cellSpursRequestIdleSpu`: Upstream provided only a 1-argument stub (`cellSpursRequestIdleSpu(u64 spurs_ea)`) that discarded any passed workload ID or count. While `cellSpursGetWorkloadInfo` reads `SPURS_WKL_IDLE2 + wid` (`idleSpuRequest`), `cellSpursRequestIdleSpu` never populated it. Under the standard SPURS ABI, the signature is `(spurs, wid, count)`. It must validate that `spurs` is non-null, `wid < CELL_SPURS_MAX_WORKLOAD`, and that the workload slot is currently in use and belongs to the specified instance (`CELL_SPURS_CORE_ERROR_SRCH`, matching `cellSpursSetMaxContention` and `cellSpursRemoveWorkload`). + +## What changed + +- In `libs/spurs/cellSpurs.c`: + - Added `spurs_clamp_contention(u32 c)` clamping values to `CELL_SPURS_MAX_SPU`. + - Applied clamping in `cellSpursAddWorkload` and `cellSpursSetMaxContention`. + - Implemented `cellSpursRequestIdleSpu(u64 spurs_ea, u64 wid64, u64 count64)` with full argument validation and storage into `SPURS_WKL_IDLE2`. +- Added unit test `tests/test_spurs_api_limits.c` and Python driver `tools/test_spurs_api_limits.py` (which runs automatically under `CI=1` in the repository test suite). + +## Testing & Verification + +- Tested with `CI=1 python tools/test_spurs_api_limits.py`: + - `cellSpursAddWorkload` with 256 clamps to 8. + - `cellSpursSetMaxContention` with 300 clamps to 8. + - `cellSpursRequestIdleSpu` against an unallocated workload returns `CELL_SPURS_CORE_ERROR_SRCH`. + - `cellSpursRequestIdleSpu` with invalid `wid >= 16` returns `CELL_SPURS_CORE_ERROR_INVAL`. + - `cellSpursRequestIdleSpu` with a valid workload sets `SPURS_WKL_IDLE2` and returns `CELL_OK`. +- Clean-room implementation per documented Cell SPURS specifications. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-649/solution/patch.diff b/tasks/sp00nznet__ps3recomp-649/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f685148698347e4cedc9e7611c99604e93521c5c --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-649/solution/patch.diff @@ -0,0 +1,160 @@ +diff --git a/libs/spurs/cellSpurs.c b/libs/spurs/cellSpurs.c +index 82ea66c6..a60fc689 100644 +--- a/libs/spurs/cellSpurs.c ++++ b/libs/spurs/cellSpurs.c +@@ -698,6 +698,14 @@ s32 cellSpursGetNumSpuThread(const CellSpurs* spurs, u32* nThreads) + return CELL_OK; + } + ++/* The instance keeps maxContention in one byte and no workload can occupy more ++ * than CELL_SPURS_MAX_SPU SPUs, so larger values clamp: a bare (u8) cast turned ++ * 256 into 0. */ ++static u32 spurs_clamp_contention(u32 c) ++{ ++ return c > CELL_SPURS_MAX_SPU ? CELL_SPURS_MAX_SPU : c; ++} ++ + s32 cellSpursSetMaxContention(CellSpurs* spurs, CellSpursWorkloadId wid, + u32 maxContention) + { +@@ -710,6 +718,7 @@ s32 cellSpursSetMaxContention(CellSpurs* spurs, CellSpursWorkloadId wid, + spurs_api_unlock(si); return CELL_SPURS_CORE_ERROR_SRCH; + } + ++ maxContention = spurs_clamp_contention(maxContention); + s_workloads[wid].maxContention = maxContention; + vm_write8(si->ea + SPURS_WKL_MAXCONT + wid, (u8)maxContention); + spurs_api_unlock(si); +@@ -1387,6 +1396,7 @@ s32 cellSpursAddWorkload(CellSpurs* spurs, CellSpursWorkloadId* wid, + { + if (!spurs || !wid) + return CELL_SPURS_CORE_ERROR_NULL_POINTER; ++ maxContention = spurs_clamp_contention(maxContention); + /* spurs/wid/priority are guest EAs; pm stays a guest EA (it's the SPU + * program address consumed later by the workload dispatch). */ + uint32_t spurs_ea = (uint32_t)(uintptr_t)spurs; +@@ -3125,10 +3135,25 @@ s32 cellSpursQueuePushBody(u64 queue_ea, u64 data_ea, u32 isBlocking) + * Misc SPURS surface the title links (logged CELL_OK stubs). + * =====================================================================*/ + +-s32 cellSpursRequestIdleSpu(u64 spurs_ea) ++/* cellSpursRequestIdleSpu(spurs, wid, count): the workload may also run on up to ++ * `count` SPUs beyond its ready count. Stored in the instance byte the ++ * kernel reads (SPURS_WKL_IDLE2). */ ++s32 cellSpursRequestIdleSpu(u64 spurs_ea, u64 wid64, u64 count64) + { ++ const u32 wid = (u32)wid64, count = (u32)count64; ++ if (!spurs_ea) return CELL_SPURS_CORE_ERROR_NULL_POINTER; ++ if (wid >= CELL_SPURS_MAX_WORKLOAD) return CELL_SPURS_CORE_ERROR_INVAL; ++ struct SpursInst* si; ++ s32 rc = spurs_api_lock((u32)spurs_ea, &si); ++ if (rc) return rc; ++ if (!s_workloads[wid].in_use || s_workloads[wid].spurs_ea != si->ea) { ++ spurs_api_unlock(si); return CELL_SPURS_CORE_ERROR_SRCH; /* same as SetMaxContention */ ++ } ++ vm_write8(si->ea + SPURS_WKL_IDLE2 + wid, (u8)count); + static int _n = 0; +- if (PS3_LOG_FIRST(_n, 4)) printf("[cellSpurs] RequestIdleSpu(spurs=0x%08X)\n", (u32)spurs_ea); ++ if (PS3_LOG_FIRST(_n, 8)) ++ printf("[cellSpurs] RequestIdleSpu(spurs=0x%08X wid=%u count=%u)\n", (u32)spurs_ea, wid, count); ++ spurs_api_unlock(si); + return CELL_OK; + } + +diff --git a/tests/test_spurs_api_limits.c b/tests/test_spurs_api_limits.c +new file mode 100644 +index 00000000..42e353a1 +--- /dev/null ++++ b/tests/test_spurs_api_limits.c +@@ -0,0 +1,65 @@ ++/* cellSpurs argument limits. Manufactured policy module only, no game code. */ ++#include "../libs/spurs/cellSpurs.c" ++#include <assert.h> ++#include <stdatomic.h> ++#include "../runtime/spu/spu_coherency.h" ++ ++void spu_indirect_branch(spu_context*); ++uint8_t* vm_base; ++uint32_t ppu_vm_size=0x20000; ++int g_resv_store_active; ++uint32_t g_ww_lo,g_ww_hi,g_barrier_sync_watch; ++uint32_t g_spu_image_src_ea,g_spu_image_ls_start,g_spu_image_span; ++unsigned long long ps3_ms_now(void) { LARGE_INTEGER n,f; QueryPerformanceCounter(&n); QueryPerformanceFrequency(&f); return n.QuadPart*1000/f.QuadPart; } ++void ppu_resv_break_store(uint64_t ea) {(void)ea;} ++void ps3_ww_report_inline(uint32_t a,uint64_t v,int w){(void)a;(void)v;(void)w;} ++void sys_event_queue_cancel_by_id(u32 id) {(void)id;} ++void sys_event_queue_uncancel_by_id(u32 id) {(void)id;} ++ ++static atomic_uint gate; ++static void hold_policy(spu_context* c) ++{ ++ u32 ea=spu_ls_read32(c,0x1C4),wid=spu_ls_read32(c,0x1DC); ++ while(!atomic_load(&gate)) Sleep(1); ++ vm_write8(ea+0x80+wid,3); ++ c->pc=SPURS_PM_EXIT_TO_KERNEL_LS;spu_indirect_branch(c); ++} ++static void finalize(u32 ea) ++{ ++ for(unsigned i=0;i<3000;i++) { ++ s32 rc=cellSpursFinalize((CellSpurs*)(uintptr_t)ea); ++ if (!rc) return; ++ assert((u32)rc==CELL_SPURS_CORE_ERROR_BUSY);Sleep(1); ++ } ++ assert(!"finalize failed"); ++} ++ ++int main(void) ++{ ++ vm_base=calloc(1,ppu_vm_size);assert(vm_base); ++ memset(vm_base+0x9000,0x11,16); ++ spu_workload_register_img(spu_workload_fingerprint(vm_base+0x9000,16),hold_policy,77,"api limits fixture"); ++ assert(cellSpursInitialize((CellSpurs*)0x1000,2,0,0,0)==0); ++ ++ /* maxContention is a u8 in the instance; 256 must not wrap to 0 ("none"). */ ++ assert(cellSpursAddWorkload((CellSpurs*)0x1000,(u32*)0x8000,(void*)0x9000,16,0,NULL,1,256)==0); ++ assert(vm_read32(0x8000)==0); ++ assert(vm_read8(0x1000+SPURS_WKL_MAXCONT)==CELL_SPURS_MAX_SPU); ++ assert(cellSpursSetMaxContention((CellSpurs*)0x1000,0,300)==0); ++ assert(vm_read8(0x1000+SPURS_WKL_MAXCONT)==CELL_SPURS_MAX_SPU); ++ assert(cellSpursSetMaxContention((CellSpurs*)0x1000,0,3)==0); ++ assert(vm_read8(0x1000+SPURS_WKL_MAXCONT)==3); ++ puts("SPURS maxContention above 8 clamps instead of wrapping PASS"); ++ ++ /* RequestIdleSpu on a slot that is not in use must fail and leave it alone. */ ++ assert((u32)cellSpursRequestIdleSpu(0x1000,5,2)==CELL_SPURS_CORE_ERROR_SRCH); ++ assert(vm_read8(0x1000+SPURS_WKL_IDLE2+5)==0); ++ assert((u32)cellSpursRequestIdleSpu(0x1000,16,2)==CELL_SPURS_CORE_ERROR_INVAL); ++ assert(cellSpursRequestIdleSpu(0x1000,0,2)==0); ++ assert(vm_read8(0x1000+SPURS_WKL_IDLE2)==2); ++ puts("SPURS RequestIdleSpu rejects a workload slot that is not in use PASS"); ++ ++ atomic_store(&gate,1); ++ finalize(0x1000); ++ free(vm_base);return 0; ++} +diff --git a/tools/test_spurs_api_limits.py b/tools/test_spurs_api_limits.py +new file mode 100755 +index 00000000..573b713e +--- /dev/null ++++ b/tools/test_spurs_api_limits.py +@@ -0,0 +1,20 @@ ++#!/usr/bin/env python3 ++"""cellSpurs argument limits (maxContention clamp, RequestIdleSpu workload check).""" ++import os, platform, subprocess, tempfile ++from pathlib import Path ++if os.name == 'nt': ++ print('SKIP: POSIX fixture'); raise SystemExit(0) ++r=Path(__file__).resolve().parents[1] ++with tempfile.TemporaryDirectory(prefix='spurs-limits-') as tmp: ++ out=Path(tmp)/'test' ++ units=['spu_channels','spu_drain','spu_lockstep','spu_coherency','spu_workload', ++ 'spurs_policy','spurs_job','spu_tsp_weak','spu_vm_pagemap', ++ 'spurs_policy_blob_weak','spu_interp'] ++ subprocess.run([os.environ.get('CC','cc'),'-std=gnu17','-O1','-UNDEBUG', ++ '-ffunction-sections','-fdata-sections', ++ '-Wl,-dead_strip' if platform.system()=='Darwin' else '-Wl,--gc-sections', ++ '-I'+str(r/'include'),'-I'+str(r/'runtime/spu'),'-I'+str(r/'runtime/platform'), ++ str(r/'tests/test_spurs_api_limits.c'), ++ *[str(r/'runtime/spu'/f'{u}.c') for u in units], ++ str(r/'runtime/platform/win32_compat.c'),'-pthread','-lm','-o',str(out)],check=True) ++ subprocess.run([str(out)],check=True,timeout=15) diff --git a/tasks/sp00nznet__ps3recomp-649/solution/solve.sh b/tasks/sp00nznet__ps3recomp-649/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-649/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-649/task.toml b/tasks/sp00nznet__ps3recomp-649/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..173cda47f4721625c9be0323eece9bc8cb81ba89 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-649/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-649" +description = "cellSpurs: clamp maxContention and implement cellSpursRequestIdleSpu" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/649" +source_access = "auto" +built_at = "2026-11-16T16:09:59.741900+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b4ad4b91b4af8d0ef82904ddb9dc9858e81b51d09ad2ad82254908f01301ca7f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/spurs/cellSpurs.c", + "tests/test_spurs_api_limits.c", + "tools/test_spurs_api_limits.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 114 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.145278+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-649/tests/capture.py b/tasks/sp00nznet__ps3recomp-649/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-649/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-649/tests/instruction.md b/tasks/sp00nznet__ps3recomp-649/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9045f67fff77380d7d91bb3cf2011f34fb4b6224 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-649/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** cellSpurs: clamp maxContention and implement cellSpursRequestIdleSpu + +## Description + +## Why + +1. `cellSpursSetMaxContention` and `cellSpursAddWorkload`: The SPURS instance stores per-workload maximum contention in an 8-bit unsigned integer (`SPURS_WKL_MAXCONT`). In titles or wrappers that pass high default contention values (such as 256), a bare `(u8)` cast wrapped the value to `0`. A contention cap of 0 meant the workload was never dispatched by `spurs_kernel_thread` (`if (!maxcont || si->active[wid] >= maxcont) continue;`). Per the Cell SPURS specification, a workload cannot use more than `CELL_SPURS_MAX_SPU` (8) SPUs, so contention values above 8 must clamp to 8 instead of wrapping. + +2. `cellSpursRequestIdleSpu`: Upstream provided only a 1-argument stub (`cellSpursRequestIdleSpu(u64 spurs_ea)`) that discarded any passed workload ID or count. While `cellSpursGetWorkloadInfo` reads `SPURS_WKL_IDLE2 + wid` (`idleSpuRequest`), `cellSpursRequestIdleSpu` never populated it. Under the standard SPURS ABI, the signature is `(spurs, wid, count)`. It must validate that `spurs` is non-null, `wid < CELL_SPURS_MAX_WORKLOAD`, and that the workload slot is currently in use and belongs to the specified instance (`CELL_SPURS_CORE_ERROR_SRCH`, matching `cellSpursSetMaxContention` and `cellSpursRemoveWorkload`). + +## What changed + +- In `libs/spurs/cellSpurs.c`: + - Added `spurs_clamp_contention(u32 c)` clamping values to `CELL_SPURS_MAX_SPU`. + - Applied clamping in `cellSpursAddWorkload` and `cellSpursSetMaxContention`. + - Implemented `cellSpursRequestIdleSpu(u64 spurs_ea, u64 wid64, u64 count64)` with full argument validation and storage into `SPURS_WKL_IDLE2`. +- Added unit test `tests/test_spurs_api_limits.c` and Python driver `tools/test_spurs_api_limits.py` (which runs automatically under `CI=1` in the repository test suite). + +## Testing & Verification + +- Tested with `CI=1 python tools/test_spurs_api_limits.py`: + - `cellSpursAddWorkload` with 256 clamps to 8. + - `cellSpursSetMaxContention` with 300 clamps to 8. + - `cellSpursRequestIdleSpu` against an unallocated workload returns `CELL_SPURS_CORE_ERROR_SRCH`. + - `cellSpursRequestIdleSpu` with invalid `wid >= 16` returns `CELL_SPURS_CORE_ERROR_INVAL`. + - `cellSpursRequestIdleSpu` with a valid workload sets `SPURS_WKL_IDLE2` and returns `CELL_OK`. +- Clean-room implementation per documented Cell SPURS specifications. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-649/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-649/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f685148698347e4cedc9e7611c99604e93521c5c --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-649/tests/oracle.patch @@ -0,0 +1,160 @@ +diff --git a/libs/spurs/cellSpurs.c b/libs/spurs/cellSpurs.c +index 82ea66c6..a60fc689 100644 +--- a/libs/spurs/cellSpurs.c ++++ b/libs/spurs/cellSpurs.c +@@ -698,6 +698,14 @@ s32 cellSpursGetNumSpuThread(const CellSpurs* spurs, u32* nThreads) + return CELL_OK; + } + ++/* The instance keeps maxContention in one byte and no workload can occupy more ++ * than CELL_SPURS_MAX_SPU SPUs, so larger values clamp: a bare (u8) cast turned ++ * 256 into 0. */ ++static u32 spurs_clamp_contention(u32 c) ++{ ++ return c > CELL_SPURS_MAX_SPU ? CELL_SPURS_MAX_SPU : c; ++} ++ + s32 cellSpursSetMaxContention(CellSpurs* spurs, CellSpursWorkloadId wid, + u32 maxContention) + { +@@ -710,6 +718,7 @@ s32 cellSpursSetMaxContention(CellSpurs* spurs, CellSpursWorkloadId wid, + spurs_api_unlock(si); return CELL_SPURS_CORE_ERROR_SRCH; + } + ++ maxContention = spurs_clamp_contention(maxContention); + s_workloads[wid].maxContention = maxContention; + vm_write8(si->ea + SPURS_WKL_MAXCONT + wid, (u8)maxContention); + spurs_api_unlock(si); +@@ -1387,6 +1396,7 @@ s32 cellSpursAddWorkload(CellSpurs* spurs, CellSpursWorkloadId* wid, + { + if (!spurs || !wid) + return CELL_SPURS_CORE_ERROR_NULL_POINTER; ++ maxContention = spurs_clamp_contention(maxContention); + /* spurs/wid/priority are guest EAs; pm stays a guest EA (it's the SPU + * program address consumed later by the workload dispatch). */ + uint32_t spurs_ea = (uint32_t)(uintptr_t)spurs; +@@ -3125,10 +3135,25 @@ s32 cellSpursQueuePushBody(u64 queue_ea, u64 data_ea, u32 isBlocking) + * Misc SPURS surface the title links (logged CELL_OK stubs). + * =====================================================================*/ + +-s32 cellSpursRequestIdleSpu(u64 spurs_ea) ++/* cellSpursRequestIdleSpu(spurs, wid, count): the workload may also run on up to ++ * `count` SPUs beyond its ready count. Stored in the instance byte the ++ * kernel reads (SPURS_WKL_IDLE2). */ ++s32 cellSpursRequestIdleSpu(u64 spurs_ea, u64 wid64, u64 count64) + { ++ const u32 wid = (u32)wid64, count = (u32)count64; ++ if (!spurs_ea) return CELL_SPURS_CORE_ERROR_NULL_POINTER; ++ if (wid >= CELL_SPURS_MAX_WORKLOAD) return CELL_SPURS_CORE_ERROR_INVAL; ++ struct SpursInst* si; ++ s32 rc = spurs_api_lock((u32)spurs_ea, &si); ++ if (rc) return rc; ++ if (!s_workloads[wid].in_use || s_workloads[wid].spurs_ea != si->ea) { ++ spurs_api_unlock(si); return CELL_SPURS_CORE_ERROR_SRCH; /* same as SetMaxContention */ ++ } ++ vm_write8(si->ea + SPURS_WKL_IDLE2 + wid, (u8)count); + static int _n = 0; +- if (PS3_LOG_FIRST(_n, 4)) printf("[cellSpurs] RequestIdleSpu(spurs=0x%08X)\n", (u32)spurs_ea); ++ if (PS3_LOG_FIRST(_n, 8)) ++ printf("[cellSpurs] RequestIdleSpu(spurs=0x%08X wid=%u count=%u)\n", (u32)spurs_ea, wid, count); ++ spurs_api_unlock(si); + return CELL_OK; + } + +diff --git a/tests/test_spurs_api_limits.c b/tests/test_spurs_api_limits.c +new file mode 100644 +index 00000000..42e353a1 +--- /dev/null ++++ b/tests/test_spurs_api_limits.c +@@ -0,0 +1,65 @@ ++/* cellSpurs argument limits. Manufactured policy module only, no game code. */ ++#include "../libs/spurs/cellSpurs.c" ++#include <assert.h> ++#include <stdatomic.h> ++#include "../runtime/spu/spu_coherency.h" ++ ++void spu_indirect_branch(spu_context*); ++uint8_t* vm_base; ++uint32_t ppu_vm_size=0x20000; ++int g_resv_store_active; ++uint32_t g_ww_lo,g_ww_hi,g_barrier_sync_watch; ++uint32_t g_spu_image_src_ea,g_spu_image_ls_start,g_spu_image_span; ++unsigned long long ps3_ms_now(void) { LARGE_INTEGER n,f; QueryPerformanceCounter(&n); QueryPerformanceFrequency(&f); return n.QuadPart*1000/f.QuadPart; } ++void ppu_resv_break_store(uint64_t ea) {(void)ea;} ++void ps3_ww_report_inline(uint32_t a,uint64_t v,int w){(void)a;(void)v;(void)w;} ++void sys_event_queue_cancel_by_id(u32 id) {(void)id;} ++void sys_event_queue_uncancel_by_id(u32 id) {(void)id;} ++ ++static atomic_uint gate; ++static void hold_policy(spu_context* c) ++{ ++ u32 ea=spu_ls_read32(c,0x1C4),wid=spu_ls_read32(c,0x1DC); ++ while(!atomic_load(&gate)) Sleep(1); ++ vm_write8(ea+0x80+wid,3); ++ c->pc=SPURS_PM_EXIT_TO_KERNEL_LS;spu_indirect_branch(c); ++} ++static void finalize(u32 ea) ++{ ++ for(unsigned i=0;i<3000;i++) { ++ s32 rc=cellSpursFinalize((CellSpurs*)(uintptr_t)ea); ++ if (!rc) return; ++ assert((u32)rc==CELL_SPURS_CORE_ERROR_BUSY);Sleep(1); ++ } ++ assert(!"finalize failed"); ++} ++ ++int main(void) ++{ ++ vm_base=calloc(1,ppu_vm_size);assert(vm_base); ++ memset(vm_base+0x9000,0x11,16); ++ spu_workload_register_img(spu_workload_fingerprint(vm_base+0x9000,16),hold_policy,77,"api limits fixture"); ++ assert(cellSpursInitialize((CellSpurs*)0x1000,2,0,0,0)==0); ++ ++ /* maxContention is a u8 in the instance; 256 must not wrap to 0 ("none"). */ ++ assert(cellSpursAddWorkload((CellSpurs*)0x1000,(u32*)0x8000,(void*)0x9000,16,0,NULL,1,256)==0); ++ assert(vm_read32(0x8000)==0); ++ assert(vm_read8(0x1000+SPURS_WKL_MAXCONT)==CELL_SPURS_MAX_SPU); ++ assert(cellSpursSetMaxContention((CellSpurs*)0x1000,0,300)==0); ++ assert(vm_read8(0x1000+SPURS_WKL_MAXCONT)==CELL_SPURS_MAX_SPU); ++ assert(cellSpursSetMaxContention((CellSpurs*)0x1000,0,3)==0); ++ assert(vm_read8(0x1000+SPURS_WKL_MAXCONT)==3); ++ puts("SPURS maxContention above 8 clamps instead of wrapping PASS"); ++ ++ /* RequestIdleSpu on a slot that is not in use must fail and leave it alone. */ ++ assert((u32)cellSpursRequestIdleSpu(0x1000,5,2)==CELL_SPURS_CORE_ERROR_SRCH); ++ assert(vm_read8(0x1000+SPURS_WKL_IDLE2+5)==0); ++ assert((u32)cellSpursRequestIdleSpu(0x1000,16,2)==CELL_SPURS_CORE_ERROR_INVAL); ++ assert(cellSpursRequestIdleSpu(0x1000,0,2)==0); ++ assert(vm_read8(0x1000+SPURS_WKL_IDLE2)==2); ++ puts("SPURS RequestIdleSpu rejects a workload slot that is not in use PASS"); ++ ++ atomic_store(&gate,1); ++ finalize(0x1000); ++ free(vm_base);return 0; ++} +diff --git a/tools/test_spurs_api_limits.py b/tools/test_spurs_api_limits.py +new file mode 100755 +index 00000000..573b713e +--- /dev/null ++++ b/tools/test_spurs_api_limits.py +@@ -0,0 +1,20 @@ ++#!/usr/bin/env python3 ++"""cellSpurs argument limits (maxContention clamp, RequestIdleSpu workload check).""" ++import os, platform, subprocess, tempfile ++from pathlib import Path ++if os.name == 'nt': ++ print('SKIP: POSIX fixture'); raise SystemExit(0) ++r=Path(__file__).resolve().parents[1] ++with tempfile.TemporaryDirectory(prefix='spurs-limits-') as tmp: ++ out=Path(tmp)/'test' ++ units=['spu_channels','spu_drain','spu_lockstep','spu_coherency','spu_workload', ++ 'spurs_policy','spurs_job','spu_tsp_weak','spu_vm_pagemap', ++ 'spurs_policy_blob_weak','spu_interp'] ++ subprocess.run([os.environ.get('CC','cc'),'-std=gnu17','-O1','-UNDEBUG', ++ '-ffunction-sections','-fdata-sections', ++ '-Wl,-dead_strip' if platform.system()=='Darwin' else '-Wl,--gc-sections', ++ '-I'+str(r/'include'),'-I'+str(r/'runtime/spu'),'-I'+str(r/'runtime/platform'), ++ str(r/'tests/test_spurs_api_limits.c'), ++ *[str(r/'runtime/spu'/f'{u}.c') for u in units], ++ str(r/'runtime/platform/win32_compat.c'),'-pthread','-lm','-o',str(out)],check=True) ++ subprocess.run([str(out)],check=True,timeout=15) diff --git a/tasks/sp00nznet__ps3recomp-649/tests/test.sh b/tasks/sp00nznet__ps3recomp-649/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-649/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-649/tests/verifier.py b/tasks/sp00nznet__ps3recomp-649/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-649/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-652/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-652/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-652/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-652/instruction.md b/tasks/sp00nznet__ps3recomp-652/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ac939f198f704a8ac9548ceada23aaac8c40a8e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-652/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** ppu: distinguish completed callbacks from missing dispatch + +## Description + +The resolved code/TOC callback API returns zero both when dispatch never happens and when a callback completes with guest r3 equal to zero. Add a checked form with a separate completion status and result output, while preserving the result-only wrapper. Restore the host active-context and pending trampoline on C++ unwind, and drain only continuations owned by this callback. + +The production-function fixture covers unresolved and zero code, null output, completed zero, full-width arguments/results, callback tails, a preexisting caller tail, and exception propagation/restoration. Unmodified upstream fails the behavioral control. The complete-loader callback-stack regression also passes, including nested callbacks, two simultaneous host threads and 100 sequential thread lifetimes. + +Validation commands: + +```sh +python3 tools/test_guest_call_completion.py +python3 tools/test_ppu_guest_call_stack.py +``` + +Local focused checks pass on Apple Silicon macOS with AppleClang 17 and Python 3.14. The six candidates, including the subsequent CI repairs, also merge cleanly together, build in Release with PS3RECOMP_BUILD_TESTS=ON, and pass 22/22 CTest tests. That full runtime build and CTest result belong to the combined validation checkout. POSIX-only Python compiler harnesses explicitly skip Windows; the standard hosted Windows build and its other checks provide separate platform coverage. + +This is a host API contract, not a new claim about firmware ABI. The focused fixture extracts the actual callback body and supplies a function registry and stack-allocation boundary; the existing complete-loader regression separately exercises real callback stacks. General C longjmp and unrelated OPD dispatch paths are outside this change. + +Based directly on upstream master `4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514` (v0.18.0). No dependency on another proposed PR. + +CI follow-up: the first hosted macOS jobs were canceled before executing because of GitHub's scheduled macOS 14 runner-image brownout. A separate commit moves the existing arm64 matrix to `macos-15`, retaining its architecture checks. See Hosted checks are being monitored on the updated head. + +Additional CI repairs: the existing FIFO-walker profiler now stops against an elapsed monotonic deadline instead of counting requested one-millisecond sleeps. Its regression includes forced 20 ms wakeups and validates a nonempty consistent profile without assuming the host delivers 1 kHz. The delayed-wakeup control fails before the repair and passes after it. + +Hosted CI at published head `f79607461e5ae8b370849ba30ffb70a0a0853f9a`: all 10 jobs pass, covering Linux GCC/Clang Debug and Release, Windows Debug and Release, macOS arm64 Debug and Release, and Vulkan on lavapipe with GCC and Clang. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-652/solution/patch.diff b/tasks/sp00nznet__ps3recomp-652/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..178b1cebda4c796d17c024b23672b4fad09413bd --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-652/solution/patch.diff @@ -0,0 +1,138 @@ +diff --git a/include/ps3emu/guest_call.h b/include/ps3emu/guest_call.h +index 2df28d96..fc7eeac5 100644 +--- a/include/ps3emu/guest_call.h ++++ b/include/ps3emu/guest_call.h +@@ -47,6 +47,15 @@ typedef void (*ps3_guest_caller_fn)(uint32_t opd_addr, + * check for NULL before invoking. */ + extern ps3_guest_caller_fn g_ps3_guest_caller; + ++/* Synchronous resolved callback dispatch. Returns 0 only when not dispatched, ++ * 1 after callback and trampoline completion; the guest r3 result is separate. ++ * Output is initialized to zero. Exceptions/nonlocal exits propagate and mean ++ * uncertain ownership; callers must quarantine rather than retry side effects. ++ * No guest memory is read by this code/TOC form. */ ++int ppu_guest_call_ct_checked(uint32_t code, uint32_t toc, ++ uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, ++ uint64_t a4, uint64_t a5, uint64_t a6, uint64_t a7, uint64_t* result); ++ + /* Convenience wrapper — checks for NULL and invokes if set. */ + static inline void ps3_invoke_guest(uint32_t opd_addr, + uint64_t arg0, uint64_t arg1, +diff --git a/runtime/ppu/ppu_loader.cpp b/runtime/ppu/ppu_loader.cpp +index 9309f2d3..44633f26 100644 +--- a/runtime/ppu/ppu_loader.cpp ++++ b/runtime/ppu/ppu_loader.cpp +@@ -3944,10 +3944,22 @@ extern "C" uint64_t ppu_guest_call(uint32_t opd_addr, + * callbacks whose OPD is captured at registration time and may later be + * clobbered in guest memory (e.g. the GCM flip/vblank handler OPDs). Same + * scratch-stack + trampoline-drain behaviour as ppu_guest_call. */ +-extern "C" uint64_t ppu_guest_call_ct(uint32_t code, uint32_t toc, ++/* Restore host context even when a synchronous callback throws. */ ++struct ppu_active_context_scope { ++ ppu_context* previous; ++ explicit ppu_active_context_scope(ppu_context* current) : previous(g_active_ctx) { ++ g_active_ctx = current; ++ } ++ ~ppu_active_context_scope() { g_active_ctx = previous; } ++}; ++ ++extern "C" int ppu_guest_call_ct_checked(uint32_t code, uint32_t toc, + uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, +- uint64_t a4, uint64_t a5, uint64_t a6, uint64_t a7) ++ uint64_t a4, uint64_t a5, uint64_t a6, uint64_t a7, ++ uint64_t* result) + { ++ if (!result) return 0; ++ *result = 0; + if (!code) return 0; + ppu_fn fn = ppu_lookup(code); + if (!fn) { fprintf(stderr, "[ppu] guest_call_ct: code 0x%08X not registered\n", code); return 0; } +@@ -3970,11 +3982,30 @@ extern "C" uint64_t ppu_guest_call_ct(uint32_t code, uint32_t toc, + #else + ctx.thread_id = saved_active ? saved_active->thread_id : 0x7FFF0000ull; + #endif +- g_active_ctx = &ctx; ++ ppu_active_context_scope active_scope(&ctx); ++ /* A callback owns only the continuations it enqueues. Preserve any caller ++ * continuation, and discard an abandoned tail if this callback unwinds. */ ++ struct callback_trampoline_scope { ++ void (*previous)(void*); ++ callback_trampoline_scope() : previous(g_trampoline_fn) { g_trampoline_fn = nullptr; } ++ ~callback_trampoline_scope() { g_trampoline_fn = previous; } ++ } trampoline_scope; ++ + fn(&ctx); + while (g_trampoline_fn) { void (*tf)(void*) = g_trampoline_fn; g_trampoline_fn = 0; tf(&ctx); } +- g_active_ctx = saved_active; +- return ctx.gpr[3]; ++ *result = ctx.gpr[3]; ++ return 1; ++} ++ ++/* Legacy callers keep their result-only contract. Ownership-sensitive users ++ * use the checked entry point: zero-valued callback success is unambiguous. */ ++extern "C" uint64_t ppu_guest_call_ct(uint32_t code, uint32_t toc, ++ uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, ++ uint64_t a4, uint64_t a5, uint64_t a6, uint64_t a7) ++{ ++ uint64_t result = 0; ++ ppu_guest_call_ct_checked(code,toc,a0,a1,a2,a3,a4,a5,a6,a7,&result); ++ return result; + } + + extern "C" ppu_context* volatile g_ppu_main_ctx = nullptr; +diff --git a/tools/test_guest_call_completion.py b/tools/test_guest_call_completion.py +new file mode 100644 +index 00000000..a942e12a +--- /dev/null ++++ b/tools/test_guest_call_completion.py +@@ -0,0 +1,49 @@ ++#!/usr/bin/env python3 ++"""Compile the actual resolved guest-call body with an isolated function registry.""" ++import os,subprocess,tempfile ++from pathlib import Path ++root=Path(__file__).resolve().parents[1] ++s=(root/'runtime/ppu/ppu_loader.cpp').read_text() ++def function(name): ++ start=s.index('extern "C"',s.index(name)-30);body=s.index('{',start);depth=1;i=body+1 ++ while depth: ++ depth+=(s[i]=='{')-(s[i]=='}');i+=1 ++ return s[start:i] ++def main(): ++ if os.name=='nt': print('SKIP standalone POSIX C++ fixture');return ++ legacy=function('uint64_t ppu_guest_call_ct(') ++ checked=function('int ppu_guest_call_ct_checked(') if 'int ppu_guest_call_ct_checked(' in s else '' ++ begin=s.find('struct ppu_active_context_scope');scope=s[begin:s.index('};',begin)+2] if begin >= 0 else '' ++ baseline="""// Baseline preserves the old ambiguous return contract so RED is behavioral. ++extern "C" int ppu_guest_call_ct_checked(uint32_t c,uint32_t t,uint64_t a,uint64_t b,uint64_t d,uint64_t e,uint64_t f,uint64_t g,uint64_t h,uint64_t i,uint64_t*out){*out=ppu_guest_call_ct(c,t,a,b,d,e,f,g,h,i);return 1;} ++""" ++ pre="""#include "ppu_context.h" ++#include <cassert> ++#include <cstdio> ++#include <stdexcept> ++using ppu_fn=void(*)(ppu_context*); ++static ppu_context* g_active_ctx=nullptr; ++static void(*g_trampoline_fn)(void*)=nullptr; ++#define PPU_TLS_TP 0x74000130 ++static uint32_t ppu_cb_stack_sp(ppu_context*) { return 0x50000; } ++static unsigned calls=0;static bool throwing=false,trampoline=false; ++static void tail(void*p){auto*c=(ppu_context*)p;c->gpr[3]=0xFEDCBA9876543210ULL;} ++static void guest(ppu_context*c){++calls;assert(c==g_active_ctx);assert(c->gpr[2]==0x12345678);assert(c->thread_id==99);assert(c->gpr[13]==PPU_TLS_TP);for(unsigned i=0;i<8;++i)assert(c->gpr[3+i]==0x100000000ULL+i);if(throwing){g_trampoline_fn=tail;throw std::runtime_error("callback did not complete");}c->gpr[3]=0;if(trampoline)g_trampoline_fn=tail;} ++static ppu_fn ppu_lookup(uint32_t c){return c==0x100?guest:nullptr;} ++""" ++ tests="""static int invoke(uint32_t code,uint64_t*out){return ppu_guest_call_ct_checked(code,0x12345678,0x100000000ULL,0x100000001ULL,0x100000002ULL,0x100000003ULL,0x100000004ULL,0x100000005ULL,0x100000006ULL,0x100000007ULL,out);} ++int main(){ppu_context owner{};owner.thread_id=99;g_active_ctx=&owner;uint64_t out=0xA5; ++assert(invoke(0x200,&out)==0);assert(!calls&&out==0&&g_active_ctx==&owner); ++assert(invoke(0,&out)==0);assert(!calls); ++assert(invoke(0x100,nullptr)==0);assert(!calls); ++assert(invoke(0x100,&out)==1);assert(calls==1&&out==0&&g_active_ctx==&owner); ++trampoline=true;assert(invoke(0x100,&out)==1);assert(out==0xFEDCBA9876543210ULL&&g_active_ctx==&owner); ++g_trampoline_fn=tail;trampoline=false;assert(invoke(0x100,&out)==1&&out==0&&g_trampoline_fn==tail);g_trampoline_fn=nullptr; ++throwing=true;out=0xA5;bool escaped=false;try{invoke(0x100,&out);}catch(const std::runtime_error&){escaped=true;} ++assert(escaped&&out==0&&g_active_ctx==&owner);assert(!g_trampoline_fn);throwing=false;trampoline=false;assert(invoke(0x100,&out)==1&&out==0);puts("PASS never-dispatched vs completed zero,64-bit result/args,trampoline,exception context restore");} ++""" ++ with tempfile.TemporaryDirectory(prefix='guest-call-completion-') as tmp: ++ tmp=Path(tmp);cpp=tmp/'fixture.cpp';cpp.write_text(pre+scope+'\n'+checked+'\n'+legacy+'\n'+('' if checked else baseline)+tests) ++ subprocess.run([os.environ.get('CXX','c++'),'-std=c++20','-O1','-UNDEBUG','-I'+str(root/'runtime/ppu'),str(cpp),'-o',str(tmp/'fixture')],check=True,timeout=30) ++ subprocess.run([str(tmp/'fixture')],check=True,timeout=5) ++if __name__=='__main__':main() diff --git a/tasks/sp00nznet__ps3recomp-652/solution/solve.sh b/tasks/sp00nznet__ps3recomp-652/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-652/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-652/task.toml b/tasks/sp00nznet__ps3recomp-652/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a6e31129dc9852b8161e0951f1736fa5ed51b112 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-652/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-652" +description = "ppu: distinguish completed callbacks from missing dispatch" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/652" +source_access = "auto" +built_at = "2026-11-16T16:09:59.740121+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e85dad73d227cb3b3fe528aa5f54f01d39aeab2282e830c0225e03d769524908" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "include/ps3emu/guest_call.h", + "runtime/ppu/ppu_loader.cpp", + "tools/test_guest_call_completion.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 99 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.145871+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-652/tests/capture.py b/tasks/sp00nznet__ps3recomp-652/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-652/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-652/tests/instruction.md b/tasks/sp00nznet__ps3recomp-652/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ac939f198f704a8ac9548ceada23aaac8c40a8e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-652/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** ppu: distinguish completed callbacks from missing dispatch + +## Description + +The resolved code/TOC callback API returns zero both when dispatch never happens and when a callback completes with guest r3 equal to zero. Add a checked form with a separate completion status and result output, while preserving the result-only wrapper. Restore the host active-context and pending trampoline on C++ unwind, and drain only continuations owned by this callback. + +The production-function fixture covers unresolved and zero code, null output, completed zero, full-width arguments/results, callback tails, a preexisting caller tail, and exception propagation/restoration. Unmodified upstream fails the behavioral control. The complete-loader callback-stack regression also passes, including nested callbacks, two simultaneous host threads and 100 sequential thread lifetimes. + +Validation commands: + +```sh +python3 tools/test_guest_call_completion.py +python3 tools/test_ppu_guest_call_stack.py +``` + +Local focused checks pass on Apple Silicon macOS with AppleClang 17 and Python 3.14. The six candidates, including the subsequent CI repairs, also merge cleanly together, build in Release with PS3RECOMP_BUILD_TESTS=ON, and pass 22/22 CTest tests. That full runtime build and CTest result belong to the combined validation checkout. POSIX-only Python compiler harnesses explicitly skip Windows; the standard hosted Windows build and its other checks provide separate platform coverage. + +This is a host API contract, not a new claim about firmware ABI. The focused fixture extracts the actual callback body and supplies a function registry and stack-allocation boundary; the existing complete-loader regression separately exercises real callback stacks. General C longjmp and unrelated OPD dispatch paths are outside this change. + +Based directly on upstream master `4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514` (v0.18.0). No dependency on another proposed PR. + +CI follow-up: the first hosted macOS jobs were canceled before executing because of GitHub's scheduled macOS 14 runner-image brownout. A separate commit moves the existing arm64 matrix to `macos-15`, retaining its architecture checks. See Hosted checks are being monitored on the updated head. + +Additional CI repairs: the existing FIFO-walker profiler now stops against an elapsed monotonic deadline instead of counting requested one-millisecond sleeps. Its regression includes forced 20 ms wakeups and validates a nonempty consistent profile without assuming the host delivers 1 kHz. The delayed-wakeup control fails before the repair and passes after it. + +Hosted CI at published head `f79607461e5ae8b370849ba30ffb70a0a0853f9a`: all 10 jobs pass, covering Linux GCC/Clang Debug and Release, Windows Debug and Release, macOS arm64 Debug and Release, and Vulkan on lavapipe with GCC and Clang. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-652/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-652/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..178b1cebda4c796d17c024b23672b4fad09413bd --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-652/tests/oracle.patch @@ -0,0 +1,138 @@ +diff --git a/include/ps3emu/guest_call.h b/include/ps3emu/guest_call.h +index 2df28d96..fc7eeac5 100644 +--- a/include/ps3emu/guest_call.h ++++ b/include/ps3emu/guest_call.h +@@ -47,6 +47,15 @@ typedef void (*ps3_guest_caller_fn)(uint32_t opd_addr, + * check for NULL before invoking. */ + extern ps3_guest_caller_fn g_ps3_guest_caller; + ++/* Synchronous resolved callback dispatch. Returns 0 only when not dispatched, ++ * 1 after callback and trampoline completion; the guest r3 result is separate. ++ * Output is initialized to zero. Exceptions/nonlocal exits propagate and mean ++ * uncertain ownership; callers must quarantine rather than retry side effects. ++ * No guest memory is read by this code/TOC form. */ ++int ppu_guest_call_ct_checked(uint32_t code, uint32_t toc, ++ uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, ++ uint64_t a4, uint64_t a5, uint64_t a6, uint64_t a7, uint64_t* result); ++ + /* Convenience wrapper — checks for NULL and invokes if set. */ + static inline void ps3_invoke_guest(uint32_t opd_addr, + uint64_t arg0, uint64_t arg1, +diff --git a/runtime/ppu/ppu_loader.cpp b/runtime/ppu/ppu_loader.cpp +index 9309f2d3..44633f26 100644 +--- a/runtime/ppu/ppu_loader.cpp ++++ b/runtime/ppu/ppu_loader.cpp +@@ -3944,10 +3944,22 @@ extern "C" uint64_t ppu_guest_call(uint32_t opd_addr, + * callbacks whose OPD is captured at registration time and may later be + * clobbered in guest memory (e.g. the GCM flip/vblank handler OPDs). Same + * scratch-stack + trampoline-drain behaviour as ppu_guest_call. */ +-extern "C" uint64_t ppu_guest_call_ct(uint32_t code, uint32_t toc, ++/* Restore host context even when a synchronous callback throws. */ ++struct ppu_active_context_scope { ++ ppu_context* previous; ++ explicit ppu_active_context_scope(ppu_context* current) : previous(g_active_ctx) { ++ g_active_ctx = current; ++ } ++ ~ppu_active_context_scope() { g_active_ctx = previous; } ++}; ++ ++extern "C" int ppu_guest_call_ct_checked(uint32_t code, uint32_t toc, + uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, +- uint64_t a4, uint64_t a5, uint64_t a6, uint64_t a7) ++ uint64_t a4, uint64_t a5, uint64_t a6, uint64_t a7, ++ uint64_t* result) + { ++ if (!result) return 0; ++ *result = 0; + if (!code) return 0; + ppu_fn fn = ppu_lookup(code); + if (!fn) { fprintf(stderr, "[ppu] guest_call_ct: code 0x%08X not registered\n", code); return 0; } +@@ -3970,11 +3982,30 @@ extern "C" uint64_t ppu_guest_call_ct(uint32_t code, uint32_t toc, + #else + ctx.thread_id = saved_active ? saved_active->thread_id : 0x7FFF0000ull; + #endif +- g_active_ctx = &ctx; ++ ppu_active_context_scope active_scope(&ctx); ++ /* A callback owns only the continuations it enqueues. Preserve any caller ++ * continuation, and discard an abandoned tail if this callback unwinds. */ ++ struct callback_trampoline_scope { ++ void (*previous)(void*); ++ callback_trampoline_scope() : previous(g_trampoline_fn) { g_trampoline_fn = nullptr; } ++ ~callback_trampoline_scope() { g_trampoline_fn = previous; } ++ } trampoline_scope; ++ + fn(&ctx); + while (g_trampoline_fn) { void (*tf)(void*) = g_trampoline_fn; g_trampoline_fn = 0; tf(&ctx); } +- g_active_ctx = saved_active; +- return ctx.gpr[3]; ++ *result = ctx.gpr[3]; ++ return 1; ++} ++ ++/* Legacy callers keep their result-only contract. Ownership-sensitive users ++ * use the checked entry point: zero-valued callback success is unambiguous. */ ++extern "C" uint64_t ppu_guest_call_ct(uint32_t code, uint32_t toc, ++ uint64_t a0, uint64_t a1, uint64_t a2, uint64_t a3, ++ uint64_t a4, uint64_t a5, uint64_t a6, uint64_t a7) ++{ ++ uint64_t result = 0; ++ ppu_guest_call_ct_checked(code,toc,a0,a1,a2,a3,a4,a5,a6,a7,&result); ++ return result; + } + + extern "C" ppu_context* volatile g_ppu_main_ctx = nullptr; +diff --git a/tools/test_guest_call_completion.py b/tools/test_guest_call_completion.py +new file mode 100644 +index 00000000..a942e12a +--- /dev/null ++++ b/tools/test_guest_call_completion.py +@@ -0,0 +1,49 @@ ++#!/usr/bin/env python3 ++"""Compile the actual resolved guest-call body with an isolated function registry.""" ++import os,subprocess,tempfile ++from pathlib import Path ++root=Path(__file__).resolve().parents[1] ++s=(root/'runtime/ppu/ppu_loader.cpp').read_text() ++def function(name): ++ start=s.index('extern "C"',s.index(name)-30);body=s.index('{',start);depth=1;i=body+1 ++ while depth: ++ depth+=(s[i]=='{')-(s[i]=='}');i+=1 ++ return s[start:i] ++def main(): ++ if os.name=='nt': print('SKIP standalone POSIX C++ fixture');return ++ legacy=function('uint64_t ppu_guest_call_ct(') ++ checked=function('int ppu_guest_call_ct_checked(') if 'int ppu_guest_call_ct_checked(' in s else '' ++ begin=s.find('struct ppu_active_context_scope');scope=s[begin:s.index('};',begin)+2] if begin >= 0 else '' ++ baseline="""// Baseline preserves the old ambiguous return contract so RED is behavioral. ++extern "C" int ppu_guest_call_ct_checked(uint32_t c,uint32_t t,uint64_t a,uint64_t b,uint64_t d,uint64_t e,uint64_t f,uint64_t g,uint64_t h,uint64_t i,uint64_t*out){*out=ppu_guest_call_ct(c,t,a,b,d,e,f,g,h,i);return 1;} ++""" ++ pre="""#include "ppu_context.h" ++#include <cassert> ++#include <cstdio> ++#include <stdexcept> ++using ppu_fn=void(*)(ppu_context*); ++static ppu_context* g_active_ctx=nullptr; ++static void(*g_trampoline_fn)(void*)=nullptr; ++#define PPU_TLS_TP 0x74000130 ++static uint32_t ppu_cb_stack_sp(ppu_context*) { return 0x50000; } ++static unsigned calls=0;static bool throwing=false,trampoline=false; ++static void tail(void*p){auto*c=(ppu_context*)p;c->gpr[3]=0xFEDCBA9876543210ULL;} ++static void guest(ppu_context*c){++calls;assert(c==g_active_ctx);assert(c->gpr[2]==0x12345678);assert(c->thread_id==99);assert(c->gpr[13]==PPU_TLS_TP);for(unsigned i=0;i<8;++i)assert(c->gpr[3+i]==0x100000000ULL+i);if(throwing){g_trampoline_fn=tail;throw std::runtime_error("callback did not complete");}c->gpr[3]=0;if(trampoline)g_trampoline_fn=tail;} ++static ppu_fn ppu_lookup(uint32_t c){return c==0x100?guest:nullptr;} ++""" ++ tests="""static int invoke(uint32_t code,uint64_t*out){return ppu_guest_call_ct_checked(code,0x12345678,0x100000000ULL,0x100000001ULL,0x100000002ULL,0x100000003ULL,0x100000004ULL,0x100000005ULL,0x100000006ULL,0x100000007ULL,out);} ++int main(){ppu_context owner{};owner.thread_id=99;g_active_ctx=&owner;uint64_t out=0xA5; ++assert(invoke(0x200,&out)==0);assert(!calls&&out==0&&g_active_ctx==&owner); ++assert(invoke(0,&out)==0);assert(!calls); ++assert(invoke(0x100,nullptr)==0);assert(!calls); ++assert(invoke(0x100,&out)==1);assert(calls==1&&out==0&&g_active_ctx==&owner); ++trampoline=true;assert(invoke(0x100,&out)==1);assert(out==0xFEDCBA9876543210ULL&&g_active_ctx==&owner); ++g_trampoline_fn=tail;trampoline=false;assert(invoke(0x100,&out)==1&&out==0&&g_trampoline_fn==tail);g_trampoline_fn=nullptr; ++throwing=true;out=0xA5;bool escaped=false;try{invoke(0x100,&out);}catch(const std::runtime_error&){escaped=true;} ++assert(escaped&&out==0&&g_active_ctx==&owner);assert(!g_trampoline_fn);throwing=false;trampoline=false;assert(invoke(0x100,&out)==1&&out==0);puts("PASS never-dispatched vs completed zero,64-bit result/args,trampoline,exception context restore");} ++""" ++ with tempfile.TemporaryDirectory(prefix='guest-call-completion-') as tmp: ++ tmp=Path(tmp);cpp=tmp/'fixture.cpp';cpp.write_text(pre+scope+'\n'+checked+'\n'+legacy+'\n'+('' if checked else baseline)+tests) ++ subprocess.run([os.environ.get('CXX','c++'),'-std=c++20','-O1','-UNDEBUG','-I'+str(root/'runtime/ppu'),str(cpp),'-o',str(tmp/'fixture')],check=True,timeout=30) ++ subprocess.run([str(tmp/'fixture')],check=True,timeout=5) ++if __name__=='__main__':main() diff --git a/tasks/sp00nznet__ps3recomp-652/tests/test.sh b/tasks/sp00nznet__ps3recomp-652/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-652/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-652/tests/verifier.py b/tasks/sp00nznet__ps3recomp-652/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-652/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-653/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-653/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-653/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-653/instruction.md b/tasks/sp00nznet__ps3recomp-653/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b52cd44155b4b6deb171530545392b8e9a3fc3b4 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-653/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** sail: retain the allocator argument in its embedded callback record + +## Description + +cellSailMemAllocatorInitialize drops the third argument and its public declarations describe host-sized pointers. Represent the guest allocator as two embedded 32-bit callback OPDs plus the 32-bit argument, copy both callbacks by value, and store pArg at offset 8. Validate the 12-byte destination and 8-byte input before writing, and read both callback words before overlapping output stores. + +The actual generated NID registration and PPU HLE dispatcher run 20 checks for exact byte layout, pArg preservation, canaries, invalid guest ranges/alignment, and overlapping input/output. The unmodified upstream control fails on the dropped pArg. Compile-time size checks enforce 8-byte callbacks and a 12-byte allocator record. + +Validation commands: + +```sh +python3 tools/test_sail_memory_allocator.py +``` + +Local focused checks pass on Apple Silicon macOS with AppleClang 17 and Python 3.14. The six candidates, including the subsequent CI repairs, also merge cleanly together, build in Release with PS3RECOMP_BUILD_TESTS=ON, and pass 22/22 CTest tests. That full runtime build and CTest result belong to the combined validation checkout. POSIX-only Python compiler harnesses explicitly skip Windows; the standard hosted Windows build and its other checks provide separate platform coverage. + +SDK 4.00 `cell/target/ppu/include/cell/sail/common.h`, CellSailMemAllocatorFuncs, CellSailMemAllocator, and cellSailMemAllocatorInitialize: callbacks are embedded, followed by pArg; the header declares three arguments. The same release's CHM initializer topic still shows two arguments, so the header is the precise declaration used here. This corrects the fork's eight-byte callback-table-pointer assumption rather than exporting it. No SDK source, game binaries or capture bytes are included. Descriptor/player lifetime handling is outside this standalone fix. + +Based directly on upstream master `4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514` (v0.18.0). No dependency on another proposed PR. + +CI follow-up: the first hosted macOS jobs were canceled before executing because of GitHub's scheduled macOS 14 runner-image brownout. A separate commit moves the existing arm64 matrix to `macos-15`, retaining its architecture checks. See Hosted checks are being monitored on the updated head. + +Additional CI repairs: the existing FIFO-walker profiler now stops against an elapsed monotonic deadline instead of counting requested one-millisecond sleeps. Its regression includes forced 20 ms wakeups and validates a nonempty consistent profile without assuming the host delivers 1 kHz. The delayed-wakeup control fails before the repair and passes after it. + +Hosted CI at published head `c3a6469b3ab0673344da44dd7f6e3a20f0f3a9d7`: all 10 jobs pass, covering Linux GCC/Clang Debug and Release, Windows Debug and Release, macOS arm64 Debug and Release, and Vulkan on lavapipe with GCC and Clang. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-653/solution/patch.diff b/tasks/sp00nznet__ps3recomp-653/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7ed43a35db64c794b4dc5a994496de071338504f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-653/solution/patch.diff @@ -0,0 +1,199 @@ +diff --git a/libs/codec/cellSail.c b/libs/codec/cellSail.c +index df6d4b38..b29ce167 100644 +--- a/libs/codec/cellSail.c ++++ b/libs/codec/cellSail.c +@@ -566,21 +566,23 @@ s32 cellSailGraphicsAdapterSetPreferredFormat(u32 pSelf, u32 pFormat) + } + + s32 cellSailMemAllocatorInitialize(CellSailMemAllocator* allocator, +- CellSailMemAllocatorFuncs* pFuncs) +-{ +- /* Both parameters are GUEST addresses, and both structs live in GUEST +- * memory with 32-bit big-endian pointers. Dereferencing them as host +- * structs was wrong twice over: the address was never translated, and the +- * host struct has 64-bit fields, so even the offsets did not line up. The +- * values stored here are guest OPD addresses that SAIL calls back into. */ +- u32 alloc_ea = (u32)(uintptr_t)allocator; +- u32 funcs_ea = (u32)(uintptr_t)pFuncs; +- printf("[cellSail] MemAllocatorInitialize(allocator=0x%08X funcs=0x%08X)\n", +- alloc_ea, funcs_ea); +- if (!alloc_ea) return (s32)CELL_SAIL_ERROR_INVALID_ARGUMENT; +- if (funcs_ea) { +- vm_write32(alloc_ea + 0, vm_read32(funcs_ea + 0)); /* pAlloc */ +- vm_write32(alloc_ea + 4, vm_read32(funcs_ea + 4)); /* pFree */ +- } ++ CellSailMemAllocatorFuncs* pFuncs, void* pArg) ++{ ++ /* These arguments are guest EAs, not host records. Copy the two callback ++ * OPDs by value and preserve the third argument in the twelve-byte record. ++ * Read both callbacks first so overlapping input/output remains safe. */ ++ const u64 alloc_ea = (u64)(uintptr_t)allocator; ++ const u64 funcs_ea = (u64)(uintptr_t)pFuncs; ++ extern u32 ppu_vm_size; ++ const u64 limit = ppu_vm_size ? ppu_vm_size : 0x100000000ull; ++ if (!vm_base || !alloc_ea || !funcs_ea || (alloc_ea & 3) || (funcs_ea & 3) || ++ alloc_ea > limit || funcs_ea > limit || ++ 12 > limit - alloc_ea || 8 > limit - funcs_ea) ++ return (s32)0x80610701u; ++ const u32 alloc_opd = vm_read32((u32)funcs_ea); ++ const u32 free_opd = vm_read32((u32)funcs_ea + 4); ++ vm_write32((u32)alloc_ea, alloc_opd); ++ vm_write32((u32)alloc_ea + 4, free_opd); ++ vm_write32((u32)alloc_ea + 8, (u32)(uintptr_t)pArg); + return CELL_OK; + } +diff --git a/libs/codec/cellSail.h b/libs/codec/cellSail.h +index 5224eb38..073b0207 100644 +--- a/libs/codec/cellSail.h ++++ b/libs/codec/cellSail.h +@@ -122,20 +122,18 @@ s32 cellSailDescriptorGetStreamType(CellSailDescriptorHandle desc, s32* type); + s32 cellSailDescriptorSetAutoSelection(CellSailDescriptorHandle desc, s32 enable); + s32 cellSailDescriptorGetUri(CellSailDescriptorHandle desc, char* uri, u32 maxLen); + +-/* Memory allocator */ +-typedef struct CellSailMemAllocator { +- void* (*alloc)(void* arg, u32 boundary, u32 size); +- void (*free)(void* arg, u32 boundary, void* ptr); +- void* arg; +-} CellSailMemAllocator; +- +-/* Mirrors RPCS3's CellSailMemAllocatorFuncs: a guest struct of two callback +- * pointers, passed as one pointer arg (not two separate function pointers). */ ++/* Guest storage layout: 32-bit big-endian callback OPDs followed by pArg. ++ * SDK 4.00 cell/sail/common.h embeds the callback pair by value. */ + typedef struct CellSailMemAllocatorFuncs { +- void* pAlloc; +- void* pFree; ++ u32 pAlloc; ++ u32 pFree; + } CellSailMemAllocatorFuncs; + ++typedef struct CellSailMemAllocator { ++ CellSailMemAllocatorFuncs callbacks; ++ u32 pArg; ++} CellSailMemAllocator; ++ + /* Named pFuncs (not "callbacks") so the import-bridge generator's naming + * heuristic (gen_imports.py param_marshal) treats this as a real guest + * struct pointer needing host-pointer translation, not a raw callback value. */ +@@ -143,7 +141,7 @@ s32 cellSailPlayerInitialize2(u32 pSelf, u32 pAllocator, u32 pCallback, + u32 pUserParam, u32 pAttribute, u32 pResource); + s32 cellSailSoundAdapterInitialize(u32 pSelf, u32 pCallbacks, u32 pArg); + s32 cellSailMemAllocatorInitialize(CellSailMemAllocator* allocator, +- CellSailMemAllocatorFuncs* pFuncs); ++ CellSailMemAllocatorFuncs* pFuncs, void* pArg); + + #ifdef __cplusplus + } +diff --git a/tests/test_sail_memory_allocator.cpp b/tests/test_sail_memory_allocator.cpp +new file mode 100644 +index 00000000..5dec5dc2 +--- /dev/null ++++ b/tests/test_sail_memory_allocator.cpp +@@ -0,0 +1,71 @@ ++/* Exercise generated NID registration and the real PPU HLE bridge. */ ++#include "ppu_context.h" ++#include "../libs/codec/cellSail.h" ++#include "ps3emu/guest_call.h" ++#include <cstdio> ++#include <cstdlib> ++#include <cstring> ++#include <cstdint> ++ ++extern "C" { ++uint8_t* vm_base; ++uint32_t ppu_vm_size=0x10000; ++uint32_t g_ww_lo=0,g_ww_hi=0; ++int g_resv_store_active=0; ++ps3_guest_caller_fn g_ps3_guest_caller=nullptr; ++void ppu_hle_register_all(); ++int ps3_hle_has(uint32_t); ++void ps3_hle_call(uint32_t,ppu_context*); ++int cellfs_translate_path(const char*,char*,size_t) { return -1; } ++int32_t cellPamfReaderInitialize(void*,void*,uint64_t,uint32_t) { std::abort(); } ++int32_t cellPamfReaderGetStreamIndex(void*) { std::abort(); } ++uint32_t prx_resolve_export(uint32_t) { return 0; } ++void ps3_indirect_call(ppu_context*) { std::abort(); } ++uint64_t ppu_guest_call(uint32_t,uint64_t,uint64_t,uint64_t,uint64_t,uint64_t,uint64_t,uint64_t,uint64_t) { std::abort(); } ++void ppu_prof_stamp(void*,unsigned) {} ++void ppu_gcm_pump() {} ++uint32_t ppu_prof_resolve_host(void*) { return 0; } ++void ps3_msf(const char*,...) {} ++int spu_coh_is_reserved(uint32_t) { return 0; } ++void spu_coh_notify_write(uint32_t) {} ++void spu_lockline_lock() {} ++void spu_lockline_unlock() {} ++void ppu_resv_break_store(uint64_t) {} ++void ps3_ww_report_inline(uint32_t,uint64_t,int) {} ++uint32_t vm_read32(uint64_t a) { uint32_t x;std::memcpy(&x,vm_base+a,4);return __builtin_bswap32(x); } ++void vm_write32(uint64_t a,uint32_t x) { x=__builtin_bswap32(x);std::memcpy(vm_base+a,&x,4); } ++} ++extern "C" uint64_t vm_read64(uint64_t a) { uint64_t x;std::memcpy(&x,vm_base+a,8);return __builtin_bswap64(x); } ++void vm_write64(uint64_t a,uint64_t x) { x=__builtin_bswap64(x);std::memcpy(vm_base+a,&x,8); } ++extern "C" void ppu_dump_guest_stack(ppu_context*,const char*) {} ++extern "C" void ppu_dump_bctrl_ring(uint32_t,const char*) {} ++extern "C" void ppu_guest_callstack(const char*) {} ++uint32_t g_ydkj_real_spurs_ea=0,g_ydkj_real_taskset_ea=0; ++ ++static_assert(sizeof(CellSailMemAllocatorFuncs)==8, "guest callback pair"); ++static_assert(sizeof(CellSailMemAllocator)==12, "guest allocator record"); ++static unsigned checks; ++#define CHECK(x) do { ++checks; if(!(x)) { std::fprintf(stderr,"FAIL line%d: %s\n",__LINE__,#x);return 1; } } while(0) ++static uint32_t call(uint32_t nid,uint64_t a=0,uint64_t b=0,uint64_t c=0,uint64_t d=0,uint64_t e=0) { ++ ppu_context ctx{};ctx.gpr[1]=0x8000;ctx.gpr[2]=0x12345678; ++ ctx.gpr[3]=a;ctx.gpr[4]=b;ctx.gpr[5]=c;ctx.gpr[6]=d;ctx.gpr[7]=e; ++ ps3_hle_call(nid,&ctx);if(ctx.gpr[2]!=0x12345678)std::abort();return uint32_t(ctx.gpr[3]); ++} ++int main() { ++ static uint8_t memory[0x10000];vm_base=memory;ppu_hle_register_all(); ++ constexpr uint32_t INIT=0x346EBBA3,ARG=0x80610701; ++ vm_write32(0x1000,0xDEADBEEF);vm_write32(0x1004,0xDEADBEEF);vm_write32(0x1008,0xDEADBEEF);vm_write32(0x100C,0x55667788); ++ vm_write32(0x2000,0x3000);vm_write32(0x2004,0x4000); ++ CHECK(ps3_hle_has(INIT));CHECK(call(INIT,0x1000,0x2000,0x11223344)==0); ++ CHECK(vm_read32(0x1000)==0x3000);CHECK(vm_read32(0x1004)==0x4000);CHECK(vm_read32(0x1008)==0x11223344);CHECK(vm_read32(0x100C)==0x55667788); ++ CHECK(call(INIT,0,0x2000)==ARG);CHECK(call(INIT,0x1001,0x2000)==ARG); ++ CHECK(call(INIT,0xFFFC,0x2000)==ARG);CHECK(call(INIT,0x1000,0)==ARG); ++ CHECK(call(INIT,0x1000,0x2001)==ARG);CHECK(call(INIT,0x1000,0xFFFC)==ARG); ++ CHECK(vm_read32(0x1000)==0x3000);CHECK(vm_read32(0x1004)==0x4000);CHECK(vm_read32(0x1008)==0x11223344); ++ // Copy callbacks before storing: destination may overlap the input table. ++ vm_write32(0x3004,0x5000);vm_write32(0x3008,0x6000); ++ CHECK(call(INIT,0x3000,0x3004,0x77889900)==0); ++ CHECK(vm_read32(0x3000)==0x5000);CHECK(vm_read32(0x3004)==0x6000);CHECK(vm_read32(0x3008)==0x77889900); ++ CHECK(call(INIT,0xFFF8,0x2000)==ARG); ++ std::printf("%u allocator layout checks PASS\n",checks);return 0; ++} +diff --git a/tools/test_sail_memory_allocator.py b/tools/test_sail_memory_allocator.py +new file mode 100644 +index 00000000..9328435a +--- /dev/null ++++ b/tools/test_sail_memory_allocator.py +@@ -0,0 +1,29 @@ ++#!/usr/bin/env python3 ++"""Compile/run real Sail and generated NID registration through the PPU HLE bridge.""" ++import os ++from pathlib import Path ++import subprocess ++import sys ++import tempfile ++from gen_hle_nids import scan ++ ++root=Path(__file__).resolve().parents[1] ++ ++def main(): ++ if os.name=='nt': ++ print('SKIP: standalone HLE bridge regression needs a POSIX toolchain') ++ return 0 ++ handlers=dict(scan(root/'libs/codec/cellSail.c')) ++ assert handlers.get(0x346EBBA3)=='cellSailMemAllocatorInitialize','Allocator is not registered' ++ with tempfile.TemporaryDirectory(prefix='ps3-sail-descriptor-') as tmp: ++ tmp=Path(tmp) ++ (tmp/'ppu_recomp.h').write_text('#include "ppu_context.h"\n') ++ subprocess.run([sys.executable,str(root/'tools/gen_hle_nids.py'),'cellSail','--out',str(tmp/'nids.cpp')],check=True,timeout=15) ++ includes=['-I'+str(p) for p in (root/'include',root/'runtime/ppu',tmp)] ++ subprocess.run([os.environ.get('CC','cc'),'-std=gnu17','-O1','-UNDEBUG',*includes,'-c',str(root/'libs/codec/cellSail.c'),'-o',str(tmp/'sail.o')],check=True,timeout=30) ++ subprocess.run([os.environ.get('CXX','c++'),'-std=c++17','-O1','-UNDEBUG',*includes,str(root/'tests/test_sail_memory_allocator.cpp'),str(root/'runtime/ppu/ppu_hle.cpp'),str(tmp/'nids.cpp'),str(tmp/'sail.o'),'-o',str(tmp/'fixture')],check=True,timeout=45) ++ env={k:v for k,v in os.environ.items() if k in ('PATH','HOME','TMPDIR','SYSTEMROOT')} ++ subprocess.run([str(tmp/'fixture')],env=env,check=True,timeout=10) ++ return 0 ++if __name__=='__main__': ++ raise SystemExit(main()) diff --git a/tasks/sp00nznet__ps3recomp-653/solution/solve.sh b/tasks/sp00nznet__ps3recomp-653/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-653/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-653/task.toml b/tasks/sp00nznet__ps3recomp-653/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7f4694be5238311607ec9386488214a3880f9801 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-653/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-653" +description = "sail: retain the allocator argument in its embedded callback record" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/653" +source_access = "auto" +built_at = "2026-11-16T16:09:59.738165+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ead8b6263567250e6d3c37de35720a911c36ee2e0f855e407165e1feac5b1426" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/codec/cellSail.c", + "libs/codec/cellSail.h", + "tests/test_sail_memory_allocator.cpp", + "tools/test_sail_memory_allocator.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 156 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.146419+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-653/tests/capture.py b/tasks/sp00nznet__ps3recomp-653/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-653/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-653/tests/instruction.md b/tasks/sp00nznet__ps3recomp-653/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b52cd44155b4b6deb171530545392b8e9a3fc3b4 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-653/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** sail: retain the allocator argument in its embedded callback record + +## Description + +cellSailMemAllocatorInitialize drops the third argument and its public declarations describe host-sized pointers. Represent the guest allocator as two embedded 32-bit callback OPDs plus the 32-bit argument, copy both callbacks by value, and store pArg at offset 8. Validate the 12-byte destination and 8-byte input before writing, and read both callback words before overlapping output stores. + +The actual generated NID registration and PPU HLE dispatcher run 20 checks for exact byte layout, pArg preservation, canaries, invalid guest ranges/alignment, and overlapping input/output. The unmodified upstream control fails on the dropped pArg. Compile-time size checks enforce 8-byte callbacks and a 12-byte allocator record. + +Validation commands: + +```sh +python3 tools/test_sail_memory_allocator.py +``` + +Local focused checks pass on Apple Silicon macOS with AppleClang 17 and Python 3.14. The six candidates, including the subsequent CI repairs, also merge cleanly together, build in Release with PS3RECOMP_BUILD_TESTS=ON, and pass 22/22 CTest tests. That full runtime build and CTest result belong to the combined validation checkout. POSIX-only Python compiler harnesses explicitly skip Windows; the standard hosted Windows build and its other checks provide separate platform coverage. + +SDK 4.00 `cell/target/ppu/include/cell/sail/common.h`, CellSailMemAllocatorFuncs, CellSailMemAllocator, and cellSailMemAllocatorInitialize: callbacks are embedded, followed by pArg; the header declares three arguments. The same release's CHM initializer topic still shows two arguments, so the header is the precise declaration used here. This corrects the fork's eight-byte callback-table-pointer assumption rather than exporting it. No SDK source, game binaries or capture bytes are included. Descriptor/player lifetime handling is outside this standalone fix. + +Based directly on upstream master `4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514` (v0.18.0). No dependency on another proposed PR. + +CI follow-up: the first hosted macOS jobs were canceled before executing because of GitHub's scheduled macOS 14 runner-image brownout. A separate commit moves the existing arm64 matrix to `macos-15`, retaining its architecture checks. See Hosted checks are being monitored on the updated head. + +Additional CI repairs: the existing FIFO-walker profiler now stops against an elapsed monotonic deadline instead of counting requested one-millisecond sleeps. Its regression includes forced 20 ms wakeups and validates a nonempty consistent profile without assuming the host delivers 1 kHz. The delayed-wakeup control fails before the repair and passes after it. + +Hosted CI at published head `c3a6469b3ab0673344da44dd7f6e3a20f0f3a9d7`: all 10 jobs pass, covering Linux GCC/Clang Debug and Release, Windows Debug and Release, macOS arm64 Debug and Release, and Vulkan on lavapipe with GCC and Clang. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-653/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-653/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7ed43a35db64c794b4dc5a994496de071338504f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-653/tests/oracle.patch @@ -0,0 +1,199 @@ +diff --git a/libs/codec/cellSail.c b/libs/codec/cellSail.c +index df6d4b38..b29ce167 100644 +--- a/libs/codec/cellSail.c ++++ b/libs/codec/cellSail.c +@@ -566,21 +566,23 @@ s32 cellSailGraphicsAdapterSetPreferredFormat(u32 pSelf, u32 pFormat) + } + + s32 cellSailMemAllocatorInitialize(CellSailMemAllocator* allocator, +- CellSailMemAllocatorFuncs* pFuncs) +-{ +- /* Both parameters are GUEST addresses, and both structs live in GUEST +- * memory with 32-bit big-endian pointers. Dereferencing them as host +- * structs was wrong twice over: the address was never translated, and the +- * host struct has 64-bit fields, so even the offsets did not line up. The +- * values stored here are guest OPD addresses that SAIL calls back into. */ +- u32 alloc_ea = (u32)(uintptr_t)allocator; +- u32 funcs_ea = (u32)(uintptr_t)pFuncs; +- printf("[cellSail] MemAllocatorInitialize(allocator=0x%08X funcs=0x%08X)\n", +- alloc_ea, funcs_ea); +- if (!alloc_ea) return (s32)CELL_SAIL_ERROR_INVALID_ARGUMENT; +- if (funcs_ea) { +- vm_write32(alloc_ea + 0, vm_read32(funcs_ea + 0)); /* pAlloc */ +- vm_write32(alloc_ea + 4, vm_read32(funcs_ea + 4)); /* pFree */ +- } ++ CellSailMemAllocatorFuncs* pFuncs, void* pArg) ++{ ++ /* These arguments are guest EAs, not host records. Copy the two callback ++ * OPDs by value and preserve the third argument in the twelve-byte record. ++ * Read both callbacks first so overlapping input/output remains safe. */ ++ const u64 alloc_ea = (u64)(uintptr_t)allocator; ++ const u64 funcs_ea = (u64)(uintptr_t)pFuncs; ++ extern u32 ppu_vm_size; ++ const u64 limit = ppu_vm_size ? ppu_vm_size : 0x100000000ull; ++ if (!vm_base || !alloc_ea || !funcs_ea || (alloc_ea & 3) || (funcs_ea & 3) || ++ alloc_ea > limit || funcs_ea > limit || ++ 12 > limit - alloc_ea || 8 > limit - funcs_ea) ++ return (s32)0x80610701u; ++ const u32 alloc_opd = vm_read32((u32)funcs_ea); ++ const u32 free_opd = vm_read32((u32)funcs_ea + 4); ++ vm_write32((u32)alloc_ea, alloc_opd); ++ vm_write32((u32)alloc_ea + 4, free_opd); ++ vm_write32((u32)alloc_ea + 8, (u32)(uintptr_t)pArg); + return CELL_OK; + } +diff --git a/libs/codec/cellSail.h b/libs/codec/cellSail.h +index 5224eb38..073b0207 100644 +--- a/libs/codec/cellSail.h ++++ b/libs/codec/cellSail.h +@@ -122,20 +122,18 @@ s32 cellSailDescriptorGetStreamType(CellSailDescriptorHandle desc, s32* type); + s32 cellSailDescriptorSetAutoSelection(CellSailDescriptorHandle desc, s32 enable); + s32 cellSailDescriptorGetUri(CellSailDescriptorHandle desc, char* uri, u32 maxLen); + +-/* Memory allocator */ +-typedef struct CellSailMemAllocator { +- void* (*alloc)(void* arg, u32 boundary, u32 size); +- void (*free)(void* arg, u32 boundary, void* ptr); +- void* arg; +-} CellSailMemAllocator; +- +-/* Mirrors RPCS3's CellSailMemAllocatorFuncs: a guest struct of two callback +- * pointers, passed as one pointer arg (not two separate function pointers). */ ++/* Guest storage layout: 32-bit big-endian callback OPDs followed by pArg. ++ * SDK 4.00 cell/sail/common.h embeds the callback pair by value. */ + typedef struct CellSailMemAllocatorFuncs { +- void* pAlloc; +- void* pFree; ++ u32 pAlloc; ++ u32 pFree; + } CellSailMemAllocatorFuncs; + ++typedef struct CellSailMemAllocator { ++ CellSailMemAllocatorFuncs callbacks; ++ u32 pArg; ++} CellSailMemAllocator; ++ + /* Named pFuncs (not "callbacks") so the import-bridge generator's naming + * heuristic (gen_imports.py param_marshal) treats this as a real guest + * struct pointer needing host-pointer translation, not a raw callback value. */ +@@ -143,7 +141,7 @@ s32 cellSailPlayerInitialize2(u32 pSelf, u32 pAllocator, u32 pCallback, + u32 pUserParam, u32 pAttribute, u32 pResource); + s32 cellSailSoundAdapterInitialize(u32 pSelf, u32 pCallbacks, u32 pArg); + s32 cellSailMemAllocatorInitialize(CellSailMemAllocator* allocator, +- CellSailMemAllocatorFuncs* pFuncs); ++ CellSailMemAllocatorFuncs* pFuncs, void* pArg); + + #ifdef __cplusplus + } +diff --git a/tests/test_sail_memory_allocator.cpp b/tests/test_sail_memory_allocator.cpp +new file mode 100644 +index 00000000..5dec5dc2 +--- /dev/null ++++ b/tests/test_sail_memory_allocator.cpp +@@ -0,0 +1,71 @@ ++/* Exercise generated NID registration and the real PPU HLE bridge. */ ++#include "ppu_context.h" ++#include "../libs/codec/cellSail.h" ++#include "ps3emu/guest_call.h" ++#include <cstdio> ++#include <cstdlib> ++#include <cstring> ++#include <cstdint> ++ ++extern "C" { ++uint8_t* vm_base; ++uint32_t ppu_vm_size=0x10000; ++uint32_t g_ww_lo=0,g_ww_hi=0; ++int g_resv_store_active=0; ++ps3_guest_caller_fn g_ps3_guest_caller=nullptr; ++void ppu_hle_register_all(); ++int ps3_hle_has(uint32_t); ++void ps3_hle_call(uint32_t,ppu_context*); ++int cellfs_translate_path(const char*,char*,size_t) { return -1; } ++int32_t cellPamfReaderInitialize(void*,void*,uint64_t,uint32_t) { std::abort(); } ++int32_t cellPamfReaderGetStreamIndex(void*) { std::abort(); } ++uint32_t prx_resolve_export(uint32_t) { return 0; } ++void ps3_indirect_call(ppu_context*) { std::abort(); } ++uint64_t ppu_guest_call(uint32_t,uint64_t,uint64_t,uint64_t,uint64_t,uint64_t,uint64_t,uint64_t,uint64_t) { std::abort(); } ++void ppu_prof_stamp(void*,unsigned) {} ++void ppu_gcm_pump() {} ++uint32_t ppu_prof_resolve_host(void*) { return 0; } ++void ps3_msf(const char*,...) {} ++int spu_coh_is_reserved(uint32_t) { return 0; } ++void spu_coh_notify_write(uint32_t) {} ++void spu_lockline_lock() {} ++void spu_lockline_unlock() {} ++void ppu_resv_break_store(uint64_t) {} ++void ps3_ww_report_inline(uint32_t,uint64_t,int) {} ++uint32_t vm_read32(uint64_t a) { uint32_t x;std::memcpy(&x,vm_base+a,4);return __builtin_bswap32(x); } ++void vm_write32(uint64_t a,uint32_t x) { x=__builtin_bswap32(x);std::memcpy(vm_base+a,&x,4); } ++} ++extern "C" uint64_t vm_read64(uint64_t a) { uint64_t x;std::memcpy(&x,vm_base+a,8);return __builtin_bswap64(x); } ++void vm_write64(uint64_t a,uint64_t x) { x=__builtin_bswap64(x);std::memcpy(vm_base+a,&x,8); } ++extern "C" void ppu_dump_guest_stack(ppu_context*,const char*) {} ++extern "C" void ppu_dump_bctrl_ring(uint32_t,const char*) {} ++extern "C" void ppu_guest_callstack(const char*) {} ++uint32_t g_ydkj_real_spurs_ea=0,g_ydkj_real_taskset_ea=0; ++ ++static_assert(sizeof(CellSailMemAllocatorFuncs)==8, "guest callback pair"); ++static_assert(sizeof(CellSailMemAllocator)==12, "guest allocator record"); ++static unsigned checks; ++#define CHECK(x) do { ++checks; if(!(x)) { std::fprintf(stderr,"FAIL line%d: %s\n",__LINE__,#x);return 1; } } while(0) ++static uint32_t call(uint32_t nid,uint64_t a=0,uint64_t b=0,uint64_t c=0,uint64_t d=0,uint64_t e=0) { ++ ppu_context ctx{};ctx.gpr[1]=0x8000;ctx.gpr[2]=0x12345678; ++ ctx.gpr[3]=a;ctx.gpr[4]=b;ctx.gpr[5]=c;ctx.gpr[6]=d;ctx.gpr[7]=e; ++ ps3_hle_call(nid,&ctx);if(ctx.gpr[2]!=0x12345678)std::abort();return uint32_t(ctx.gpr[3]); ++} ++int main() { ++ static uint8_t memory[0x10000];vm_base=memory;ppu_hle_register_all(); ++ constexpr uint32_t INIT=0x346EBBA3,ARG=0x80610701; ++ vm_write32(0x1000,0xDEADBEEF);vm_write32(0x1004,0xDEADBEEF);vm_write32(0x1008,0xDEADBEEF);vm_write32(0x100C,0x55667788); ++ vm_write32(0x2000,0x3000);vm_write32(0x2004,0x4000); ++ CHECK(ps3_hle_has(INIT));CHECK(call(INIT,0x1000,0x2000,0x11223344)==0); ++ CHECK(vm_read32(0x1000)==0x3000);CHECK(vm_read32(0x1004)==0x4000);CHECK(vm_read32(0x1008)==0x11223344);CHECK(vm_read32(0x100C)==0x55667788); ++ CHECK(call(INIT,0,0x2000)==ARG);CHECK(call(INIT,0x1001,0x2000)==ARG); ++ CHECK(call(INIT,0xFFFC,0x2000)==ARG);CHECK(call(INIT,0x1000,0)==ARG); ++ CHECK(call(INIT,0x1000,0x2001)==ARG);CHECK(call(INIT,0x1000,0xFFFC)==ARG); ++ CHECK(vm_read32(0x1000)==0x3000);CHECK(vm_read32(0x1004)==0x4000);CHECK(vm_read32(0x1008)==0x11223344); ++ // Copy callbacks before storing: destination may overlap the input table. ++ vm_write32(0x3004,0x5000);vm_write32(0x3008,0x6000); ++ CHECK(call(INIT,0x3000,0x3004,0x77889900)==0); ++ CHECK(vm_read32(0x3000)==0x5000);CHECK(vm_read32(0x3004)==0x6000);CHECK(vm_read32(0x3008)==0x77889900); ++ CHECK(call(INIT,0xFFF8,0x2000)==ARG); ++ std::printf("%u allocator layout checks PASS\n",checks);return 0; ++} +diff --git a/tools/test_sail_memory_allocator.py b/tools/test_sail_memory_allocator.py +new file mode 100644 +index 00000000..9328435a +--- /dev/null ++++ b/tools/test_sail_memory_allocator.py +@@ -0,0 +1,29 @@ ++#!/usr/bin/env python3 ++"""Compile/run real Sail and generated NID registration through the PPU HLE bridge.""" ++import os ++from pathlib import Path ++import subprocess ++import sys ++import tempfile ++from gen_hle_nids import scan ++ ++root=Path(__file__).resolve().parents[1] ++ ++def main(): ++ if os.name=='nt': ++ print('SKIP: standalone HLE bridge regression needs a POSIX toolchain') ++ return 0 ++ handlers=dict(scan(root/'libs/codec/cellSail.c')) ++ assert handlers.get(0x346EBBA3)=='cellSailMemAllocatorInitialize','Allocator is not registered' ++ with tempfile.TemporaryDirectory(prefix='ps3-sail-descriptor-') as tmp: ++ tmp=Path(tmp) ++ (tmp/'ppu_recomp.h').write_text('#include "ppu_context.h"\n') ++ subprocess.run([sys.executable,str(root/'tools/gen_hle_nids.py'),'cellSail','--out',str(tmp/'nids.cpp')],check=True,timeout=15) ++ includes=['-I'+str(p) for p in (root/'include',root/'runtime/ppu',tmp)] ++ subprocess.run([os.environ.get('CC','cc'),'-std=gnu17','-O1','-UNDEBUG',*includes,'-c',str(root/'libs/codec/cellSail.c'),'-o',str(tmp/'sail.o')],check=True,timeout=30) ++ subprocess.run([os.environ.get('CXX','c++'),'-std=c++17','-O1','-UNDEBUG',*includes,str(root/'tests/test_sail_memory_allocator.cpp'),str(root/'runtime/ppu/ppu_hle.cpp'),str(tmp/'nids.cpp'),str(tmp/'sail.o'),'-o',str(tmp/'fixture')],check=True,timeout=45) ++ env={k:v for k,v in os.environ.items() if k in ('PATH','HOME','TMPDIR','SYSTEMROOT')} ++ subprocess.run([str(tmp/'fixture')],env=env,check=True,timeout=10) ++ return 0 ++if __name__=='__main__': ++ raise SystemExit(main()) diff --git a/tasks/sp00nznet__ps3recomp-653/tests/test.sh b/tasks/sp00nznet__ps3recomp-653/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-653/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-653/tests/verifier.py b/tasks/sp00nznet__ps3recomp-653/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-653/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-654/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-654/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-654/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-654/instruction.md b/tasks/sp00nznet__ps3recomp-654/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b52aa1b3b34818cc51a0839ced79adb82907e251 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-654/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** spu: reject unrelated large GETs in address-only overlay registries + +## Description + +The existing small-GET prefilter still scans every overlay source for large GETs even when the registry has no signature entries. Publish a monotonic signature-present flag before the source count and extend the exact-EA rejection to all sizes in address-only registries. Destination residency invalidation still runs before rejection; signature matching and registration order remain intact. + +The production runtime fixture passes 12 optimized/UBSan combinations: core and full registry cases with the dispatch cache off, on and in shadow mode. It covers matching addresses, zero EA, 4 through 16384-byte transfers, overwritten resident code, fixed-load matching, list-stall resume and signature publication. Four deliberately broken controls are rejected. The unmodified-upstream control fails on unnecessary large-GET scans. + +Validation commands: + +```sh +python3 tools/test_spu_overlay_allsize.py --mutants +``` + +Local focused checks pass on Apple Silicon macOS with AppleClang 17 and Python 3.14. The six candidates, including the subsequent CI repairs, also merge cleanly together, build in Release with PS3RECOMP_BUILD_TESTS=ON, and pass 22/22 CTest tests. That full runtime build and CTest result belong to the combined validation checkout. POSIX-only Python compiler harnesses explicitly skip Windows; the standard hosted Windows build and its other checks provide separate platform coverage. + +This extends the source prefilter already merged from PR #455. No new firmware behavior is inferred and no application FPS gain is claimed. Registration keeps its existing single-writer contract. Private-only verified-overlay/cache-epoch APIs were omitted from the upstream fixture; current upstream residency, lookup and DMA paths are exercised directly. + +Based directly on upstream master `4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514` (v0.18.0). No dependency on another proposed PR. + +CI follow-up: the first hosted macOS jobs were canceled before executing because of GitHub's scheduled macOS 14 runner-image brownout. A separate commit moves the existing arm64 matrix to `macos-15`, retaining its architecture checks. See Hosted checks are being monitored on the updated head. + +Additional CI repairs: the existing FIFO-walker profiler now stops against an elapsed monotonic deadline instead of counting requested one-millisecond sleeps. Its regression includes forced 20 ms wakeups and validates a nonempty consistent profile without assuming the host delivers 1 kHz. The delayed-wakeup control fails before the repair and passes after it. + +Hosted CI at published head `84efbb212889b31aaade6a08061c67dd73b475c2`: all 10 jobs pass, covering Linux GCC/Clang Debug and Release, Windows Debug and Release, macOS arm64 Debug and Release, and Vulkan on lavapipe with GCC and Clang. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-654/solution/patch.diff b/tasks/sp00nznet__ps3recomp-654/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ca94a97acb40d0743bf5effb489a7ccd63eb4979 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-654/solution/patch.diff @@ -0,0 +1,277 @@ +diff --git a/runtime/spu/spu_channels.c b/runtime/spu/spu_channels.c +index 5fc50208..46ae783d 100644 +--- a/runtime/spu/spu_channels.c ++++ b/runtime/spu/spu_channels.c +@@ -1848,6 +1848,10 @@ typedef struct { uint32_t src_ea; int image_id; uint8_t sig[16]; int has_sig; ui + #define SPU_OVL_SRC_MAX 128 + static spu_ovl_src s_ovl_src[SPU_OVL_SRC_MAX]; + static int s_ovl_src_count = 0; ++/* Monotonic: published before any signature entry becomes visible through ++ * s_ovl_src_count. A reader that acquired that count cannot miss the flag. ++ * This lets EA-only registries reject unrelated GETs of every size. */ ++static atomic_int s_ovl_has_sig; + + /* Every MFC GET is checked against the registered sources, and a job that + * streams its data in small pieces issues thousands of GETs a frame against +@@ -2071,7 +2075,8 @@ void spu_overlay_register_sig(const uint8_t sig[16], int image_id) + s_ovl_src[s_ovl_src_count].image_id = image_id; + memcpy(s_ovl_src[s_ovl_src_count].sig, sig, 16); + s_ovl_src[s_ovl_src_count].has_sig = 1; +- s_ovl_src_count++; ++ atomic_store_explicit(&s_ovl_has_sig, 1, memory_order_release); ++ __atomic_store_n(&s_ovl_src_count, s_ovl_src_count + 1, __ATOMIC_RELEASE); + } + } + +@@ -2148,7 +2153,12 @@ void spu_overlay_note_get(spu_context* ctx, uint32_t ea, const uint8_t* ls, uint + } + } + int nsrc = __atomic_load_n(&s_ovl_src_count, __ATOMIC_ACQUIRE); +- if (size < 512 && !spu_ovl_ea_known(ea)) return; ++ /* Invalidate destination code/residency above even for an unrelated EA. ++ * Acquire count before the signature flag: if this snapshot contains a ++ * signature, its earlier flag publication is visible. A racing future ++ * signature can only force an unnecessary scan of the older snapshot. */ ++ if ((size < 512 || !atomic_load_explicit(&s_ovl_has_sig, memory_order_acquire)) && ++ !spu_ovl_ea_known(ea)) return; + for (int i = 0; i < nsrc; i++) { + const spu_ovl_src* o = &s_ovl_src[i]; + int hit = o->has_sig ? (size >= 512 && memcmp(ls, o->sig, 16) == 0) +diff --git a/runtime/spu/tests/test_spu_overlay_allsize.c b/runtime/spu/tests/test_spu_overlay_allsize.c +new file mode 100644 +index 00000000..5b1fda90 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_overlay_allsize.c +@@ -0,0 +1,142 @@ ++/* Real runtime; temporary source instrumentation observes discovery work and ++ * single-writer publication boundaries without adding production test hooks. */ ++#define main allsize_unused_mfc_main ++#include "allsize_fixture.h" ++#undef main ++ ++static spu_context* signature_ctx; ++static int publication_checks; ++static const uint8_t signature[16]={0xa1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; ++static void lifted(spu_context* c){c->gpr[3]._u32[0]=42;} ++static spu_context* fresh(void) ++{ ++ spu_context* c=calloc(1,sizeof(*c));CHECK(c!=NULL); ++ spu_context_init(c,0);c->image_id=501;return c; ++} ++void allsize_sig_published(void) ++{ ++ if(!signature_ctx)return; ++ /* A reader admitted immediately at count publication must not falsely ++ * reject a signature whose flag was published too late. */ ++ signature_ctx->resident_ovl=0; ++ spu_overlay_note_get(signature_ctx,0x77000040,signature_ctx->ls+0x20000,512); ++ CHECK(signature_ctx->resident_ovl==777);++publication_checks; ++} ++static void absence_and_hits(spu_context* c) ++{ ++ for(unsigned i=0;i<30;++i)spu_overlay_register_source(0x70000000+i*0x10000,600+i); ++ spu_overlay_register_source(0,650); ++ spu_overlay_register_source(0x70000000,651); /* first matching source wins */ ++ static const unsigned sizes[]={4,16,128,511,512,1024,16384}; ++ for(unsigned k=0;k<sizeof sizes/sizeof sizes[0];++k){ ++ allsize_scans=0;c->resident_ovl=17; ++ spu_overlay_note_get(c,0x78000000,c->ls+0x20000,sizes[k]); ++ CHECK(c->resident_ovl==17);CHECK(allsize_scans==0); ++ allsize_scans=0;c->resident_ovl=0; ++ spu_overlay_note_get(c,0x70000000,c->ls+0x20000,sizes[k]); ++ CHECK(c->resident_ovl==600);CHECK(allsize_scans>0); ++ c->resident_ovl=0;spu_overlay_note_get(c,0,c->ls+0x20000,sizes[k]); ++ CHECK(c->resident_ovl==650); ++ } ++} ++static void residency_and_epochs(spu_context* c) ++{ ++ const uint32_t base=0x10000,source=0x71000000; ++ static const uint8_t code[]={0x11,2,3,4,5,6,7,8}; ++ const spu_overlay_code_segment seg={base,sizeof code,code}; ++ spu_begin_image(701);spu_register_function(base,lifted);spu_begin_image(0); ++ CHECK(spu_overlay_register_verified_region(source,base,0x400,701,&seg,1)); ++ memcpy(c->ls+base,code,sizeof code); ++ spu_overlay_note_get(c,source,c->ls+base,512); ++ CHECK(spu_lifted_lookup(c,base)==lifted); ++ CHECK(c->resident_code[0].verify_state==SPU_OVERLAY_VERIFIED); ++ uint32_t epoch=c->dcache_residency; ++ /* A continuation's EA is not a registered source: negative discovery ++ * must still reset verification, and changed code must fail validation. */ ++ c->ls[base+4]^=0xff;allsize_scans=0; ++ spu_overlay_note_get(c,source+4,c->ls+base+4,512); ++ CHECK(allsize_scans==0);CHECK(c->dcache_residency!=epoch); ++ CHECK(c->resident_code[0].verify_state==SPU_OVERLAY_PENDING); ++ CHECK(spu_lifted_lookup(c,base)==NULL); ++ memcpy(c->ls+base,code,sizeof code); ++ spu_overlay_note_get(c,source,c->ls+base,512); ++ CHECK(spu_lifted_lookup(c,base)==lifted); ++ /* Partial foreign overwrite starts below the resident range. */ ++ epoch=c->dcache_residency; ++ spu_overlay_note_get(c,0x79000000,c->ls+base-16,512); ++ CHECK(!c->resident_code[0].image_id);CHECK(c->dcache_residency!=epoch); ++ ++ ++} ++static void old_matcher_edges(spu_context* c) ++{ ++ /* An early exact-EA hit with a wrong fixed load must continue to the ++ * later exact-EA hit, rather than adopting the first indexed source. */ ++ static const uint8_t code[]={1,2,3,4}; ++ const spu_overlay_code_segment a={0x24000,4,code},b={0x25000,4,code}; ++ CHECK(spu_overlay_register_verified_region(0x72000000,0x24000,0x400,710,&a,1)); ++ CHECK(spu_overlay_register_verified_region(0x72000000,0x25000,0x400,711,&b,1)); ++ memset(c->resident_code,0,sizeof c->resident_code); ++ spu_overlay_note_get(c,0x72000000,c->ls+0x25000,512); ++ CHECK(c->resident_code[0].image_id==711); ++ spu_overlay_register_region(0x73000000,0x400,712); ++ memset(c->resident_code,0,sizeof c->resident_code);c->resident_ovl=19; ++ spu_overlay_note_get(c,0x73000000,c->ls+SPU_LS_SIZE-0x100,16); ++ CHECK(!c->resident_code[0].image_id && c->resident_ovl==19); ++ for(unsigned i=0;i<4;++i){c->resident_code[i].image_id=800+i;c->resident_code[i].lsa=0x3000+i*0x100;c->resident_code[i].size=16;} ++ spu_overlay_note_get(c,0x73000000,c->ls+0x27000,512); ++ for(unsigned i=0;i<4;++i)CHECK(c->resident_code[i].image_id==(int)(800+i)); ++ memset(c->resident_code,0,sizeof c->resident_code); ++} ++static void list_resume(spu_context* c) ++{ ++ memset(guest_memory+0x21000,0x51,512);memset(guest_memory+0x22000,0x62,512); ++ spu_ls_write32(c,0x3000,512);spu_ls_write32(c,0x3004,0x21000); ++ spu_ls_write32(c,0x3008,0x80000000);spu_ls_write32(c,0x300c,0); ++ spu_ls_write32(c,0x3010,512);spu_ls_write32(c,0x3014,0x22000); ++ mfc_engine* m=mfc_for(c);m->tag_completed&=~(1u<<4); ++ c->mfc_lsa=0x28000;c->mfc_eal=0x3000;c->mfc_size=24;c->mfc_tag=4; ++ CHECK(mfc_submit(m,c,0x44)==0); ++ CHECK(c->ls[0x28000]==0x51 && c->ls[0x28200]==0); ++ CHECK(c->list_stall_mask==(1u<<4) && !(m->tag_completed&(1u<<4))); ++ CHECK(c->event_status&2);CHECK(c->list_stall_dest_lsa[4]==0x28200); ++ /* Resume must read this modified remaining element live. */ ++ spu_ls_write32(c,0x3014,0x21000); ++ CHECK(mfc_list_stall_ack(m,c,4)==0); ++ CHECK(c->ls[0x28200]==0x51 && !c->list_stall_mask); ++ CHECK(m->tag_completed&(1u<<4)); ++} ++static void signatures(spu_context* c) ++{ ++ memcpy(c->ls+0x20000,signature,16);signature_ctx=c; ++ spu_overlay_register_sig(signature,777);signature_ctx=NULL; ++ CHECK(publication_checks==1); ++ c->resident_ovl=19;spu_overlay_note_get(c,0x77000040,c->ls+0x20000,511); ++ CHECK(c->resident_ovl==19); ++ spu_overlay_note_get(c,0x77000040,c->ls+0x20000,512); ++ CHECK(c->resident_ovl==777); ++ CHECK(spu_overlay_match_sig(signature)==777); ++ /* Known EA and signature both match: registration order remains exact. */ ++ spu_overlay_note_get(c,0x70000000,c->ls+0x20000,512); ++ CHECK(c->resident_ovl==600); ++} ++int main(int argc,char** argv) ++{ ++ spu_context* c=fresh(); ++ if(argc>1 && !strcmp(argv[1],"full")){ ++ for(unsigned i=0;i<128;++i)spu_overlay_register_source(0x70000000+i*0x10000,600+i); ++ unsigned count=s_ovl_src_count; ++ /* Rejection must occur before reading the inaccessible signature. */ ++ spu_overlay_register_sig((const uint8_t*)(uintptr_t)1,999); ++ CHECK(s_ovl_src_count==(int)count); ++ allsize_scans=0;c->resident_ovl=19; ++ spu_overlay_note_get(c,0x78000000,c->ls+0x20000,512); ++ CHECK(c->resident_ovl==19);CHECK(allsize_scans==0); ++ }else{ ++ absence_and_hits(c);residency_and_epochs(c);old_matcher_edges(c); ++ list_resume(c);signatures(c); ++ } ++ spu_mfc_release(c);free(c); ++ printf("OVERLAY_ALLSIZE passed=%d failed=%d\n",g_pass,g_fail); ++ return g_fail?1:0; ++} +diff --git a/tools/test_spu_overlay_allsize.py b/tools/test_spu_overlay_allsize.py +new file mode 100644 +index 00000000..02bd7419 +--- /dev/null ++++ b/tools/test_spu_overlay_allsize.py +@@ -0,0 +1,84 @@ ++#!/usr/bin/env python3 ++"""Real GET discovery, residency/code epochs, list stalls and publication. ++ ++Only temporary source copies acquire counters/publication observation points. ++--output-dir retains the exact compiled binaries, argv and output for review. ++""" ++import argparse,json,os,pathlib,subprocess,tempfile ++if os.name == 'nt': ++ print('SKIP: standalone runtime fixture requires a POSIX compiler') ++ raise SystemExit(0) ++ROOT=pathlib.Path(__file__).resolve().parents[1];SPU=ROOT/'runtime/spu' ++parser=argparse.ArgumentParser() ++parser.add_argument('--output-dir',type=pathlib.Path) ++parser.add_argument('--source',type=pathlib.Path) ++parser.add_argument('--mutants',action='store_true') ++args=parser.parse_args() ++units=['spu_drain','spu_lockstep','spu_coherency','spu_workload','spurs_policy','spurs_job','spu_tsp_weak','spu_vm_pagemap','spurs_policy_blob_weak','spu_interp'] ++env={k:v for k,v in os.environ.items() if not k.startswith(('SPU_','SPURS_','YDKJ_','LBP_','GH3_'))} ++source=(args.source or SPU/'spu_channels.c').read_text() ++def instrument(text): ++ text=text.replace('#include "../','#include "'+str(SPU.parent)+'/') ++ needle='for (int i = 0; i < nsrc; i++) {' ++ assert text.count(needle)==1 ++ text=text.replace(needle,needle+'\n ++allsize_scans;') ++ start=text.index('void spu_overlay_register_sig(') ++ end=text.index('\n}',start) ++ body=text[start:end] ++ needle='__atomic_store_n(&s_ovl_src_count, s_ovl_src_count + 1, __ATOMIC_RELEASE);' ++ if needle not in body:needle='s_ovl_src_count++;' ++ assert body.count(needle)==1 ++ text=text[:start]+body.replace(needle,needle+'\n allsize_sig_published();')+text[end:] ++ return 'static unsigned allsize_scans;\nvoid allsize_sig_published(void);\n'+text ++def run(work): ++ fixture=(SPU/'tests/test_spu_mfc_slots.c').read_text() ++ fixture=fixture.replace('#include "../spu_channels.c"','#include "allsize_channels.c"') ++ fixture=fixture.replace('#include "../spu_lifted_job.h"','#include "'+str(SPU/'spu_lifted_job.h')+'"') ++ (work/'allsize_fixture.h').write_text(fixture) ++ records=[] ++ def variant(name,text,sanitize=False): ++ where=work/name;where.mkdir(exist_ok=True) ++ (where/'allsize_channels.c').write_text(instrument(text)) ++ exe=where/'fixture' ++ cmd=[os.environ.get('CC','cc'),'-std=gnu17','-O2','-UNDEBUG'] ++ if sanitize:cmd+=['-fsanitize=undefined','-fno-sanitize-recover=all'] ++ cmd+=['-I'+str(where),'-I'+str(work),'-I'+str(ROOT/'include'),'-I'+str(SPU),'-I'+str(ROOT/'runtime/platform'),str(SPU/'tests/test_spu_overlay_allsize.c'),*[str(SPU/(u+'.c')) for u in units],str(ROOT/'runtime/platform/win32_compat.c'),'-pthread','-lm','-o',str(exe)] ++ (where/'build-argv.json').write_text(json.dumps(cmd,indent=2)+'\n') ++ build=subprocess.run(cmd,capture_output=True,text=True,timeout=60) ++ (where/'build.stdout').write_text(build.stdout);(where/'build.stderr').write_text(build.stderr) ++ assert not build.returncode,build.stdout+build.stderr ++ results=[] ++ for mode in ['0','1','shadow']: ++ for case in ['core','full']: ++ argv=[str(exe),case] ++ r=subprocess.run(argv,env=dict(env,SPU_DISPATCH_CACHE=mode),capture_output=True,text=True,timeout=15) ++ label=mode+'-'+case ++ (where/(label+'.stdout')).write_text(r.stdout);(where/(label+'.stderr')).write_text(r.stderr) ++ records.append({'name':name,'mode':mode,'case':case,'argv':argv,'returncode':r.returncode}) ++ results.append(r) ++ print(name,mode,case,r.returncode,r.stdout.strip(),flush=True) ++ return results ++ good=True ++ for name,san in [('o2',False),('ubsan',True)]: ++ results=variant(name,source,san) ++ good=good and all(not r.returncode for r in results) ++ if args.mutants: ++ changes={ ++ 'reject-matches':('!spu_ovl_ea_known(ea)', '1'), ++ 'drop-residency':(' for (unsigned slot = 0; slot < 4; ++slot) {\n if (!ctx->resident_code[slot].image_id) continue;', ' for (unsigned slot = 4; slot < 4; ++slot) {\n if (!ctx->resident_code[slot].image_id) continue;'), ++ 'ignore-signatures':('!atomic_load_explicit(&s_ovl_has_sig, memory_order_acquire)', '1'), ++ 'late-signature-flag':(' atomic_store_explicit(&s_ovl_has_sig, 1, memory_order_release);\n __atomic_store_n(&s_ovl_src_count, s_ovl_src_count + 1, __ATOMIC_RELEASE);', ++ ' __atomic_store_n(&s_ovl_src_count, s_ovl_src_count + 1, __ATOMIC_RELEASE);\n atomic_store_explicit(&s_ovl_has_sig, 1, memory_order_release);'), ++ } ++ for name,(old,new) in changes.items(): ++ assert source.count(old)==1,(name,source.count(old)) ++ results=variant('mutant-'+name,source.replace(old,new)) ++ assert any(r.returncode and 'FAIL:' in r.stdout for r in results),name ++ print('PASS rejected bug control',name,flush=True) ++ (work/'runs.json').write_text(json.dumps(records,indent=2)+'\n') ++ if not good:raise SystemExit(1) ++ print('PASS real all-size overlay discovery preservation',flush=True) ++if args.output_dir: ++ args.output_dir.mkdir(parents=True,exist_ok=True);run(args.output_dir.resolve()) ++else: ++ with tempfile.TemporaryDirectory(prefix='spu-overlay-allsize-') as td:run(pathlib.Path(td)) diff --git a/tasks/sp00nznet__ps3recomp-654/solution/solve.sh b/tasks/sp00nznet__ps3recomp-654/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-654/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-654/task.toml b/tasks/sp00nznet__ps3recomp-654/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..66f68bde465ea12cc3dcfd3d8e0c52573550ab40 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-654/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-654" +description = "spu: reject unrelated large GETs in address-only overlay registries" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/654" +source_access = "auto" +built_at = "2026-11-16T16:09:59.646709+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:157454cf5fe90e79bd7c698b2b12de2ffca39bc3427b50b7cb067443de817907" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "runtime/spu/spu_channels.c", + "runtime/spu/tests/test_spu_overlay_allsize.c", + "tools/test_spu_overlay_allsize.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 240 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.146962+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-654/tests/capture.py b/tasks/sp00nznet__ps3recomp-654/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-654/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-654/tests/instruction.md b/tasks/sp00nznet__ps3recomp-654/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b52aa1b3b34818cc51a0839ced79adb82907e251 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-654/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** spu: reject unrelated large GETs in address-only overlay registries + +## Description + +The existing small-GET prefilter still scans every overlay source for large GETs even when the registry has no signature entries. Publish a monotonic signature-present flag before the source count and extend the exact-EA rejection to all sizes in address-only registries. Destination residency invalidation still runs before rejection; signature matching and registration order remain intact. + +The production runtime fixture passes 12 optimized/UBSan combinations: core and full registry cases with the dispatch cache off, on and in shadow mode. It covers matching addresses, zero EA, 4 through 16384-byte transfers, overwritten resident code, fixed-load matching, list-stall resume and signature publication. Four deliberately broken controls are rejected. The unmodified-upstream control fails on unnecessary large-GET scans. + +Validation commands: + +```sh +python3 tools/test_spu_overlay_allsize.py --mutants +``` + +Local focused checks pass on Apple Silicon macOS with AppleClang 17 and Python 3.14. The six candidates, including the subsequent CI repairs, also merge cleanly together, build in Release with PS3RECOMP_BUILD_TESTS=ON, and pass 22/22 CTest tests. That full runtime build and CTest result belong to the combined validation checkout. POSIX-only Python compiler harnesses explicitly skip Windows; the standard hosted Windows build and its other checks provide separate platform coverage. + +This extends the source prefilter already merged from PR #455. No new firmware behavior is inferred and no application FPS gain is claimed. Registration keeps its existing single-writer contract. Private-only verified-overlay/cache-epoch APIs were omitted from the upstream fixture; current upstream residency, lookup and DMA paths are exercised directly. + +Based directly on upstream master `4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514` (v0.18.0). No dependency on another proposed PR. + +CI follow-up: the first hosted macOS jobs were canceled before executing because of GitHub's scheduled macOS 14 runner-image brownout. A separate commit moves the existing arm64 matrix to `macos-15`, retaining its architecture checks. See Hosted checks are being monitored on the updated head. + +Additional CI repairs: the existing FIFO-walker profiler now stops against an elapsed monotonic deadline instead of counting requested one-millisecond sleeps. Its regression includes forced 20 ms wakeups and validates a nonempty consistent profile without assuming the host delivers 1 kHz. The delayed-wakeup control fails before the repair and passes after it. + +Hosted CI at published head `84efbb212889b31aaade6a08061c67dd73b475c2`: all 10 jobs pass, covering Linux GCC/Clang Debug and Release, Windows Debug and Release, macOS arm64 Debug and Release, and Vulkan on lavapipe with GCC and Clang. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-654/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-654/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ca94a97acb40d0743bf5effb489a7ccd63eb4979 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-654/tests/oracle.patch @@ -0,0 +1,277 @@ +diff --git a/runtime/spu/spu_channels.c b/runtime/spu/spu_channels.c +index 5fc50208..46ae783d 100644 +--- a/runtime/spu/spu_channels.c ++++ b/runtime/spu/spu_channels.c +@@ -1848,6 +1848,10 @@ typedef struct { uint32_t src_ea; int image_id; uint8_t sig[16]; int has_sig; ui + #define SPU_OVL_SRC_MAX 128 + static spu_ovl_src s_ovl_src[SPU_OVL_SRC_MAX]; + static int s_ovl_src_count = 0; ++/* Monotonic: published before any signature entry becomes visible through ++ * s_ovl_src_count. A reader that acquired that count cannot miss the flag. ++ * This lets EA-only registries reject unrelated GETs of every size. */ ++static atomic_int s_ovl_has_sig; + + /* Every MFC GET is checked against the registered sources, and a job that + * streams its data in small pieces issues thousands of GETs a frame against +@@ -2071,7 +2075,8 @@ void spu_overlay_register_sig(const uint8_t sig[16], int image_id) + s_ovl_src[s_ovl_src_count].image_id = image_id; + memcpy(s_ovl_src[s_ovl_src_count].sig, sig, 16); + s_ovl_src[s_ovl_src_count].has_sig = 1; +- s_ovl_src_count++; ++ atomic_store_explicit(&s_ovl_has_sig, 1, memory_order_release); ++ __atomic_store_n(&s_ovl_src_count, s_ovl_src_count + 1, __ATOMIC_RELEASE); + } + } + +@@ -2148,7 +2153,12 @@ void spu_overlay_note_get(spu_context* ctx, uint32_t ea, const uint8_t* ls, uint + } + } + int nsrc = __atomic_load_n(&s_ovl_src_count, __ATOMIC_ACQUIRE); +- if (size < 512 && !spu_ovl_ea_known(ea)) return; ++ /* Invalidate destination code/residency above even for an unrelated EA. ++ * Acquire count before the signature flag: if this snapshot contains a ++ * signature, its earlier flag publication is visible. A racing future ++ * signature can only force an unnecessary scan of the older snapshot. */ ++ if ((size < 512 || !atomic_load_explicit(&s_ovl_has_sig, memory_order_acquire)) && ++ !spu_ovl_ea_known(ea)) return; + for (int i = 0; i < nsrc; i++) { + const spu_ovl_src* o = &s_ovl_src[i]; + int hit = o->has_sig ? (size >= 512 && memcmp(ls, o->sig, 16) == 0) +diff --git a/runtime/spu/tests/test_spu_overlay_allsize.c b/runtime/spu/tests/test_spu_overlay_allsize.c +new file mode 100644 +index 00000000..5b1fda90 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_overlay_allsize.c +@@ -0,0 +1,142 @@ ++/* Real runtime; temporary source instrumentation observes discovery work and ++ * single-writer publication boundaries without adding production test hooks. */ ++#define main allsize_unused_mfc_main ++#include "allsize_fixture.h" ++#undef main ++ ++static spu_context* signature_ctx; ++static int publication_checks; ++static const uint8_t signature[16]={0xa1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; ++static void lifted(spu_context* c){c->gpr[3]._u32[0]=42;} ++static spu_context* fresh(void) ++{ ++ spu_context* c=calloc(1,sizeof(*c));CHECK(c!=NULL); ++ spu_context_init(c,0);c->image_id=501;return c; ++} ++void allsize_sig_published(void) ++{ ++ if(!signature_ctx)return; ++ /* A reader admitted immediately at count publication must not falsely ++ * reject a signature whose flag was published too late. */ ++ signature_ctx->resident_ovl=0; ++ spu_overlay_note_get(signature_ctx,0x77000040,signature_ctx->ls+0x20000,512); ++ CHECK(signature_ctx->resident_ovl==777);++publication_checks; ++} ++static void absence_and_hits(spu_context* c) ++{ ++ for(unsigned i=0;i<30;++i)spu_overlay_register_source(0x70000000+i*0x10000,600+i); ++ spu_overlay_register_source(0,650); ++ spu_overlay_register_source(0x70000000,651); /* first matching source wins */ ++ static const unsigned sizes[]={4,16,128,511,512,1024,16384}; ++ for(unsigned k=0;k<sizeof sizes/sizeof sizes[0];++k){ ++ allsize_scans=0;c->resident_ovl=17; ++ spu_overlay_note_get(c,0x78000000,c->ls+0x20000,sizes[k]); ++ CHECK(c->resident_ovl==17);CHECK(allsize_scans==0); ++ allsize_scans=0;c->resident_ovl=0; ++ spu_overlay_note_get(c,0x70000000,c->ls+0x20000,sizes[k]); ++ CHECK(c->resident_ovl==600);CHECK(allsize_scans>0); ++ c->resident_ovl=0;spu_overlay_note_get(c,0,c->ls+0x20000,sizes[k]); ++ CHECK(c->resident_ovl==650); ++ } ++} ++static void residency_and_epochs(spu_context* c) ++{ ++ const uint32_t base=0x10000,source=0x71000000; ++ static const uint8_t code[]={0x11,2,3,4,5,6,7,8}; ++ const spu_overlay_code_segment seg={base,sizeof code,code}; ++ spu_begin_image(701);spu_register_function(base,lifted);spu_begin_image(0); ++ CHECK(spu_overlay_register_verified_region(source,base,0x400,701,&seg,1)); ++ memcpy(c->ls+base,code,sizeof code); ++ spu_overlay_note_get(c,source,c->ls+base,512); ++ CHECK(spu_lifted_lookup(c,base)==lifted); ++ CHECK(c->resident_code[0].verify_state==SPU_OVERLAY_VERIFIED); ++ uint32_t epoch=c->dcache_residency; ++ /* A continuation's EA is not a registered source: negative discovery ++ * must still reset verification, and changed code must fail validation. */ ++ c->ls[base+4]^=0xff;allsize_scans=0; ++ spu_overlay_note_get(c,source+4,c->ls+base+4,512); ++ CHECK(allsize_scans==0);CHECK(c->dcache_residency!=epoch); ++ CHECK(c->resident_code[0].verify_state==SPU_OVERLAY_PENDING); ++ CHECK(spu_lifted_lookup(c,base)==NULL); ++ memcpy(c->ls+base,code,sizeof code); ++ spu_overlay_note_get(c,source,c->ls+base,512); ++ CHECK(spu_lifted_lookup(c,base)==lifted); ++ /* Partial foreign overwrite starts below the resident range. */ ++ epoch=c->dcache_residency; ++ spu_overlay_note_get(c,0x79000000,c->ls+base-16,512); ++ CHECK(!c->resident_code[0].image_id);CHECK(c->dcache_residency!=epoch); ++ ++ ++} ++static void old_matcher_edges(spu_context* c) ++{ ++ /* An early exact-EA hit with a wrong fixed load must continue to the ++ * later exact-EA hit, rather than adopting the first indexed source. */ ++ static const uint8_t code[]={1,2,3,4}; ++ const spu_overlay_code_segment a={0x24000,4,code},b={0x25000,4,code}; ++ CHECK(spu_overlay_register_verified_region(0x72000000,0x24000,0x400,710,&a,1)); ++ CHECK(spu_overlay_register_verified_region(0x72000000,0x25000,0x400,711,&b,1)); ++ memset(c->resident_code,0,sizeof c->resident_code); ++ spu_overlay_note_get(c,0x72000000,c->ls+0x25000,512); ++ CHECK(c->resident_code[0].image_id==711); ++ spu_overlay_register_region(0x73000000,0x400,712); ++ memset(c->resident_code,0,sizeof c->resident_code);c->resident_ovl=19; ++ spu_overlay_note_get(c,0x73000000,c->ls+SPU_LS_SIZE-0x100,16); ++ CHECK(!c->resident_code[0].image_id && c->resident_ovl==19); ++ for(unsigned i=0;i<4;++i){c->resident_code[i].image_id=800+i;c->resident_code[i].lsa=0x3000+i*0x100;c->resident_code[i].size=16;} ++ spu_overlay_note_get(c,0x73000000,c->ls+0x27000,512); ++ for(unsigned i=0;i<4;++i)CHECK(c->resident_code[i].image_id==(int)(800+i)); ++ memset(c->resident_code,0,sizeof c->resident_code); ++} ++static void list_resume(spu_context* c) ++{ ++ memset(guest_memory+0x21000,0x51,512);memset(guest_memory+0x22000,0x62,512); ++ spu_ls_write32(c,0x3000,512);spu_ls_write32(c,0x3004,0x21000); ++ spu_ls_write32(c,0x3008,0x80000000);spu_ls_write32(c,0x300c,0); ++ spu_ls_write32(c,0x3010,512);spu_ls_write32(c,0x3014,0x22000); ++ mfc_engine* m=mfc_for(c);m->tag_completed&=~(1u<<4); ++ c->mfc_lsa=0x28000;c->mfc_eal=0x3000;c->mfc_size=24;c->mfc_tag=4; ++ CHECK(mfc_submit(m,c,0x44)==0); ++ CHECK(c->ls[0x28000]==0x51 && c->ls[0x28200]==0); ++ CHECK(c->list_stall_mask==(1u<<4) && !(m->tag_completed&(1u<<4))); ++ CHECK(c->event_status&2);CHECK(c->list_stall_dest_lsa[4]==0x28200); ++ /* Resume must read this modified remaining element live. */ ++ spu_ls_write32(c,0x3014,0x21000); ++ CHECK(mfc_list_stall_ack(m,c,4)==0); ++ CHECK(c->ls[0x28200]==0x51 && !c->list_stall_mask); ++ CHECK(m->tag_completed&(1u<<4)); ++} ++static void signatures(spu_context* c) ++{ ++ memcpy(c->ls+0x20000,signature,16);signature_ctx=c; ++ spu_overlay_register_sig(signature,777);signature_ctx=NULL; ++ CHECK(publication_checks==1); ++ c->resident_ovl=19;spu_overlay_note_get(c,0x77000040,c->ls+0x20000,511); ++ CHECK(c->resident_ovl==19); ++ spu_overlay_note_get(c,0x77000040,c->ls+0x20000,512); ++ CHECK(c->resident_ovl==777); ++ CHECK(spu_overlay_match_sig(signature)==777); ++ /* Known EA and signature both match: registration order remains exact. */ ++ spu_overlay_note_get(c,0x70000000,c->ls+0x20000,512); ++ CHECK(c->resident_ovl==600); ++} ++int main(int argc,char** argv) ++{ ++ spu_context* c=fresh(); ++ if(argc>1 && !strcmp(argv[1],"full")){ ++ for(unsigned i=0;i<128;++i)spu_overlay_register_source(0x70000000+i*0x10000,600+i); ++ unsigned count=s_ovl_src_count; ++ /* Rejection must occur before reading the inaccessible signature. */ ++ spu_overlay_register_sig((const uint8_t*)(uintptr_t)1,999); ++ CHECK(s_ovl_src_count==(int)count); ++ allsize_scans=0;c->resident_ovl=19; ++ spu_overlay_note_get(c,0x78000000,c->ls+0x20000,512); ++ CHECK(c->resident_ovl==19);CHECK(allsize_scans==0); ++ }else{ ++ absence_and_hits(c);residency_and_epochs(c);old_matcher_edges(c); ++ list_resume(c);signatures(c); ++ } ++ spu_mfc_release(c);free(c); ++ printf("OVERLAY_ALLSIZE passed=%d failed=%d\n",g_pass,g_fail); ++ return g_fail?1:0; ++} +diff --git a/tools/test_spu_overlay_allsize.py b/tools/test_spu_overlay_allsize.py +new file mode 100644 +index 00000000..02bd7419 +--- /dev/null ++++ b/tools/test_spu_overlay_allsize.py +@@ -0,0 +1,84 @@ ++#!/usr/bin/env python3 ++"""Real GET discovery, residency/code epochs, list stalls and publication. ++ ++Only temporary source copies acquire counters/publication observation points. ++--output-dir retains the exact compiled binaries, argv and output for review. ++""" ++import argparse,json,os,pathlib,subprocess,tempfile ++if os.name == 'nt': ++ print('SKIP: standalone runtime fixture requires a POSIX compiler') ++ raise SystemExit(0) ++ROOT=pathlib.Path(__file__).resolve().parents[1];SPU=ROOT/'runtime/spu' ++parser=argparse.ArgumentParser() ++parser.add_argument('--output-dir',type=pathlib.Path) ++parser.add_argument('--source',type=pathlib.Path) ++parser.add_argument('--mutants',action='store_true') ++args=parser.parse_args() ++units=['spu_drain','spu_lockstep','spu_coherency','spu_workload','spurs_policy','spurs_job','spu_tsp_weak','spu_vm_pagemap','spurs_policy_blob_weak','spu_interp'] ++env={k:v for k,v in os.environ.items() if not k.startswith(('SPU_','SPURS_','YDKJ_','LBP_','GH3_'))} ++source=(args.source or SPU/'spu_channels.c').read_text() ++def instrument(text): ++ text=text.replace('#include "../','#include "'+str(SPU.parent)+'/') ++ needle='for (int i = 0; i < nsrc; i++) {' ++ assert text.count(needle)==1 ++ text=text.replace(needle,needle+'\n ++allsize_scans;') ++ start=text.index('void spu_overlay_register_sig(') ++ end=text.index('\n}',start) ++ body=text[start:end] ++ needle='__atomic_store_n(&s_ovl_src_count, s_ovl_src_count + 1, __ATOMIC_RELEASE);' ++ if needle not in body:needle='s_ovl_src_count++;' ++ assert body.count(needle)==1 ++ text=text[:start]+body.replace(needle,needle+'\n allsize_sig_published();')+text[end:] ++ return 'static unsigned allsize_scans;\nvoid allsize_sig_published(void);\n'+text ++def run(work): ++ fixture=(SPU/'tests/test_spu_mfc_slots.c').read_text() ++ fixture=fixture.replace('#include "../spu_channels.c"','#include "allsize_channels.c"') ++ fixture=fixture.replace('#include "../spu_lifted_job.h"','#include "'+str(SPU/'spu_lifted_job.h')+'"') ++ (work/'allsize_fixture.h').write_text(fixture) ++ records=[] ++ def variant(name,text,sanitize=False): ++ where=work/name;where.mkdir(exist_ok=True) ++ (where/'allsize_channels.c').write_text(instrument(text)) ++ exe=where/'fixture' ++ cmd=[os.environ.get('CC','cc'),'-std=gnu17','-O2','-UNDEBUG'] ++ if sanitize:cmd+=['-fsanitize=undefined','-fno-sanitize-recover=all'] ++ cmd+=['-I'+str(where),'-I'+str(work),'-I'+str(ROOT/'include'),'-I'+str(SPU),'-I'+str(ROOT/'runtime/platform'),str(SPU/'tests/test_spu_overlay_allsize.c'),*[str(SPU/(u+'.c')) for u in units],str(ROOT/'runtime/platform/win32_compat.c'),'-pthread','-lm','-o',str(exe)] ++ (where/'build-argv.json').write_text(json.dumps(cmd,indent=2)+'\n') ++ build=subprocess.run(cmd,capture_output=True,text=True,timeout=60) ++ (where/'build.stdout').write_text(build.stdout);(where/'build.stderr').write_text(build.stderr) ++ assert not build.returncode,build.stdout+build.stderr ++ results=[] ++ for mode in ['0','1','shadow']: ++ for case in ['core','full']: ++ argv=[str(exe),case] ++ r=subprocess.run(argv,env=dict(env,SPU_DISPATCH_CACHE=mode),capture_output=True,text=True,timeout=15) ++ label=mode+'-'+case ++ (where/(label+'.stdout')).write_text(r.stdout);(where/(label+'.stderr')).write_text(r.stderr) ++ records.append({'name':name,'mode':mode,'case':case,'argv':argv,'returncode':r.returncode}) ++ results.append(r) ++ print(name,mode,case,r.returncode,r.stdout.strip(),flush=True) ++ return results ++ good=True ++ for name,san in [('o2',False),('ubsan',True)]: ++ results=variant(name,source,san) ++ good=good and all(not r.returncode for r in results) ++ if args.mutants: ++ changes={ ++ 'reject-matches':('!spu_ovl_ea_known(ea)', '1'), ++ 'drop-residency':(' for (unsigned slot = 0; slot < 4; ++slot) {\n if (!ctx->resident_code[slot].image_id) continue;', ' for (unsigned slot = 4; slot < 4; ++slot) {\n if (!ctx->resident_code[slot].image_id) continue;'), ++ 'ignore-signatures':('!atomic_load_explicit(&s_ovl_has_sig, memory_order_acquire)', '1'), ++ 'late-signature-flag':(' atomic_store_explicit(&s_ovl_has_sig, 1, memory_order_release);\n __atomic_store_n(&s_ovl_src_count, s_ovl_src_count + 1, __ATOMIC_RELEASE);', ++ ' __atomic_store_n(&s_ovl_src_count, s_ovl_src_count + 1, __ATOMIC_RELEASE);\n atomic_store_explicit(&s_ovl_has_sig, 1, memory_order_release);'), ++ } ++ for name,(old,new) in changes.items(): ++ assert source.count(old)==1,(name,source.count(old)) ++ results=variant('mutant-'+name,source.replace(old,new)) ++ assert any(r.returncode and 'FAIL:' in r.stdout for r in results),name ++ print('PASS rejected bug control',name,flush=True) ++ (work/'runs.json').write_text(json.dumps(records,indent=2)+'\n') ++ if not good:raise SystemExit(1) ++ print('PASS real all-size overlay discovery preservation',flush=True) ++if args.output_dir: ++ args.output_dir.mkdir(parents=True,exist_ok=True);run(args.output_dir.resolve()) ++else: ++ with tempfile.TemporaryDirectory(prefix='spu-overlay-allsize-') as td:run(pathlib.Path(td)) diff --git a/tasks/sp00nznet__ps3recomp-654/tests/test.sh b/tasks/sp00nznet__ps3recomp-654/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-654/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-654/tests/verifier.py b/tasks/sp00nznet__ps3recomp-654/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-654/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-657/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-657/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-657/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-657/instruction.md b/tasks/sp00nznet__ps3recomp-657/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..38cc8bc3c0ac800802cc43ae33c3b2a39def151a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-657/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** macOS: bound walker profiling by elapsed time + +## Description + +## Why + +Both macOS arm64 jobs currently fail in `tools/test_gcm_walker_prof.py`: + +- the sampler is still armed after the six-second fixture window +- no profile file has been written +- stderr only reaches `[walker prof] sampling for 1 s` + +`RSX_WALKER_PROF_SECONDS=1` is implemented as 1,000 relative 1 ms sleeps. On the hosted arm64 runners those sleeps are coalesced enough that the supposed one-second profile takes longer than six wall-clock seconds. The detached thread is still active when the fixture checks it and exits. + +## What changed + +- Stop sampling at a monotonic wall-clock deadline instead of after `seconds * 1000` sleeps. +- Keep the sample-cap guard and nominal 1 ms cadence unchanged. +- Stretch each nominal tick to 5 ms in the fixture and bound the walker loop to four seconds. The old implementation needs at least five seconds and fails deterministically; the deadline-based implementation still finishes after about one second. + +## Validation + +- Confirmed the new delayed-tick regression fails against `master`. +- `tools/test_gcm_walker_prof.py` passes on Apple Silicon (162 samples/lines in the final run). +- Every `tools/test_gcm_*.py` test passes with Python 3.13. +- A Release `ps3recomp_runtime` build succeeds with Apple Clang and produces a native arm64 archive. +- `git diff --check` passes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-657/solution/patch.diff b/tasks/sp00nznet__ps3recomp-657/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7945d6c2227aea8760dc612922033e2622b9da3b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-657/solution/patch.diff @@ -0,0 +1,100 @@ +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..ec64c692 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -1886,10 +1886,12 @@ static void* wprof_thread(void* arg) + sigemptyset(&sa.sa_mask); + sigaction(SIGPROF, &sa, NULL); + fprintf(stderr, "[walker prof] sampling for %d s\n", secs); +- for (int k = 0; k < secs * 1000 && atomic_load(&s_wprof_n) < WPROF_MAX; k++) { ++ const u64 deadline = get_timestamp_ns() + (u64)secs * 1000000000ULL; ++ do { + pthread_kill(s_wprof_target, SIGPROF); + nanosleep(&tick, NULL); +- } ++ } while (atomic_load(&s_wprof_n) < WPROF_MAX && ++ get_timestamp_ns() < deadline); + nanosleep(&poll, NULL); + const int n = atomic_load_explicit(&s_wprof_n, memory_order_acquire); + FILE* f = fopen(out, "w"); +diff --git a/libs/video/tests/test_gcm_walker_prof.c b/libs/video/tests/test_gcm_walker_prof.c +index 065fb54d..7cab42b9 100644 +--- a/libs/video/tests/test_gcm_walker_prof.c ++++ b/libs/video/tests/test_gcm_walker_prof.c +@@ -1,20 +1,37 @@ + /* RSX_WALKER_PROF (cellGcmSys.c), the in-process walker sampler, on a host + * fixture: with RSX_WALKER_PROF=<file> and RSX_WALKER_PROF_SECONDS=1 the +- * first thread to drain the FIFO is sampled and the file holds the samples; +- * without it nothing is armed and no file appears. macOS arm64 only (the +- * sampler is compiled out elsewhere and this test only checks that). +- * Diagnostic coverage; it never starts a graphics backend. ++ * first thread to drain the FIFO is sampled and the file holds the samples. ++ * The fixture stretches every nominal 1 ms sleep to prove the requested ++ * duration follows elapsed time rather than a count of sleeps. Without the ++ * variable nothing is armed and no file appears. macOS arm64 only (the sampler ++ * is compiled out elsewhere and this test only checks that). Diagnostic ++ * coverage; it never starts a graphics backend. + * + * clang -std=gnu17 -I include -I libs/video libs/video/tests/test_gcm_walker_prof.c + * -ffunction-sections -fdata-sections -Wl,-dead_strip -o /tmp/test_gcm_walker_prof + * Run: /tmp/test_gcm_walker_prof on <file> (RSX_WALKER_PROF=<file> RSX_WALKER_PROF_SECONDS=1) + * /tmp/test_gcm_walker_prof off <file> (RSX_WALKER_PROF unset) + */ ++#include <time.h> ++#if defined(__APPLE__) && defined(__aarch64__) ++static int wprof_test_nanosleep(const struct timespec* req, struct timespec* rem); ++#define nanosleep wprof_test_nanosleep ++#endif + #include "../cellGcmSys.c" ++#if defined(__APPLE__) && defined(__aarch64__) ++#undef nanosleep ++/* Model timer coalescing: duration follows wall time, not 1000 sleeps. */ ++static int wprof_test_nanosleep(const struct timespec* req, struct timespec* rem) ++{ ++ struct timespec delayed = *req; ++ if (delayed.tv_sec == 0 && delayed.tv_nsec == 1000000) ++ delayed.tv_nsec = 5000000; ++ return nanosleep(&delayed, rem); ++} ++#endif + #include <stdio.h> + #include <stdlib.h> + #include <string.h> +-#include <time.h> + #include <ctype.h> + uint8_t* vm_base; + uint32_t ppu_vm_size; +@@ -125,7 +142,7 @@ int main(int argc, char** argv) + check(f == NULL, "without RSX_WALKER_PROF no profile is written"); + if (f) fclose(f); + } else { +- walker_loop(6.0); ++ walker_loop(4.0); + check(atomic_load(&s_wprof_state) == 2, "the sampler finishes after RSX_WALKER_PROF_SECONDS"); + FILE* f = fopen(path, "r"); + check(f != NULL, "the profile file is written"); +@@ -139,7 +156,7 @@ int main(int argc, char** argv) + } + if (f) fclose(f); + printf(" %d samples, %d lines\n", n, lines); +- check(n > 100 && lines == n, "about a sample per millisecond, one line each"); ++ check(n >= 10 && lines == n, "periodic samples are written one per line"); + check(frames_ok, "every sample has frames"); + } + #else +diff --git a/tools/test_gcm_walker_prof.py b/tools/test_gcm_walker_prof.py +index fc4d47ec..0f5d0eec 100644 +--- a/tools/test_gcm_walker_prof.py ++++ b/tools/test_gcm_walker_prof.py +@@ -1,8 +1,8 @@ + #!/usr/bin/env python3 + """RSX_WALKER_PROF, the in-process FIFO walker sampler (diagnostic, macOS +-arm64): armed only when set, and it writes about a sample per millisecond for +-RSX_WALKER_PROF_SECONDS (libs/video/tests/test_gcm_walker_prof.c, which +-compiles cellGcmSys.c in).""" ++arm64): armed only when set, bounded by RSX_WALKER_PROF_SECONDS even when its ++nominal 1 ms sleeps are coalesced, and writes every sample on its own line ++(libs/video/tests/test_gcm_walker_prof.c compiles cellGcmSys.c in).""" + import os + from pathlib import Path + import subprocess diff --git a/tasks/sp00nznet__ps3recomp-657/solution/solve.sh b/tasks/sp00nznet__ps3recomp-657/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-657/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-657/task.toml b/tasks/sp00nznet__ps3recomp-657/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6ebad4221271e4dda3542b58c1b2b72d102a4889 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-657/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-657" +description = "macOS: bound walker profiling by elapsed time" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/657" +source_access = "auto" +built_at = "2026-11-16T16:09:59.736142+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5e0e8b2af14a6fb7b501f920bcdec52692d1a2db9a1f331cd02f3fe7c5701431" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/video/cellGcmSys.c", + "libs/video/tests/test_gcm_walker_prof.c", + "tools/test_gcm_walker_prof.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 43 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.147506+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-657/tests/capture.py b/tasks/sp00nznet__ps3recomp-657/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-657/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-657/tests/instruction.md b/tasks/sp00nznet__ps3recomp-657/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..38cc8bc3c0ac800802cc43ae33c3b2a39def151a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-657/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** macOS: bound walker profiling by elapsed time + +## Description + +## Why + +Both macOS arm64 jobs currently fail in `tools/test_gcm_walker_prof.py`: + +- the sampler is still armed after the six-second fixture window +- no profile file has been written +- stderr only reaches `[walker prof] sampling for 1 s` + +`RSX_WALKER_PROF_SECONDS=1` is implemented as 1,000 relative 1 ms sleeps. On the hosted arm64 runners those sleeps are coalesced enough that the supposed one-second profile takes longer than six wall-clock seconds. The detached thread is still active when the fixture checks it and exits. + +## What changed + +- Stop sampling at a monotonic wall-clock deadline instead of after `seconds * 1000` sleeps. +- Keep the sample-cap guard and nominal 1 ms cadence unchanged. +- Stretch each nominal tick to 5 ms in the fixture and bound the walker loop to four seconds. The old implementation needs at least five seconds and fails deterministically; the deadline-based implementation still finishes after about one second. + +## Validation + +- Confirmed the new delayed-tick regression fails against `master`. +- `tools/test_gcm_walker_prof.py` passes on Apple Silicon (162 samples/lines in the final run). +- Every `tools/test_gcm_*.py` test passes with Python 3.13. +- A Release `ps3recomp_runtime` build succeeds with Apple Clang and produces a native arm64 archive. +- `git diff --check` passes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-657/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-657/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7945d6c2227aea8760dc612922033e2622b9da3b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-657/tests/oracle.patch @@ -0,0 +1,100 @@ +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..ec64c692 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -1886,10 +1886,12 @@ static void* wprof_thread(void* arg) + sigemptyset(&sa.sa_mask); + sigaction(SIGPROF, &sa, NULL); + fprintf(stderr, "[walker prof] sampling for %d s\n", secs); +- for (int k = 0; k < secs * 1000 && atomic_load(&s_wprof_n) < WPROF_MAX; k++) { ++ const u64 deadline = get_timestamp_ns() + (u64)secs * 1000000000ULL; ++ do { + pthread_kill(s_wprof_target, SIGPROF); + nanosleep(&tick, NULL); +- } ++ } while (atomic_load(&s_wprof_n) < WPROF_MAX && ++ get_timestamp_ns() < deadline); + nanosleep(&poll, NULL); + const int n = atomic_load_explicit(&s_wprof_n, memory_order_acquire); + FILE* f = fopen(out, "w"); +diff --git a/libs/video/tests/test_gcm_walker_prof.c b/libs/video/tests/test_gcm_walker_prof.c +index 065fb54d..7cab42b9 100644 +--- a/libs/video/tests/test_gcm_walker_prof.c ++++ b/libs/video/tests/test_gcm_walker_prof.c +@@ -1,20 +1,37 @@ + /* RSX_WALKER_PROF (cellGcmSys.c), the in-process walker sampler, on a host + * fixture: with RSX_WALKER_PROF=<file> and RSX_WALKER_PROF_SECONDS=1 the +- * first thread to drain the FIFO is sampled and the file holds the samples; +- * without it nothing is armed and no file appears. macOS arm64 only (the +- * sampler is compiled out elsewhere and this test only checks that). +- * Diagnostic coverage; it never starts a graphics backend. ++ * first thread to drain the FIFO is sampled and the file holds the samples. ++ * The fixture stretches every nominal 1 ms sleep to prove the requested ++ * duration follows elapsed time rather than a count of sleeps. Without the ++ * variable nothing is armed and no file appears. macOS arm64 only (the sampler ++ * is compiled out elsewhere and this test only checks that). Diagnostic ++ * coverage; it never starts a graphics backend. + * + * clang -std=gnu17 -I include -I libs/video libs/video/tests/test_gcm_walker_prof.c + * -ffunction-sections -fdata-sections -Wl,-dead_strip -o /tmp/test_gcm_walker_prof + * Run: /tmp/test_gcm_walker_prof on <file> (RSX_WALKER_PROF=<file> RSX_WALKER_PROF_SECONDS=1) + * /tmp/test_gcm_walker_prof off <file> (RSX_WALKER_PROF unset) + */ ++#include <time.h> ++#if defined(__APPLE__) && defined(__aarch64__) ++static int wprof_test_nanosleep(const struct timespec* req, struct timespec* rem); ++#define nanosleep wprof_test_nanosleep ++#endif + #include "../cellGcmSys.c" ++#if defined(__APPLE__) && defined(__aarch64__) ++#undef nanosleep ++/* Model timer coalescing: duration follows wall time, not 1000 sleeps. */ ++static int wprof_test_nanosleep(const struct timespec* req, struct timespec* rem) ++{ ++ struct timespec delayed = *req; ++ if (delayed.tv_sec == 0 && delayed.tv_nsec == 1000000) ++ delayed.tv_nsec = 5000000; ++ return nanosleep(&delayed, rem); ++} ++#endif + #include <stdio.h> + #include <stdlib.h> + #include <string.h> +-#include <time.h> + #include <ctype.h> + uint8_t* vm_base; + uint32_t ppu_vm_size; +@@ -125,7 +142,7 @@ int main(int argc, char** argv) + check(f == NULL, "without RSX_WALKER_PROF no profile is written"); + if (f) fclose(f); + } else { +- walker_loop(6.0); ++ walker_loop(4.0); + check(atomic_load(&s_wprof_state) == 2, "the sampler finishes after RSX_WALKER_PROF_SECONDS"); + FILE* f = fopen(path, "r"); + check(f != NULL, "the profile file is written"); +@@ -139,7 +156,7 @@ int main(int argc, char** argv) + } + if (f) fclose(f); + printf(" %d samples, %d lines\n", n, lines); +- check(n > 100 && lines == n, "about a sample per millisecond, one line each"); ++ check(n >= 10 && lines == n, "periodic samples are written one per line"); + check(frames_ok, "every sample has frames"); + } + #else +diff --git a/tools/test_gcm_walker_prof.py b/tools/test_gcm_walker_prof.py +index fc4d47ec..0f5d0eec 100644 +--- a/tools/test_gcm_walker_prof.py ++++ b/tools/test_gcm_walker_prof.py +@@ -1,8 +1,8 @@ + #!/usr/bin/env python3 + """RSX_WALKER_PROF, the in-process FIFO walker sampler (diagnostic, macOS +-arm64): armed only when set, and it writes about a sample per millisecond for +-RSX_WALKER_PROF_SECONDS (libs/video/tests/test_gcm_walker_prof.c, which +-compiles cellGcmSys.c in).""" ++arm64): armed only when set, bounded by RSX_WALKER_PROF_SECONDS even when its ++nominal 1 ms sleeps are coalesced, and writes every sample on its own line ++(libs/video/tests/test_gcm_walker_prof.c compiles cellGcmSys.c in).""" + import os + from pathlib import Path + import subprocess diff --git a/tasks/sp00nznet__ps3recomp-657/tests/test.sh b/tasks/sp00nznet__ps3recomp-657/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-657/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-657/tests/verifier.py b/tasks/sp00nznet__ps3recomp-657/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-657/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-659/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-659/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-659/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-659/instruction.md b/tasks/sp00nznet__ps3recomp-659/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..db33ca960bb0955effd6549db393e82b2e68c3c1 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-659/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** spurs: SPURS_IDLE_MAX caps the kernel's idle back-off (default unchanged) + +## Description + +## What + +`SPURS_IDLE_MAX=<n>` (0..8, default 4) sets the cap of the kernel's idle back-off, which is now the literal `4` in `spurs_pm_worker` (`else if (si->idle[wid] < 4) si->idle[wid]++;`). Nothing changes unless the variable is set. + +## Why + +A workload whose module run finds no work is probed every 2nd, 4th, 8th, then 16th kernel pass. The cap is fixed today; this makes it tunable for titles where the default hurts. + +In God of War: Ascension a `PS3_FTRACE` timeline shows stall pieces of 39-149 ms. During them every traced PPU thread is blocked and no SPU runs except the audio workload. Each piece ends when one of `CollisL`, `MeshProcJobs` or `RsxSync` is next dispatched, and probing idle modules more often shortens them (table below). + +The mechanism is only partly understood, and I have corrected an earlier reading of it. A log of those lists' headers shows that the title does raise readyCount for `CollisL` and `MeshProcJobs`, but 1-59 ms after the PPU writes the list header, and their runs follow that kick. `RsxSync`'s runs are mostly found by probing. Why the kick comes late is still under investigation, so this PR only adds the knob and makes no claim beyond the measurements. + +## Evidence + +All numbers are from the GoW:A port on a v0.17-based toolkit, whose kernel has the same back-off with the same cap. Host is 6 cores / 12 threads. Each side is one 60-s traced window in the fast state, one run each: + +| | cap 4 (default) | `SPURS_IDLE_MAX=0` | +|---|---|---| +| time with no non-audio SPU running | 1351 ms | 254 ms | +| longest such piece | 149 ms | 17.5 ms | +| main-thread wait at the task batch | 7.3 ms/frame | 3.0 ms/frame | +| frames in the window | 758 | 810 | +| game CPU | ~7.0 cores | ~7.3 cores | + +An untraced A/B of cap 2 against cap 4 ran with a discarded warm-up run first, in the order 2 4 4 2. Game frames/s over 420-600 s: 13.44 / 13.46 with cap 2 against 13.19 / 11.32 with cap 4. The level-arrival phase gained most: 60-68 game frames/s at 90-120 s against 43-50. + +## Not yet verified + +- Not yet verified on master: building and running this branch. The change was only compile-checked: a syntax-only clang-cl pass over `libs/spurs/cellSpurs.c`. +- Not yet verified on master: whether master's request-line kick changes this picture for these workloads. + +`docs/DIAGNOSTICS.md` is generated, so I did not regenerate it here. Running `tools/gen_diagnostics_index.py` on master rewrites far more than this one entry. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-659/solution/patch.diff b/tasks/sp00nznet__ps3recomp-659/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..54309d4847d652c2dfc66348d5d21e068cdaec87 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-659/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/libs/spurs/cellSpurs.c b/libs/spurs/cellSpurs.c +index 82ea66c6..4aa43c69 100644 +--- a/libs/spurs/cellSpurs.c ++++ b/libs/spurs/cellSpurs.c +@@ -1710,6 +1710,22 @@ static WklPm* spurs_resolve_pm(u32 wid) + return r->fn ? r : NULL; + } + ++/* SPURS_IDLE_MAX=<n> (default 4, 0..8): cap of the idle back-off, as log2 of ++ * the pass cadence. A module run that finds no work doubles its workload's probe ++ * interval up to every 2^n-th kernel pass. Work that arrives without a kick is ++ * found only by those probes, and a chain of such workloads, each backed off, ++ * pays up to 2^n passes per link. 0 probes every enabled workload every pass. */ ++static u32 spurs_idle_max(void) ++{ ++ static int s_max = -1; ++ if (s_max < 0) { ++ const char* e = getenv("SPURS_IDLE_MAX"); ++ int v = e && *e ? atoi(e) : 4; ++ s_max = v < 0 ? 0 : v > 8 ? 8 : v; ++ } ++ return (u32)s_max; ++} ++ + /* One persistent worker for each configured virtual SPU. A waiting policy + * occupies only its own slot; a later runnable producer can use another slot. + * Admission and lifecycle state are serialized per instance. Guest execution +@@ -1740,7 +1756,7 @@ static DWORD WINAPI spurs_pm_worker(LPVOID p) + vm_base[slot->ea + SPURS_WKL_CURCONT + wid] = si->active[wid]; + ef_line_end(slot->ea); + if (polls) si->idle[wid] = 0; +- else if (si->idle[wid] < 4) si->idle[wid]++; ++ else if (si->idle[wid] < spurs_idle_max()) si->idle[wid]++; + slot->busy = 0; + WakeAllConditionVariable(&si->wake); + } diff --git a/tasks/sp00nznet__ps3recomp-659/solution/solve.sh b/tasks/sp00nznet__ps3recomp-659/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-659/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-659/task.toml b/tasks/sp00nznet__ps3recomp-659/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dd3f86f2c08fbf11af30c43f508f1619c706a534 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-659/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-659" +description = "spurs: SPURS_IDLE_MAX caps the kernel's idle back-off (default unchanged)" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/659" +source_access = "auto" +built_at = "2026-11-16T16:09:59.644666+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1b895e55fb93e2723f8c9e4495fc023b4fe00bf939d4a36813138db82ad5fc20" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/spurs/cellSpurs.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 18 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.148047+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-659/tests/capture.py b/tasks/sp00nznet__ps3recomp-659/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-659/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-659/tests/instruction.md b/tasks/sp00nznet__ps3recomp-659/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..db33ca960bb0955effd6549db393e82b2e68c3c1 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-659/tests/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** spurs: SPURS_IDLE_MAX caps the kernel's idle back-off (default unchanged) + +## Description + +## What + +`SPURS_IDLE_MAX=<n>` (0..8, default 4) sets the cap of the kernel's idle back-off, which is now the literal `4` in `spurs_pm_worker` (`else if (si->idle[wid] < 4) si->idle[wid]++;`). Nothing changes unless the variable is set. + +## Why + +A workload whose module run finds no work is probed every 2nd, 4th, 8th, then 16th kernel pass. The cap is fixed today; this makes it tunable for titles where the default hurts. + +In God of War: Ascension a `PS3_FTRACE` timeline shows stall pieces of 39-149 ms. During them every traced PPU thread is blocked and no SPU runs except the audio workload. Each piece ends when one of `CollisL`, `MeshProcJobs` or `RsxSync` is next dispatched, and probing idle modules more often shortens them (table below). + +The mechanism is only partly understood, and I have corrected an earlier reading of it. A log of those lists' headers shows that the title does raise readyCount for `CollisL` and `MeshProcJobs`, but 1-59 ms after the PPU writes the list header, and their runs follow that kick. `RsxSync`'s runs are mostly found by probing. Why the kick comes late is still under investigation, so this PR only adds the knob and makes no claim beyond the measurements. + +## Evidence + +All numbers are from the GoW:A port on a v0.17-based toolkit, whose kernel has the same back-off with the same cap. Host is 6 cores / 12 threads. Each side is one 60-s traced window in the fast state, one run each: + +| | cap 4 (default) | `SPURS_IDLE_MAX=0` | +|---|---|---| +| time with no non-audio SPU running | 1351 ms | 254 ms | +| longest such piece | 149 ms | 17.5 ms | +| main-thread wait at the task batch | 7.3 ms/frame | 3.0 ms/frame | +| frames in the window | 758 | 810 | +| game CPU | ~7.0 cores | ~7.3 cores | + +An untraced A/B of cap 2 against cap 4 ran with a discarded warm-up run first, in the order 2 4 4 2. Game frames/s over 420-600 s: 13.44 / 13.46 with cap 2 against 13.19 / 11.32 with cap 4. The level-arrival phase gained most: 60-68 game frames/s at 90-120 s against 43-50. + +## Not yet verified + +- Not yet verified on master: building and running this branch. The change was only compile-checked: a syntax-only clang-cl pass over `libs/spurs/cellSpurs.c`. +- Not yet verified on master: whether master's request-line kick changes this picture for these workloads. + +`docs/DIAGNOSTICS.md` is generated, so I did not regenerate it here. Running `tools/gen_diagnostics_index.py` on master rewrites far more than this one entry. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-659/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-659/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..54309d4847d652c2dfc66348d5d21e068cdaec87 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-659/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/libs/spurs/cellSpurs.c b/libs/spurs/cellSpurs.c +index 82ea66c6..4aa43c69 100644 +--- a/libs/spurs/cellSpurs.c ++++ b/libs/spurs/cellSpurs.c +@@ -1710,6 +1710,22 @@ static WklPm* spurs_resolve_pm(u32 wid) + return r->fn ? r : NULL; + } + ++/* SPURS_IDLE_MAX=<n> (default 4, 0..8): cap of the idle back-off, as log2 of ++ * the pass cadence. A module run that finds no work doubles its workload's probe ++ * interval up to every 2^n-th kernel pass. Work that arrives without a kick is ++ * found only by those probes, and a chain of such workloads, each backed off, ++ * pays up to 2^n passes per link. 0 probes every enabled workload every pass. */ ++static u32 spurs_idle_max(void) ++{ ++ static int s_max = -1; ++ if (s_max < 0) { ++ const char* e = getenv("SPURS_IDLE_MAX"); ++ int v = e && *e ? atoi(e) : 4; ++ s_max = v < 0 ? 0 : v > 8 ? 8 : v; ++ } ++ return (u32)s_max; ++} ++ + /* One persistent worker for each configured virtual SPU. A waiting policy + * occupies only its own slot; a later runnable producer can use another slot. + * Admission and lifecycle state are serialized per instance. Guest execution +@@ -1740,7 +1756,7 @@ static DWORD WINAPI spurs_pm_worker(LPVOID p) + vm_base[slot->ea + SPURS_WKL_CURCONT + wid] = si->active[wid]; + ef_line_end(slot->ea); + if (polls) si->idle[wid] = 0; +- else if (si->idle[wid] < 4) si->idle[wid]++; ++ else if (si->idle[wid] < spurs_idle_max()) si->idle[wid]++; + slot->busy = 0; + WakeAllConditionVariable(&si->wake); + } diff --git a/tasks/sp00nznet__ps3recomp-659/tests/test.sh b/tasks/sp00nznet__ps3recomp-659/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-659/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-659/tests/verifier.py b/tasks/sp00nznet__ps3recomp-659/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-659/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-666/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-666/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-666/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-666/instruction.md b/tasks/sp00nznet__ps3recomp-666/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cfdbd35ffc391dd32870882c251a9e96a48f0af2 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-666/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** spu_coherency: the lock-line spin sleeps after ~1 ms + +## Description + +## What + +`spu_lockline_lock` (MSVC/clang-cl branch) yields with `SwitchToThread` every 4096 pauses. After six such rounds (~1 ms of waiting) it now calls `Sleep(1)` instead. `SPU_LOCKLINE_SLEEP=0` keeps the current behaviour. + +## Why + +`SwitchToThread` only hands the core to a thread already queued on the same processor, and `Sleep(0)` only to one of equal or higher priority. Neither reaches a lower-priority holder that is waiting for a core somewhere else. When every logical CPU is busy and the waiters run above the holder's priority, the holder can stay off the CPU for a long time while they spin. + +This can happen on master: `sys_ppu_thread_create` raises guest priorities below 256 to `THREAD_PRIORITY_ABOVE_NORMAL`, and PPU stores to SPU-reserved lines take the lock line (the store coherency path and `ppu_stwcx32` / `ppu_stdcx64`). + +A normal wait is far below a microsecond and never reaches the sleep. + +## Evidence + +All numbers are from the God of War: Ascension port on a v0.17-based toolkit. Its SPURS kernel threads run above normal, and the toolkit has a `[lockline-long]` log that names the waiter and the holder of any wait over 5 ms. The runs had two busy processes on a 6-core / 12-thread host, 480 s each. + +- Before: up to 86 ms per wait, with several SPU threads waiting at once. In 24 of the 44 long waits the holder was a normal-priority PPU thread in `vm_write32`, `ppu_stdcx64` or `vm_write8`. +- With the whole game process raised to AboveNormal and no other change, it got worse: up to 425 ms, 42 events in 480 s. That points at the higher-priority spinners, not the other programs, as what keeps the holder waiting. +- A/B with the port also raising its process class. The order was a warm-up run, then old, new, new, old: + +| | new (this change) | old | +|---|---|---| +| longest lock-line wait | 7.4 / 14.0 ms | 34 / 179 ms | +| waits over 5 ms | 3 / 38 | 72 / 200+ | +| game frames/s, 360-480 s | 8.16 / 8.65 | 8.57 / 2.78 | + +The second old run collapsed when the host reached 100%. Apart from that run, the frame rate is the same in both arms. + +## Not yet verified + +- Not yet verified on master: building and running this branch. The change was only syntax-checked with clang-cl (`-fsyntax-only`). +- Not yet verified on master: a title where the waiters outrank the holder without the port's own priority changes. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-666/solution/patch.diff b/tasks/sp00nznet__ps3recomp-666/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0ec14fa6311d3a2d4e976d366c860e74ba1a0d75 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-666/solution/patch.diff @@ -0,0 +1,32 @@ +diff --git a/runtime/spu/spu_coherency.c b/runtime/spu/spu_coherency.c +index ed2bcf58..c0173e9e 100644 +--- a/runtime/spu/spu_coherency.c ++++ b/runtime/spu/spu_coherency.c +@@ -40,13 +40,25 @@ static volatile long g_lockline = 0; + * pause, and yield after a long wait. The bare exchange loop let GH3's four + * idle job-policy pollers saturate the line and delay every other SPU atomic + * -- FMOD's mixer task among them, 25-40 ms at a time. */ ++/* After ~1 ms of spinning (six rounds of 4096 pauses) the waiter sleeps instead. ++ * SwitchToThread only hands the core to a thread queued on this same processor, ++ * and Sleep(0) only to one of equal or higher priority -- neither reaches a ++ * lower-priority holder that is waiting for a core. With every core busy, waiters ++ * above the holder's priority could keep it off the CPU for tens of milliseconds. ++ * A normal wait is far under a microsecond and never gets here. ++ * SPU_LOCKLINE_SLEEP=0 keeps the plain spin. */ + void spu_lockline_lock(void) + { +- unsigned spins = 0; ++ static int s_sleep = -1; ++ unsigned spins = 0, rounds = 0; + while (_InterlockedExchange(&g_lockline, 1)) { ++ if (s_sleep < 0) { const char* e = getenv("SPU_LOCKLINE_SLEEP"); s_sleep = !(e && e[0] == '0'); } + do { + _mm_pause(); +- if (++spins >= 4096) { spins = 0; SwitchToThread(); } ++ if (++spins >= 4096) { ++ spins = 0; ++ if (rounds++ < 6 || !s_sleep) SwitchToThread(); else Sleep(1); ++ } + } while (g_lockline); + } + } diff --git a/tasks/sp00nznet__ps3recomp-666/solution/solve.sh b/tasks/sp00nznet__ps3recomp-666/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-666/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-666/task.toml b/tasks/sp00nznet__ps3recomp-666/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..910f904a5f0b9d16b73c19aa94655e870b3537c7 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-666/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-666" +description = "spu_coherency: the lock-line spin sleeps after ~1 ms" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/666" +source_access = "auto" +built_at = "2026-11-16T16:09:59.734368+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:44d6010303134be90da0d888fdb72834fa62a3d3f696003abf090165c37cd4eb" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "runtime/spu/spu_coherency.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 16 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.148601+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-666/tests/capture.py b/tasks/sp00nznet__ps3recomp-666/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-666/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-666/tests/instruction.md b/tasks/sp00nznet__ps3recomp-666/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cfdbd35ffc391dd32870882c251a9e96a48f0af2 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-666/tests/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** spu_coherency: the lock-line spin sleeps after ~1 ms + +## Description + +## What + +`spu_lockline_lock` (MSVC/clang-cl branch) yields with `SwitchToThread` every 4096 pauses. After six such rounds (~1 ms of waiting) it now calls `Sleep(1)` instead. `SPU_LOCKLINE_SLEEP=0` keeps the current behaviour. + +## Why + +`SwitchToThread` only hands the core to a thread already queued on the same processor, and `Sleep(0)` only to one of equal or higher priority. Neither reaches a lower-priority holder that is waiting for a core somewhere else. When every logical CPU is busy and the waiters run above the holder's priority, the holder can stay off the CPU for a long time while they spin. + +This can happen on master: `sys_ppu_thread_create` raises guest priorities below 256 to `THREAD_PRIORITY_ABOVE_NORMAL`, and PPU stores to SPU-reserved lines take the lock line (the store coherency path and `ppu_stwcx32` / `ppu_stdcx64`). + +A normal wait is far below a microsecond and never reaches the sleep. + +## Evidence + +All numbers are from the God of War: Ascension port on a v0.17-based toolkit. Its SPURS kernel threads run above normal, and the toolkit has a `[lockline-long]` log that names the waiter and the holder of any wait over 5 ms. The runs had two busy processes on a 6-core / 12-thread host, 480 s each. + +- Before: up to 86 ms per wait, with several SPU threads waiting at once. In 24 of the 44 long waits the holder was a normal-priority PPU thread in `vm_write32`, `ppu_stdcx64` or `vm_write8`. +- With the whole game process raised to AboveNormal and no other change, it got worse: up to 425 ms, 42 events in 480 s. That points at the higher-priority spinners, not the other programs, as what keeps the holder waiting. +- A/B with the port also raising its process class. The order was a warm-up run, then old, new, new, old: + +| | new (this change) | old | +|---|---|---| +| longest lock-line wait | 7.4 / 14.0 ms | 34 / 179 ms | +| waits over 5 ms | 3 / 38 | 72 / 200+ | +| game frames/s, 360-480 s | 8.16 / 8.65 | 8.57 / 2.78 | + +The second old run collapsed when the host reached 100%. Apart from that run, the frame rate is the same in both arms. + +## Not yet verified + +- Not yet verified on master: building and running this branch. The change was only syntax-checked with clang-cl (`-fsyntax-only`). +- Not yet verified on master: a title where the waiters outrank the holder without the port's own priority changes. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-666/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-666/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0ec14fa6311d3a2d4e976d366c860e74ba1a0d75 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-666/tests/oracle.patch @@ -0,0 +1,32 @@ +diff --git a/runtime/spu/spu_coherency.c b/runtime/spu/spu_coherency.c +index ed2bcf58..c0173e9e 100644 +--- a/runtime/spu/spu_coherency.c ++++ b/runtime/spu/spu_coherency.c +@@ -40,13 +40,25 @@ static volatile long g_lockline = 0; + * pause, and yield after a long wait. The bare exchange loop let GH3's four + * idle job-policy pollers saturate the line and delay every other SPU atomic + * -- FMOD's mixer task among them, 25-40 ms at a time. */ ++/* After ~1 ms of spinning (six rounds of 4096 pauses) the waiter sleeps instead. ++ * SwitchToThread only hands the core to a thread queued on this same processor, ++ * and Sleep(0) only to one of equal or higher priority -- neither reaches a ++ * lower-priority holder that is waiting for a core. With every core busy, waiters ++ * above the holder's priority could keep it off the CPU for tens of milliseconds. ++ * A normal wait is far under a microsecond and never gets here. ++ * SPU_LOCKLINE_SLEEP=0 keeps the plain spin. */ + void spu_lockline_lock(void) + { +- unsigned spins = 0; ++ static int s_sleep = -1; ++ unsigned spins = 0, rounds = 0; + while (_InterlockedExchange(&g_lockline, 1)) { ++ if (s_sleep < 0) { const char* e = getenv("SPU_LOCKLINE_SLEEP"); s_sleep = !(e && e[0] == '0'); } + do { + _mm_pause(); +- if (++spins >= 4096) { spins = 0; SwitchToThread(); } ++ if (++spins >= 4096) { ++ spins = 0; ++ if (rounds++ < 6 || !s_sleep) SwitchToThread(); else Sleep(1); ++ } + } while (g_lockline); + } + } diff --git a/tasks/sp00nznet__ps3recomp-666/tests/test.sh b/tasks/sp00nznet__ps3recomp-666/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-666/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-666/tests/verifier.py b/tasks/sp00nznet__ps3recomp-666/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-666/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-670/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-670/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-670/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-670/instruction.md b/tasks/sp00nznet__ps3recomp-670/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a3bafe736e6fd0274e48f14cea99fe8d526405f4 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-670/instruction.md @@ -0,0 +1,48 @@ +# Issue + +**Title:** Fragment programs: honour the per-source input precision modifiers + +## Description + +### Why + +DWORD2 bits 19-21, 22-24 and 25-27 hold a 3-bit input precision modifier for SRC0, SRC1 and SRC2. RPCS3 calls these fields `src0/1/2_prec_mod`; I read RPCS3 for this and copied nothing. The hardware clamps the operand to that precision's range after abs and before negate. The decompiler ignored the field. + +A downstream title showed it: a soft-particle fade `MUL r, tex, |depth difference|` with the depth source marked fixed9 was multiplied by the raw difference instead of a value in [0, 1], so every premultiplied particle drew saturated white. + +### Change + +Size: +125 lines, nothing removed. That is 39 lines in `rsx_fp_decompiler.c` and 86 lines of tests in `test_fp_decompiler.c`. + +- `Src.prec`, read from DWORD2 for non-branch instructions only (a branch's DWORD2 holds other fields). +- `fp_src_prec_clamp()`: 1 half [-65504, 65504], 2 fixed12 [-2, 2], 3 fixed9 [-1, 1], 4 saturate [0, 1]. Values 0 and 5-7 leave the operand unchanged. +- `emit_src` writes `clamp(abs(x), lo, hi)` and puts `-( )` around it for a negated source. It writes straight into the destination buffer, so there is no intermediate for -Wformat-truncation to warn about. + +ASSUMPTION: the ranges for values 1, 2 and 4 follow the destination-precision meaning of the same encodings and RPCS3's field names. Only modifier 3 has been seen in a real program (the fade above). + +### Tests + +All in `libs/video/tests/test_fp_decompiler.c`, using the same helpers and CI step as the existing cases: + +- `MAD r1, r0, r0, r0` with each of the 8 values in each of the 3 slots (24 cases). Values 1-4 expect `clamp((r[0]).xyzw, lo, hi)`; 0 and 5-7 expect no `clamp(`. +- Abs, clamp and negate order: `-(clamp(abs((r[0]).xyzw), -1.0, 1.0))`. +- A soft-particle fixture through the whole decompile: `TEX r1, TC0`; `TEX r5, TC1`; `ADD r5, r5, -{0.25}` (inline constant); `MUL r0, r1, |r5|` with SRC1 fixed9. It checks the four emitted body lines exactly and the single colour export. With the modifier cleared it checks that the operand stays `abs((r[5]).xyzw)` with no clamp. **The fixture is synthetic**: microcode words hand-encoded in the test, not taken from any title. + +CI's command line: `gcc -std=gnu17 -Wall -Wextra -I include -o t libs/video/tests/test_fp_decompiler.c libs/video/rsx_fp_decompiler.c && ./t` + +- master: 103 passed, 14 failed (all new cases). +- this branch: 117 passed, 0 failed, with both gcc 16.2 and clang 19.1. Also clean under gcc -O2 -fsanitize=address,undefined. +- The compiler warnings are the same as on master: two -Wcomment and, with gcc, two -Wformat-truncation in existing code. +- linux.yml, all 40 steps, run locally (not on GitHub) on master and on this branch, each with gcc 16.2 and with clang 19.1 (CMAKE_BUILD_TYPE=Release). The 39 steps after "Install dependencies" all pass, on both trees and with both compilers. That includes Configure, Build, the archive check, the lifter suites, the pad tests, guest shader translation, the boot smoke title, the game template, the POSIX host, sync_stress, fiber_switch and the self-contained RSX tests step, which runs `test_fp_decompiler`. "Install dependencies" (apt) was replaced by the same packages from nixpkgs: SDL2 is sdl2-compat 2.32.72 (the SDL2 API on SDL3), plus glslang 16.4, spirv-tools and spirv-cross 1.4.357. Not run: the Debug half of the build-type matrix, macos.yml, windows.yml (no macOS or Windows host here). + +Not run: MSVC/clang-cl, macOS, or a real title on this project's own backend. + +Overlap with open PRs: I took the current diff of each of the 90 open PRs for the files this branch touches and ran `git apply --check` against master and against this branch, whole and hunk by hunk. +- Apply cleanly on top of this branch: + - `rsx_fp_decompiler.c`: #601 (3/3 hunks), #635 (2/2). +- Conflict: #626 rewrites every line of `test_fp_decompiler.c` (line endings, one whole-file hunk), so whichever lands second needs a trivial rebase. +- Do not apply to master itself: #213 (`rsx_fp_decompiler.c`; 1 of its 3 hunks applies to master, and that one also applies here) and #447 (`rsx_fp_decompiler.c`, `test_fp_decompiler.c`; 2 of its 14 hunks apply to master, and both also apply here). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-670/solution/patch.diff b/tasks/sp00nznet__ps3recomp-670/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a653d0e8ed740c239a7df06afcf6b6d8e6771988 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-670/solution/patch.diff @@ -0,0 +1,171 @@ +diff --git a/libs/video/rsx_fp_decompiler.c b/libs/video/rsx_fp_decompiler.c +index cfb9685b..58a4c91a 100644 +--- a/libs/video/rsx_fp_decompiler.c ++++ b/libs/video/rsx_fp_decompiler.c +@@ -315,9 +315,36 @@ typedef struct { + int half; + int negate; + int abs; ++ int prec; /* input precision modifier, 0 = none (see fp_src_prec_clamp) */ + char swz[5]; /* e.g. "xyzw" */ + } Src; + ++/* Each source operand carries a 3-bit input precision modifier in DWORD2: ++ * bits 19-21 for SRC0, 22-24 for SRC1, 25-27 for SRC2. The hardware clamps the ++ * operand to that precision's range after abs and before negate: ++ * 1 half [-65504, 65504] ++ * 2 fixed12 [-2, 2] ++ * 3 fixed9 [-1, 1] ++ * 4 saturate [0, 1] ++ * 0 (and the values above 4) leave the operand as it is. A soft-particle ++ * program that fades with MUL r, tex, |depth difference| and marks that source ++ * fixed9 relies on it: unclamped, the difference in metres saturates every ++ * fade to full opacity. */ ++#define FP_SRC0_PREC_SHIFT 19 ++#define FP_SRC1_PREC_SHIFT 22 ++#define FP_SRC2_PREC_SHIFT 25 ++ ++static const char* fp_src_prec_clamp(int prec) ++{ ++ switch (prec) { ++ case 1: return "-65504.0, 65504.0"; ++ case 2: return "-2.0, 2.0"; ++ case 3: return "-1.0, 1.0"; ++ case 4: return "0.0, 1.0"; ++ default: return NULL; ++ } ++} ++ + static void decode_src(u32 w, int abs_bit, Src* s) + { + static const char comp[4] = {'x','y','z','w'}; +@@ -326,6 +353,7 @@ static void decode_src(u32 w, int abs_bit, Src* s) + s->half = (w & FP_SRC_HALF) ? 1 : 0; + s->negate = (w & FP_SRC_NEGATE) ? 1 : 0; + s->abs = abs_bit ? 1 : 0; ++ s->prec = 0; + for (int i = 0; i < 4; i++) + s->swz[i] = comp[(w >> (FP_SRC_SWZ_SHIFT + 2 * i)) & 3]; + s->swz[4] = '\0'; +@@ -394,6 +422,12 @@ static void emit_src(const Src* s, u32 input_src, int persp, const float* k, int + const char* pre = ""; + const char* post = ""; + if (s->abs) { pre = "abs("; post = ")"; } ++ const char* range = fp_src_prec_clamp(s->prec); ++ if (range) { /* abs, then the precision clamp, then negate */ ++ snprintf(buf, bufsz, s->negate ? "-(clamp(%s%s%s, %s))" : "clamp(%s%s%s, %s)", ++ pre, swz, post, range); ++ return; ++ } + if (s->negate) snprintf(buf, bufsz, "-(%s%s%s)", pre, swz, post); + else snprintf(buf, bufsz, "%s%s%s", pre, swz, post); + } +@@ -780,6 +814,11 @@ static int rsx_fp_decompile_internal( + decode_src(w1, w1 & FP_SRC0_ABS, &s0); + decode_src(w2, w2 & FP_SRC1_ABS, &s1); + decode_src(w3, 0, &s2); ++ if (!(w2 & FP_BRANCH)) { /* a branch's DWORD2 holds other fields */ ++ s0.prec = (int)((w2 >> FP_SRC0_PREC_SHIFT) & 7u); ++ s1.prec = (int)((w2 >> FP_SRC1_PREC_SHIFT) & 7u); ++ s2.prec = (int)((w2 >> FP_SRC2_PREC_SHIFT) & 7u); ++ } + + /* Inline constant: any CONST source pulls the next 16 bytes as a + * float4 literal and advances past it. */ +diff --git a/libs/video/tests/test_fp_decompiler.c b/libs/video/tests/test_fp_decompiler.c +index 033d2528..e9c9c398 100644 +--- a/libs/video/tests/test_fp_decompiler.c ++++ b/libs/video/tests/test_fp_decompiler.c +@@ -591,6 +591,92 @@ int main(void) + + } + ++ /* Per-source input precision modifiers: DWORD2 bits 19-21 (SRC0), 22-24 ++ * (SRC1) and 25-27 (SRC2) clamp the operand after abs and before negate. ++ * 1 half, 2 fixed12, 3 fixed9, 4 saturate; 0 and 5-7 leave it alone. */ ++ { ++ static const char* const range[8] = { ++ NULL, "-65504.0, 65504.0", "-2.0, 2.0", "-1.0, 1.0", "0.0, 1.0", ++ NULL, NULL, NULL }; ++ static const char* const slot_name[3] = { "src0", "src1", "src2" }; ++ for (int slot = 0; slot < 3; slot++) { ++ for (u32 v = 0; v < 8; v++) { ++ u8 prog[16]; ++ u32 w1 = T_TEMP | REG(0) | SWZ_IDENT | EXEC_ALWAYS; ++ u32 w2 = T_TEMP | REG(0) | SWZ_IDENT; ++ u32 w3 = T_TEMP | REG(0) | SWZ_IDENT; ++ w2 |= v << (19 + 3 * slot); ++ put_word(prog + 0, OPC(0x04) | OUTMASK_ALL | OUTREG(1) | END); /* MAD r1, r0, r0, r0 */ ++ put_word(prog + 4, w1); ++ put_word(prog + 8, w2); ++ put_word(prog + 12, w3); ++ rsx_fp_decompile(prog, sizeof(prog), CTRL_32BIT, hlsl, sizeof(hlsl)); ++ char name[64], want[128]; ++ snprintf(name, sizeof name, "prec_mod_%s_%u", slot_name[slot], v); ++ if (range[v]) { ++ snprintf(want, sizeof want, "clamp((r[0]).xyzw, %s)", range[v]); ++ check(name, hlsl, want); ++ } else { ++ check_absent(name, hlsl, "clamp("); ++ } ++ } ++ } ++ ++ /* abs is applied first, then the clamp, then the negate: ++ * MUL r1, -|r0|, r0 with SRC0 fixed9. */ ++ u8 prog[16]; ++ put_word(prog + 0, OPC(0x02) | OUTMASK_ALL | OUTREG(1) | END); ++ put_word(prog + 4, T_TEMP | REG(0) | SWZ_IDENT | EXEC_ALWAYS | (1u << 29) | (1u << 17)); ++ put_word(prog + 8, T_TEMP | REG(0) | SWZ_IDENT | (3u << 19)); ++ put_word(prog + 12, 0); ++ rsx_fp_decompile(prog, sizeof(prog), CTRL_32BIT, hlsl, sizeof(hlsl)); ++ check("prec_mod_abs_clamp_negate", hlsl, ++ "-(clamp(abs((r[0]).xyzw), -1.0, 1.0))"); ++ } ++ ++ /* Soft-particle fade through the whole decompile: a synthetic, hand-encoded ++ * four-instruction program (not taken from any title) in the shape the ++ * clamp matters for, MUL r0, tex, |depth difference| with SRC1 fixed9. ++ * TEX r1, TC0, unit 0 particle colour ++ * TEX r5, TC1, unit 1 scene depth ++ * ADD r5, r5, -{0.25} minus the fragment's depth (inline const) ++ * MUL r0, r1, |r5| (fixed9) fade, END ++ * Without the clamp the colour is multiplied by the raw difference. */ ++ { ++ u8 prog[80]; ++ put_word(prog + 0, OPC(0x17) | OUTMASK_ALL | OUTREG(1) | INSRC(4) | TEXU(0)); ++ put_word(prog + 4, T_INPUT | SWZ_IDENT | EXEC_ALWAYS); ++ put_word(prog + 8, 0); ++ put_word(prog + 12, 0); ++ put_word(prog + 16, OPC(0x17) | OUTMASK_ALL | OUTREG(5) | INSRC(5) | TEXU(1)); ++ put_word(prog + 20, T_INPUT | SWZ_IDENT | EXEC_ALWAYS); ++ put_word(prog + 24, 0); ++ put_word(prog + 28, 0); ++ put_word(prog + 32, OPC(0x03) | OUTMASK_ALL | OUTREG(5)); ++ put_word(prog + 36, T_TEMP | REG(5) | SWZ_IDENT | EXEC_ALWAYS); ++ put_word(prog + 40, T_CONST | SWZ_IDENT | (1u << 17)); /* -CONST */ ++ put_word(prog + 44, 0); ++ for (int i = 0; i < 4; i++) put_float(prog + 48 + 4 * i, 0.25f); ++ put_word(prog + 64, OPC(0x02) | OUTMASK_ALL | OUTREG(0) | END); ++ put_word(prog + 68, T_TEMP | REG(1) | SWZ_IDENT | EXEC_ALWAYS); ++ put_word(prog + 72, T_TEMP | REG(5) | SWZ_IDENT | (1u << 18) | (3u << 22)); /* |r5|, fixed9 */ ++ put_word(prog + 76, 0); ++ int n = rsx_fp_decompile(prog, sizeof(prog), CTRL_32BIT, hlsl, sizeof(hlsl)); ++ check_true("soft_particle_count", n == 4); ++ check("soft_particle_body", hlsl, ++ " { float4 _v = (float4)(rsx_tex[0].Sample(rsx_samp[0], ((input.tc0).xyzw).xy)); r[1].xyzw = _v.xyzw; }\n" ++ " { float4 _v = (float4)(rsx_tex[1].Sample(rsx_samp[1], ((input.tc1).xyzw).xy)); r[5].xyzw = _v.xyzw; }\n" ++ " { float4 _v = (float4)(((r[5]).xyzw) + (-((float4(0.25,0.25,0.25,0.25)).xyzw))); r[5].xyzw = _v.xyzw; }\n" ++ " { float4 _v = (float4)(((r[1]).xyzw) * (clamp(abs((r[5]).xyzw), -1.0, 1.0))); r[0].xyzw = _v.xyzw; }\n"); ++ check("soft_particle_export", hlsl, " float4 _o = r[0];\n"); ++ ++ /* The same program with the modifier cleared keeps the raw operand. */ ++ put_word(prog + 72, T_TEMP | REG(5) | SWZ_IDENT | (1u << 18)); ++ rsx_fp_decompile(prog, sizeof(prog), CTRL_32BIT, hlsl, sizeof(hlsl)); ++ check("soft_particle_no_mod", hlsl, "(((r[1]).xyzw) * (abs((r[5]).xyzw)))"); ++ check_absent("soft_particle_no_mod_clamp", hlsl, "clamp("); ++ } ++ + printf("\n===========================================\n"); + printf("Results: %d passed, %d failed\n", g_pass, g_fail); + return g_fail ? 1 : 0; diff --git a/tasks/sp00nznet__ps3recomp-670/solution/solve.sh b/tasks/sp00nznet__ps3recomp-670/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-670/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-670/task.toml b/tasks/sp00nznet__ps3recomp-670/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..17509c9768430efcfb9be0ba28681567034b75e4 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-670/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-670" +description = "Fragment programs: honour the per-source input precision modifiers" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/670" +source_access = "auto" +built_at = "2026-11-16T16:09:59.642244+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:45846761e542ac899be22104d3e3fb7c859b910d48214f9c8e58a564d5a65403" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/video/rsx_fp_decompiler.c", + "libs/video/tests/test_fp_decompiler.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 125 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.149191+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-670/tests/capture.py b/tasks/sp00nznet__ps3recomp-670/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-670/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-670/tests/instruction.md b/tasks/sp00nznet__ps3recomp-670/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a3bafe736e6fd0274e48f14cea99fe8d526405f4 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-670/tests/instruction.md @@ -0,0 +1,48 @@ +# Issue + +**Title:** Fragment programs: honour the per-source input precision modifiers + +## Description + +### Why + +DWORD2 bits 19-21, 22-24 and 25-27 hold a 3-bit input precision modifier for SRC0, SRC1 and SRC2. RPCS3 calls these fields `src0/1/2_prec_mod`; I read RPCS3 for this and copied nothing. The hardware clamps the operand to that precision's range after abs and before negate. The decompiler ignored the field. + +A downstream title showed it: a soft-particle fade `MUL r, tex, |depth difference|` with the depth source marked fixed9 was multiplied by the raw difference instead of a value in [0, 1], so every premultiplied particle drew saturated white. + +### Change + +Size: +125 lines, nothing removed. That is 39 lines in `rsx_fp_decompiler.c` and 86 lines of tests in `test_fp_decompiler.c`. + +- `Src.prec`, read from DWORD2 for non-branch instructions only (a branch's DWORD2 holds other fields). +- `fp_src_prec_clamp()`: 1 half [-65504, 65504], 2 fixed12 [-2, 2], 3 fixed9 [-1, 1], 4 saturate [0, 1]. Values 0 and 5-7 leave the operand unchanged. +- `emit_src` writes `clamp(abs(x), lo, hi)` and puts `-( )` around it for a negated source. It writes straight into the destination buffer, so there is no intermediate for -Wformat-truncation to warn about. + +ASSUMPTION: the ranges for values 1, 2 and 4 follow the destination-precision meaning of the same encodings and RPCS3's field names. Only modifier 3 has been seen in a real program (the fade above). + +### Tests + +All in `libs/video/tests/test_fp_decompiler.c`, using the same helpers and CI step as the existing cases: + +- `MAD r1, r0, r0, r0` with each of the 8 values in each of the 3 slots (24 cases). Values 1-4 expect `clamp((r[0]).xyzw, lo, hi)`; 0 and 5-7 expect no `clamp(`. +- Abs, clamp and negate order: `-(clamp(abs((r[0]).xyzw), -1.0, 1.0))`. +- A soft-particle fixture through the whole decompile: `TEX r1, TC0`; `TEX r5, TC1`; `ADD r5, r5, -{0.25}` (inline constant); `MUL r0, r1, |r5|` with SRC1 fixed9. It checks the four emitted body lines exactly and the single colour export. With the modifier cleared it checks that the operand stays `abs((r[5]).xyzw)` with no clamp. **The fixture is synthetic**: microcode words hand-encoded in the test, not taken from any title. + +CI's command line: `gcc -std=gnu17 -Wall -Wextra -I include -o t libs/video/tests/test_fp_decompiler.c libs/video/rsx_fp_decompiler.c && ./t` + +- master: 103 passed, 14 failed (all new cases). +- this branch: 117 passed, 0 failed, with both gcc 16.2 and clang 19.1. Also clean under gcc -O2 -fsanitize=address,undefined. +- The compiler warnings are the same as on master: two -Wcomment and, with gcc, two -Wformat-truncation in existing code. +- linux.yml, all 40 steps, run locally (not on GitHub) on master and on this branch, each with gcc 16.2 and with clang 19.1 (CMAKE_BUILD_TYPE=Release). The 39 steps after "Install dependencies" all pass, on both trees and with both compilers. That includes Configure, Build, the archive check, the lifter suites, the pad tests, guest shader translation, the boot smoke title, the game template, the POSIX host, sync_stress, fiber_switch and the self-contained RSX tests step, which runs `test_fp_decompiler`. "Install dependencies" (apt) was replaced by the same packages from nixpkgs: SDL2 is sdl2-compat 2.32.72 (the SDL2 API on SDL3), plus glslang 16.4, spirv-tools and spirv-cross 1.4.357. Not run: the Debug half of the build-type matrix, macos.yml, windows.yml (no macOS or Windows host here). + +Not run: MSVC/clang-cl, macOS, or a real title on this project's own backend. + +Overlap with open PRs: I took the current diff of each of the 90 open PRs for the files this branch touches and ran `git apply --check` against master and against this branch, whole and hunk by hunk. +- Apply cleanly on top of this branch: + - `rsx_fp_decompiler.c`: #601 (3/3 hunks), #635 (2/2). +- Conflict: #626 rewrites every line of `test_fp_decompiler.c` (line endings, one whole-file hunk), so whichever lands second needs a trivial rebase. +- Do not apply to master itself: #213 (`rsx_fp_decompiler.c`; 1 of its 3 hunks applies to master, and that one also applies here) and #447 (`rsx_fp_decompiler.c`, `test_fp_decompiler.c`; 2 of its 14 hunks apply to master, and both also apply here). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-670/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-670/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a653d0e8ed740c239a7df06afcf6b6d8e6771988 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-670/tests/oracle.patch @@ -0,0 +1,171 @@ +diff --git a/libs/video/rsx_fp_decompiler.c b/libs/video/rsx_fp_decompiler.c +index cfb9685b..58a4c91a 100644 +--- a/libs/video/rsx_fp_decompiler.c ++++ b/libs/video/rsx_fp_decompiler.c +@@ -315,9 +315,36 @@ typedef struct { + int half; + int negate; + int abs; ++ int prec; /* input precision modifier, 0 = none (see fp_src_prec_clamp) */ + char swz[5]; /* e.g. "xyzw" */ + } Src; + ++/* Each source operand carries a 3-bit input precision modifier in DWORD2: ++ * bits 19-21 for SRC0, 22-24 for SRC1, 25-27 for SRC2. The hardware clamps the ++ * operand to that precision's range after abs and before negate: ++ * 1 half [-65504, 65504] ++ * 2 fixed12 [-2, 2] ++ * 3 fixed9 [-1, 1] ++ * 4 saturate [0, 1] ++ * 0 (and the values above 4) leave the operand as it is. A soft-particle ++ * program that fades with MUL r, tex, |depth difference| and marks that source ++ * fixed9 relies on it: unclamped, the difference in metres saturates every ++ * fade to full opacity. */ ++#define FP_SRC0_PREC_SHIFT 19 ++#define FP_SRC1_PREC_SHIFT 22 ++#define FP_SRC2_PREC_SHIFT 25 ++ ++static const char* fp_src_prec_clamp(int prec) ++{ ++ switch (prec) { ++ case 1: return "-65504.0, 65504.0"; ++ case 2: return "-2.0, 2.0"; ++ case 3: return "-1.0, 1.0"; ++ case 4: return "0.0, 1.0"; ++ default: return NULL; ++ } ++} ++ + static void decode_src(u32 w, int abs_bit, Src* s) + { + static const char comp[4] = {'x','y','z','w'}; +@@ -326,6 +353,7 @@ static void decode_src(u32 w, int abs_bit, Src* s) + s->half = (w & FP_SRC_HALF) ? 1 : 0; + s->negate = (w & FP_SRC_NEGATE) ? 1 : 0; + s->abs = abs_bit ? 1 : 0; ++ s->prec = 0; + for (int i = 0; i < 4; i++) + s->swz[i] = comp[(w >> (FP_SRC_SWZ_SHIFT + 2 * i)) & 3]; + s->swz[4] = '\0'; +@@ -394,6 +422,12 @@ static void emit_src(const Src* s, u32 input_src, int persp, const float* k, int + const char* pre = ""; + const char* post = ""; + if (s->abs) { pre = "abs("; post = ")"; } ++ const char* range = fp_src_prec_clamp(s->prec); ++ if (range) { /* abs, then the precision clamp, then negate */ ++ snprintf(buf, bufsz, s->negate ? "-(clamp(%s%s%s, %s))" : "clamp(%s%s%s, %s)", ++ pre, swz, post, range); ++ return; ++ } + if (s->negate) snprintf(buf, bufsz, "-(%s%s%s)", pre, swz, post); + else snprintf(buf, bufsz, "%s%s%s", pre, swz, post); + } +@@ -780,6 +814,11 @@ static int rsx_fp_decompile_internal( + decode_src(w1, w1 & FP_SRC0_ABS, &s0); + decode_src(w2, w2 & FP_SRC1_ABS, &s1); + decode_src(w3, 0, &s2); ++ if (!(w2 & FP_BRANCH)) { /* a branch's DWORD2 holds other fields */ ++ s0.prec = (int)((w2 >> FP_SRC0_PREC_SHIFT) & 7u); ++ s1.prec = (int)((w2 >> FP_SRC1_PREC_SHIFT) & 7u); ++ s2.prec = (int)((w2 >> FP_SRC2_PREC_SHIFT) & 7u); ++ } + + /* Inline constant: any CONST source pulls the next 16 bytes as a + * float4 literal and advances past it. */ +diff --git a/libs/video/tests/test_fp_decompiler.c b/libs/video/tests/test_fp_decompiler.c +index 033d2528..e9c9c398 100644 +--- a/libs/video/tests/test_fp_decompiler.c ++++ b/libs/video/tests/test_fp_decompiler.c +@@ -591,6 +591,92 @@ int main(void) + + } + ++ /* Per-source input precision modifiers: DWORD2 bits 19-21 (SRC0), 22-24 ++ * (SRC1) and 25-27 (SRC2) clamp the operand after abs and before negate. ++ * 1 half, 2 fixed12, 3 fixed9, 4 saturate; 0 and 5-7 leave it alone. */ ++ { ++ static const char* const range[8] = { ++ NULL, "-65504.0, 65504.0", "-2.0, 2.0", "-1.0, 1.0", "0.0, 1.0", ++ NULL, NULL, NULL }; ++ static const char* const slot_name[3] = { "src0", "src1", "src2" }; ++ for (int slot = 0; slot < 3; slot++) { ++ for (u32 v = 0; v < 8; v++) { ++ u8 prog[16]; ++ u32 w1 = T_TEMP | REG(0) | SWZ_IDENT | EXEC_ALWAYS; ++ u32 w2 = T_TEMP | REG(0) | SWZ_IDENT; ++ u32 w3 = T_TEMP | REG(0) | SWZ_IDENT; ++ w2 |= v << (19 + 3 * slot); ++ put_word(prog + 0, OPC(0x04) | OUTMASK_ALL | OUTREG(1) | END); /* MAD r1, r0, r0, r0 */ ++ put_word(prog + 4, w1); ++ put_word(prog + 8, w2); ++ put_word(prog + 12, w3); ++ rsx_fp_decompile(prog, sizeof(prog), CTRL_32BIT, hlsl, sizeof(hlsl)); ++ char name[64], want[128]; ++ snprintf(name, sizeof name, "prec_mod_%s_%u", slot_name[slot], v); ++ if (range[v]) { ++ snprintf(want, sizeof want, "clamp((r[0]).xyzw, %s)", range[v]); ++ check(name, hlsl, want); ++ } else { ++ check_absent(name, hlsl, "clamp("); ++ } ++ } ++ } ++ ++ /* abs is applied first, then the clamp, then the negate: ++ * MUL r1, -|r0|, r0 with SRC0 fixed9. */ ++ u8 prog[16]; ++ put_word(prog + 0, OPC(0x02) | OUTMASK_ALL | OUTREG(1) | END); ++ put_word(prog + 4, T_TEMP | REG(0) | SWZ_IDENT | EXEC_ALWAYS | (1u << 29) | (1u << 17)); ++ put_word(prog + 8, T_TEMP | REG(0) | SWZ_IDENT | (3u << 19)); ++ put_word(prog + 12, 0); ++ rsx_fp_decompile(prog, sizeof(prog), CTRL_32BIT, hlsl, sizeof(hlsl)); ++ check("prec_mod_abs_clamp_negate", hlsl, ++ "-(clamp(abs((r[0]).xyzw), -1.0, 1.0))"); ++ } ++ ++ /* Soft-particle fade through the whole decompile: a synthetic, hand-encoded ++ * four-instruction program (not taken from any title) in the shape the ++ * clamp matters for, MUL r0, tex, |depth difference| with SRC1 fixed9. ++ * TEX r1, TC0, unit 0 particle colour ++ * TEX r5, TC1, unit 1 scene depth ++ * ADD r5, r5, -{0.25} minus the fragment's depth (inline const) ++ * MUL r0, r1, |r5| (fixed9) fade, END ++ * Without the clamp the colour is multiplied by the raw difference. */ ++ { ++ u8 prog[80]; ++ put_word(prog + 0, OPC(0x17) | OUTMASK_ALL | OUTREG(1) | INSRC(4) | TEXU(0)); ++ put_word(prog + 4, T_INPUT | SWZ_IDENT | EXEC_ALWAYS); ++ put_word(prog + 8, 0); ++ put_word(prog + 12, 0); ++ put_word(prog + 16, OPC(0x17) | OUTMASK_ALL | OUTREG(5) | INSRC(5) | TEXU(1)); ++ put_word(prog + 20, T_INPUT | SWZ_IDENT | EXEC_ALWAYS); ++ put_word(prog + 24, 0); ++ put_word(prog + 28, 0); ++ put_word(prog + 32, OPC(0x03) | OUTMASK_ALL | OUTREG(5)); ++ put_word(prog + 36, T_TEMP | REG(5) | SWZ_IDENT | EXEC_ALWAYS); ++ put_word(prog + 40, T_CONST | SWZ_IDENT | (1u << 17)); /* -CONST */ ++ put_word(prog + 44, 0); ++ for (int i = 0; i < 4; i++) put_float(prog + 48 + 4 * i, 0.25f); ++ put_word(prog + 64, OPC(0x02) | OUTMASK_ALL | OUTREG(0) | END); ++ put_word(prog + 68, T_TEMP | REG(1) | SWZ_IDENT | EXEC_ALWAYS); ++ put_word(prog + 72, T_TEMP | REG(5) | SWZ_IDENT | (1u << 18) | (3u << 22)); /* |r5|, fixed9 */ ++ put_word(prog + 76, 0); ++ int n = rsx_fp_decompile(prog, sizeof(prog), CTRL_32BIT, hlsl, sizeof(hlsl)); ++ check_true("soft_particle_count", n == 4); ++ check("soft_particle_body", hlsl, ++ " { float4 _v = (float4)(rsx_tex[0].Sample(rsx_samp[0], ((input.tc0).xyzw).xy)); r[1].xyzw = _v.xyzw; }\n" ++ " { float4 _v = (float4)(rsx_tex[1].Sample(rsx_samp[1], ((input.tc1).xyzw).xy)); r[5].xyzw = _v.xyzw; }\n" ++ " { float4 _v = (float4)(((r[5]).xyzw) + (-((float4(0.25,0.25,0.25,0.25)).xyzw))); r[5].xyzw = _v.xyzw; }\n" ++ " { float4 _v = (float4)(((r[1]).xyzw) * (clamp(abs((r[5]).xyzw), -1.0, 1.0))); r[0].xyzw = _v.xyzw; }\n"); ++ check("soft_particle_export", hlsl, " float4 _o = r[0];\n"); ++ ++ /* The same program with the modifier cleared keeps the raw operand. */ ++ put_word(prog + 72, T_TEMP | REG(5) | SWZ_IDENT | (1u << 18)); ++ rsx_fp_decompile(prog, sizeof(prog), CTRL_32BIT, hlsl, sizeof(hlsl)); ++ check("soft_particle_no_mod", hlsl, "(((r[1]).xyzw) * (abs((r[5]).xyzw)))"); ++ check_absent("soft_particle_no_mod_clamp", hlsl, "clamp("); ++ } ++ + printf("\n===========================================\n"); + printf("Results: %d passed, %d failed\n", g_pass, g_fail); + return g_fail ? 1 : 0; diff --git a/tasks/sp00nznet__ps3recomp-670/tests/test.sh b/tasks/sp00nznet__ps3recomp-670/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-670/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-670/tests/verifier.py b/tasks/sp00nznet__ps3recomp-670/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-670/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-671/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-671/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-671/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-671/instruction.md b/tasks/sp00nznet__ps3recomp-671/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2b08ac9d1eef733c8865b0729fff06d7aff47482 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-671/instruction.md @@ -0,0 +1,54 @@ +# Issue + +**Title:** cellAdec: decode AC3 through the run-time FFmpeg loader + +## Description + +### Why + +cellAdec returned silence for every codec: 1024 stereo samples (8192 bytes) per access unit. A downstream title sizes its PCM ring from bsiInfo+0x14 as channels x 4 bytes a sample. It then took 341 sample frames per AC3 frame instead of 1536, so an AC3 5.1 movie track lost most of its audio (and what was left was silence). + +### Change + +Size: +544/-33. The code is `cellAdec.c` (+253/-33). The rest is tests: `test_adec_ac3.c` (211 lines), `adec_tests.cmake` (52), `gen_adec_media.cmake` (26), and 2 lines in `libs/codec/tests/CMakeLists.txt`. + +- AC3 (codecType 2) decodes through `ps3_ffmpeg_get()`, the loader cellVdec already uses. No new FFmpeg symbols, nothing linked at build time. +- Output is interleaved big-endian float in the decoder's channel order, one 1536-sample frame per AU, with its size in the PcmItem and bsiInfo+0x14. +- StartSeq flushes the decoder and Close frees it. The AU bytes and info are copied before AUDONE, which hands the AU buffer back. +- Without a decoder (no FFmpeg build, `PS3RECOMP_FFMPEG=0`, or a damaged AU), AC3 gives silence of the real size: 1536 samples in the channel count that acmod + lfeon give (A/52 5.4.2), or 2 channels if the header is not AC3. +- Other codecs keep 1024 x 2. +- The PCM block (up to 48 KB) moves out of the 16 KB per-handle scratch into its own 64 KB per handle at VM_HLE_INJECT_BASE + 0x80000. +- FFmpeg is only called (LGPL, separate libraries), as cellVdec already does. + +### Tests + +They mirror the cellVdec ones: + +- `libs/codec/tests/test_adec_ac3.c` includes `../cellAdec.c` with the same runtime stand-ins as `test_vdec_decode.c`. +- `gen_adec_media.cmake` uses the ffmpeg program at test time to make 5.1 and 2.0 AC3 at 448 kb/s, plus FFmpeg's own f32 decode of the 5.1 file as the reference. +- `adec_tests.cmake` is included from `libs/codec/tests/CMakeLists.txt`. `.gitignore` ignores `*.cmake`, so the two new .cmake files were added with `git add -f`, as `gen_vdec_media.cmake` was. + +ctest: `adec_media_gen`; `adec_ac3_stub` (no FFmpeg: 36864 / 12288 / 8192 byte silences); `adec_ac3_disabled` (`PS3RECOMP_FFMPEG=0`); `adec_ac3_decode` (13 AUs, 119808 samples equal to FFmpeg's decode; swapped channels and a dropped AU are caught; exit 77 = skipped when libavcodec cannot load). + +How I ran them, all with FFmpeg 9.0.1 headers and libavcodec 63.1 on Linux: + +- **Whole tree with `-DPS3RECOMP_FFMPEG_RUNTIME=ON -DPS3RECOMP_BUILD_TESTS=ON`** (Release; gcc 16.2 and clang 19.1): configures and builds on master and on this branch. + - `ctest -R 'adec|vdec'` on this branch: the 4 adec tests pass with both compilers. + - 4 cellVdec tests (`vdec_idle_avc`, `vdec_idle_off_avc`, `vdec_idle_mpeg2`, `vdec_idle_off_mpeg2`) fail on master and on this branch alike, with both compilers. They are unrelated to this change, but worth knowing before reading CI. + - On master the new test does not compile (no `adec_ac3_channels`, no `ff` in `AdecSlot`). +- **What master does with the same input.** The new test cannot build against master, so I compiled a small probe against master's `cellAdec.c` and against this branch's (both without FFmpeg, gcc and clang). The probe drives the same guest-API path as `test_adec_ac3.c`: the same runtime stand-ins, `cellAdecOpen` for AC3, `cellAdecDecodeAu`, `cellAdecGetPcmItem`, `cellAdecGetPcm`. It feeds the first 3 AUs of the 5.1 and the 2.0 test streams, made at test time by `gen_adec_media.cmake` with the local ffmpeg. + - Master: every AU gives a PcmItem size and bsiInfo+0x14 of **8192** bytes of silence, for 5.1 and 2.0 alike. + - This branch without a decoder: **36864** for 5.1 and **12288** for 2.0 (also silence). + - With FFmpeg, the PCM is the real decode (`adec_ac3_decode` above). + The probe is not part of the PR. +- linux.yml, all 40 steps, run locally (not on GitHub) on master and on this branch, each with gcc 16.2 and with clang 19.1 (CMAKE_BUILD_TYPE=Release). The 39 steps after "Install dependencies" all pass, on both trees and with both compilers. That includes Configure, Build, the archive check, the lifter suites, the pad tests, guest shader translation, the boot smoke title, the game template, the POSIX host, sync_stress, fiber_switch. "Install dependencies" (apt) was replaced by the same packages from nixpkgs: SDL2 is sdl2-compat 2.32.72 (the SDL2 API on SDL3), plus glslang 16.4, spirv-tools and spirv-cross 1.4.357. Not run: the Debug half of the build-type matrix, macos.yml, windows.yml (no macOS or Windows host here). + +Not run: the Windows and macOS jobs, MSVC, or a real title on this project's own backend. + +Overlap with open PRs: I took the current diff of each of the 90 open PRs for the files this branch touches and ran `git apply --check` against master and against this branch, whole and hunk by hunk. +- Only #213 touches them (`cellAdec.c`). It does not apply to master itself: none of its 3 hunks there applies to master, so it needs a rebase whichever lands first. +- No other open PR touches `cellAdec.c` or `libs/codec/tests/`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-671/solution/patch.diff b/tasks/sp00nznet__ps3recomp-671/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..17d4e9c1b81951418acdca30b6a6dc7cfb8929fb --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-671/solution/patch.diff @@ -0,0 +1,712 @@ +diff --git a/libs/codec/cellAdec.c b/libs/codec/cellAdec.c +index 9bacce2d..c32d7676 100644 +--- a/libs/codec/cellAdec.c ++++ b/libs/codec/cellAdec.c +@@ -1,9 +1,12 @@ + /* + * ps3recomp - cellAdec HLE implementation + * +- * Stub audio decoder. Accepts AU data and delivers AUDONE callbacks. +- * Actual decoding (AAC, ATRAC3+, etc.) requires integration with +- * an audio codec library (e.g., FFmpeg). ++ * Audio decoder. Accepts AU data and delivers AUDONE + PCMOUT callbacks. ++ * AC3 decodes through FFmpeg loaded at run time (PS3RECOMP_FFMPEG_RUNTIME, ++ * ffmpeg_runtime.c, the loader cellVdec uses) into interleaved big-endian ++ * float PCM, one 1536-sample frame per AU in the stream's own channels. ++ * Every other codec, and AC3 when FFmpeg is absent or PS3RECOMP_FFMPEG=0, ++ * delivers silence of the codec's frame size. + */ + + #include "cellAdec.h" +@@ -16,6 +19,7 @@ + #include "ps3emu/guest_call.h" /* g_ps3_guest_caller -- cbFunc is a GUEST OPD */ + #include "../../runtime/memory/vm.h" /* VM_HLE_INJECT_BASE */ + #include "ps3emu/log_first.h" ++#include "ffmpeg_runtime.h" /* PS3FFmpeg; empty without PS3RECOMP_FFMPEG_RUNTIME */ + + /* CellAdecPcmItem as the guest reads it, from RPCS3 Modules/cellAdec.h:339. + * ps1_netemu copies the whole thing out with six 8-byte loads from offsets +@@ -34,12 +38,20 @@ + #define PCMITEM_AU_USERDATA 0x28u + #define PCMITEM_BYTES 0x30u + +-/* ponytail: one fixed-size silence buffer per handle, 1024 stereo float samples +- * -- the ATRAC3 frame this title (codecType 5) decodes. The ceiling is that it +- * is SILENCE and always this size; wire a real decoder in here when the audio +- * itself matters, without changing the guest-visible contract. */ ++/* PCM per AU, float (4 bytes a sample), interleaved. ++ * - AC3: one A/52 frame is 1536 samples (6 blocks of 256) in the frame's own ++ * channels (acmod + LFE from its header: 6 for a 5.1 track). A movie ++ * player that sizes its ring as channels x 4 bytes a sample and takes each ++ * AU's PCM size from bsiInfo+0x14 needs the block to be the real frame: ++ * 1024 stereo samples (8 KB) fed its 5.1 mixer a third of the audio an AU ++ * stands for. ++ * - the other codecs: 1024 stereo float samples of silence, the ATRAC3 frame ++ * the first title on this stub (codecType 5) decodes. */ + #define ADEC_PCM_SAMPLES 1024u + #define ADEC_PCM_BYTES (ADEC_PCM_SAMPLES * 2u * 4u) ++#define ADEC_AC3_SAMPLES 1536u ++/* The largest block one AU produces here: an AC3 frame in 7.1. */ ++#define ADEC_PCM_MAX_BYTES (ADEC_AC3_SAMPLES * 8u * 4u) + + /* Guest-visible scratch, in the HLE inject window rather than from the guest's + * own heap. Taking 8 KB out of that heap in cellAdecOpen stalled the title +@@ -53,7 +65,10 @@ + #define ADEC_SCRATCH_BASE (VM_HLE_INJECT_BASE + 0x40000u) + #define ADEC_SCRATCH_STRIDE 0x4000u + #define ADEC_ITEM_EA(h) (ADEC_SCRATCH_BASE + (u32)(h) * ADEC_SCRATCH_STRIDE) +-#define ADEC_PCM_EA(h) (ADEC_ITEM_EA(h) + 0x100u) ++/* The PCM block is up to 48 KB (ADEC_PCM_MAX_BYTES), more than the 16 KB ++ * stride holds, so it lives in its own 64 KB per handle at +0x80000..+0xC0000, ++ * past cellVdec's pic items at +0x50000. */ ++#define ADEC_PCM_EA(h) (VM_HLE_INJECT_BASE + 0x80000u + (u32)(h) * 0x10000u) + /* The codec info block the PcmItem's bsiInfo points to, in the gap between + * the 0x30-byte item and the PCM buffer. */ + #define ADEC_BSI_EA(h) (ADEC_ITEM_EA(h) + 0x40u) +@@ -73,11 +88,176 @@ typedef struct { + u32 itemEa; /* guest EA of the 0x30-byte CellAdecPcmItem */ + u32 pcmEa; /* guest EA of the PCM buffer it points at */ + int hasPcm; ++ u32 pcmBytes; /* size of the PCM block at pcmEa */ + u32 auCount; /* total AUs decoded */ ++ void* ff; /* AdecFf: the libavcodec decoder, or NULL */ ++ u8* au; /* host copy of the AU being decoded */ ++ u32 auCap; + } AdecSlot; + + static AdecSlot s_adec[MAX_ADEC]; + ++/* --------------------------------------------------------------------------- ++ * AC3 frame header: the frame's channel count (A/52 5.4.2), for the size of ++ * the silent block when there is no decoder. 0 when it is not an AC3 frame. ++ * -----------------------------------------------------------------------*/ ++static u32 adec_ac3_channels(const u8* f, u32 n) ++{ ++ static const u8 nfchans[8] = { 2, 1, 2, 3, 3, 4, 4, 5 }; ++ if (!f || n < 8 || f[0] != 0x0B || f[1] != 0x77) return 0; ++ if ((f[5] >> 3) > 10) return 0; /* bsid > 10: E-AC3, not parsed */ ++ u32 bits = ((u32)f[6] << 8) | f[7]; /* acmod(3) [cmixlev surmixlev dsurmod] lfeon */ ++ u32 acmod = bits >> 13; ++ int pos = 3; ++ if ((acmod & 1u) && acmod != 1u) pos += 2; /* cmixlev */ ++ if (acmod & 4u) pos += 2; /* surmixlev */ ++ if (acmod == 2u) pos += 2; /* dsurmod */ ++ return nfchans[acmod] + ((bits >> (15 - pos)) & 1u); ++} ++ ++/* --------------------------------------------------------------------------- ++ * libavcodec back end (AC3) ++ * -----------------------------------------------------------------------*/ ++#ifdef PS3RECOMP_FFMPEG_RUNTIME ++ ++typedef struct AdecFf { ++ const PS3FFmpeg* ff; ++ AVCodecContext* ctx; ++ AVPacket* pkt; ++ AVFrame* frame; ++ u8* buf; /* the AU plus FFmpeg's zeroed input padding */ ++ u32 bufCap; ++ u32* pcm; /* big-endian float words, ADEC_PCM_MAX_BYTES */ ++} AdecFf; ++ ++static void adec_ff_close(void* p) ++{ ++ AdecFf* d = (AdecFf*)p; ++ if (!d) return; ++ if (d->ctx) d->ff->avcodec_free_context(&d->ctx); ++ if (d->pkt) d->ff->av_packet_free(&d->pkt); ++ if (d->frame) d->ff->av_frame_free(&d->frame); ++ free(d->buf); ++ free(d->pcm); ++ free(d); ++} ++ ++static void* adec_ff_open(u32 codec_type) ++{ ++ if (codec_type != CELL_ADEC_TYPE_AC3) return NULL; ++ const PS3FFmpeg* ff = ps3_ffmpeg_get(); ++ if (!ff) return NULL; ++ const AVCodec* codec = ff->avcodec_find_decoder(AV_CODEC_ID_AC3); ++ if (!codec) { ++ printf("[cellAdec] libavcodec has no AC3 decoder; silence\n"); ++ return NULL; ++ } ++ AdecFf* d = (AdecFf*)calloc(1, sizeof(*d)); ++ if (!d) return NULL; ++ d->ff = ff; ++ d->ctx = ff->avcodec_alloc_context3(codec); ++ d->pkt = ff->av_packet_alloc(); ++ d->frame = ff->av_frame_alloc(); ++ d->pcm = (u32*)malloc(ADEC_PCM_MAX_BYTES); ++ if (!d->ctx || !d->pkt || !d->frame || !d->pcm || ++ ff->avcodec_open2(d->ctx, codec, NULL) < 0) { ++ printf("[cellAdec] could not open the libavcodec AC3 decoder; silence\n"); ++ adec_ff_close(d); ++ return NULL; ++ } ++ return d; ++} ++ ++static void adec_ff_flush(void* p) ++{ ++ AdecFf* d = (AdecFf*)p; ++ if (d) d->ff->avcodec_flush_buffers(d->ctx); ++} ++ ++static float adec_ff_sample(const AVFrame* f, int ch, int c, int s) ++{ ++ const u8* const* x = (const u8* const*)f->extended_data; ++ switch (f->format) { ++ case AV_SAMPLE_FMT_FLTP: return ((const float*)x[c])[s]; ++ case AV_SAMPLE_FMT_FLT: return ((const float*)x[0])[s * ch + c]; ++ case AV_SAMPLE_FMT_S16P: return ((const int16_t*)x[c])[s] * (1.0f / 32768.0f); ++ case AV_SAMPLE_FMT_S16: return ((const int16_t*)x[0])[s * ch + c] * (1.0f / 32768.0f); ++ case AV_SAMPLE_FMT_S32P: return (float)((const int32_t*)x[c])[s] * (1.0f / 2147483648.0f); ++ case AV_SAMPLE_FMT_S32: return (float)((const int32_t*)x[0])[s * ch + c] * (1.0f / 2147483648.0f); ++ default: return 0.0f; ++ } ++} ++ ++/* Decode one AU and store its PCM at guest dst as interleaved big-endian ++ * float, frame after frame. Returns the bytes stored (0: nothing came out); ++ * *channels gets the last frame's channel count. */ ++static u32 adec_ff_decode(void* p, const u8* au, u32 size, u32 dst, u32* channels) ++{ ++ AdecFf* d = (AdecFf*)p; ++ const PS3FFmpeg* ff = d->ff; ++ if (size + AV_INPUT_BUFFER_PADDING_SIZE > d->bufCap) { ++ u8* nb = (u8*)realloc(d->buf, size + AV_INPUT_BUFFER_PADDING_SIZE); ++ if (!nb) return 0; ++ d->buf = nb; ++ d->bufCap = size + AV_INPUT_BUFFER_PADDING_SIZE; ++ } ++ memcpy(d->buf, au, size); ++ memset(d->buf + size, 0, AV_INPUT_BUFFER_PADDING_SIZE); ++ d->pkt->data = d->buf; ++ d->pkt->size = (int)size; ++ int r = ff->avcodec_send_packet(d->ctx, d->pkt); ++ d->pkt->data = NULL; ++ d->pkt->size = 0; ++ u32 out = 0; ++ if (r < 0) { ++ static int _n = 0; ++ if (PS3_LOG_FIRST(_n, 8)) ++ printf("[cellAdec] AC3 AU of %u bytes did not decode (%d)\n", size, r); ++ } ++ for (;;) { ++ AVFrame* f = d->frame; ++ if (ff->avcodec_receive_frame(d->ctx, f) < 0) ++ break; /* EAGAIN / EOF / error */ ++ int ch = f->ch_layout.nb_channels, ns = f->nb_samples; ++ u32 bytes = (u32)ns * (u32)ch * 4u; ++ if (ch < 1 || ch > 8 || ns <= 0 || out + bytes > ADEC_PCM_MAX_BYTES) { ++ static int _n = 0; ++ if (PS3_LOG_FIRST(_n, 4)) ++ printf("[cellAdec] dropping a decoded frame (%d samples x %d ch, %u bytes held)\n", ++ ns, ch, out); ++ ff->av_frame_unref(f); ++ continue; ++ } ++ u32 i = 0; ++ for (int s = 0; s < ns; s++) ++ for (int c = 0; c < ch; c++) { ++ float v = adec_ff_sample(f, ch, c, s); ++ u32 w; ++ memcpy(&w, &v, 4); ++ d->pcm[i++] = (w >> 24) | ((w >> 8) & 0xFF00u) | ((w << 8) & 0xFF0000u) | (w << 24); ++ } ++ vm_memcpy_to(dst + out, d->pcm, bytes); ++ { static int _n = 0; ++ if (PS3_LOG_FIRST(_n, 1)) ++ printf("[cellAdec] AC3 through libavcodec: %d samples x %d ch at %d Hz, %u bytes an AU\n", ++ ns, ch, f->sample_rate, bytes); } ++ out += bytes; ++ *channels = (u32)ch; ++ ff->av_frame_unref(f); ++ } ++ return out; ++} ++ ++#else /* !PS3RECOMP_FFMPEG_RUNTIME */ ++ ++static void* adec_ff_open(u32 codec_type) { (void)codec_type; return NULL; } ++static void adec_ff_close(void* p) { (void)p; } ++static void adec_ff_flush(void* p) { (void)p; } ++static u32 adec_ff_decode(void* p, const u8* au, u32 size, u32 dst, u32* channels) ++{ (void)p; (void)au; (void)size; (void)dst; (void)channels; return 0; } ++ ++#endif /* PS3RECOMP_FFMPEG_RUNTIME */ ++ + /* Fire one guest callback. + * + * The guest's cbFunc is a guest EA naming an OPD, so it goes through the +@@ -164,9 +344,11 @@ s32 cellAdecOpen(const CellAdecType* type, const CellAdecResource* res, + * once already. */ + s_adec[i].itemEa = ADEC_ITEM_EA(i); + s_adec[i].pcmEa = ADEC_PCM_EA(i); ++ s_adec[i].ff = adec_ff_open(codec_type); + vm_write32(handle_ea, (u32)i); +- printf("[cellAdec] Open -> handle=%u item=0x%08X pcm=0x%08X\n", +- i, s_adec[i].itemEa, s_adec[i].pcmEa); ++ printf("[cellAdec] Open -> handle=%u item=0x%08X pcm=0x%08X%s\n", ++ i, s_adec[i].itemEa, s_adec[i].pcmEa, ++ s_adec[i].ff ? " (decoding with libavcodec)" : ""); + return CELL_OK; + } + } +@@ -180,6 +362,11 @@ s32 cellAdecClose(CellAdecHandle handle) + if (handle >= MAX_ADEC || !s_adec[handle].in_use) + return (s32)CELL_ADEC_ERROR_ARG; + ++ adec_ff_close(s_adec[handle].ff); ++ free(s_adec[handle].au); ++ s_adec[handle].ff = NULL; ++ s_adec[handle].au = NULL; ++ s_adec[handle].auCap = 0; + s_adec[handle].in_use = 0; + return CELL_OK; + } +@@ -193,6 +380,7 @@ s32 cellAdecStartSeq(CellAdecHandle handle, void* param) + return (s32)CELL_ADEC_ERROR_ARG; + + s_adec[handle].seqStarted = 1; ++ adec_ff_flush(s_adec[handle].ff); /* a new sequence starts clean */ + return CELL_OK; + } + +@@ -233,49 +421,78 @@ s32 cellAdecDecodeAu(CellAdecHandle handle, const CellAdecAuInfo* auInfo) + return (s32)CELL_ADEC_ERROR_ARG; + + AdecSlot* a = &s_adec[handle]; ++ const u32 au = GUEST_EA(auInfo); ++ const u32 au_addr = vm_read32(au + (u32)offsetof(CellAdecAuInfo, startAddr)); ++ const u32 au_size = vm_read32(au + (u32)offsetof(CellAdecAuInfo, size)); ++ /* The AU info, read before AUDONE gives it back to the title. */ ++ const u32 au_w[4] = { vm_read32(au + 0x08), vm_read32(au + 0x0C), ++ vm_read32(au + 0x10), vm_read32(au + 0x14) }; + + printf("[cellAdec] DecodeAu(handle=%u, addr=0x%X, size=%u)\n", +- handle, vm_read32(GUEST_EA(auInfo) + (u32)offsetof(CellAdecAuInfo, startAddr)), +- vm_read32(GUEST_EA(auInfo) + (u32)offsetof(CellAdecAuInfo, size))); ++ handle, au_addr, au_size); ++ ++ /* The AC3 bytes are copied out first, too: AUDONE hands their buffer back ++ * to the title's demuxer, which may refill it at once. */ ++ const u8* data = NULL; ++ if (a->codecType == CELL_ADEC_TYPE_AC3 && au_addr && au_size && au_size <= 0x10000u) { ++ if (au_size > a->auCap) { ++ u8* nb = (u8*)realloc(a->au, au_size); ++ if (nb) { a->au = nb; a->auCap = au_size; } ++ } ++ if (au_size <= a->auCap) { ++ vm_memcpy_from(a->au, au_addr, au_size); ++ data = a->au; ++ } ++ } + + /* Step 1: report the AU consumed. msgData is the AU INFO ADDRESS, not a + * status -- see RPCS3 Modules/cellAdec.cpp:1345. A decoder that tracks its + * outstanding AUs by address gets a null back if this is CELL_OK. */ +- adec_notify(handle, CELL_ADEC_MSG_TYPE_AUDONE, (s32)GUEST_EA(auInfo)); ++ adec_notify(handle, CELL_ADEC_MSG_TYPE_AUDONE, (s32)au); + +- /* Step 2: Generate PCMOUT callback with dummy PCM info. +- * Without FFmpeg, we produce silence. But games that check for +- * decode completion via callbacks will proceed correctly. */ ++ /* Step 2: the PCM. AC3 through libavcodec when it is there; otherwise ++ * silence of the codec's frame size (AC3: 1536 samples in the frame's ++ * channels), so a title that counts PCM against time still runs. */ + a->auCount++; + { +- const u32 au = GUEST_EA(auInfo); + const u32 it = a->itemEa; +- for (u32 o = 0; o < ADEC_PCM_BYTES; o += 4) vm_write32(a->pcmEa + o, 0); ++ u32 ch = 0; ++ u32 bytes = (a->ff && data) ? adec_ff_decode(a->ff, data, au_size, a->pcmEa, &ch) : 0; ++ if (bytes == 0) { ++ if (a->codecType == CELL_ADEC_TYPE_AC3) { ++ ch = adec_ac3_channels(data, data ? au_size : 0); ++ bytes = ADEC_AC3_SAMPLES * (ch ? ch : 2u) * 4u; ++ } else { ++ bytes = ADEC_PCM_BYTES; ++ } ++ vm_memset(a->pcmEa, 0, bytes); ++ } ++ a->pcmBytes = bytes; + + vm_write32(it + PCMITEM_PCM_HANDLE, (u32)handle); + vm_write32(it + PCMITEM_STATUS, 0); /* CELL_OK */ + vm_write32(it + PCMITEM_START_ADDR, a->pcmEa); +- vm_write32(it + PCMITEM_SIZE, ADEC_PCM_BYTES); ++ vm_write32(it + PCMITEM_SIZE, bytes); + /* bsiInfo must point at a codec info block, not be null. Resistance: + * Fall of Man sizes each AC3 block from bsiInfo+0x14; with a null + * pointer that read address 0x14 and came back 0, so its ring buffer + * never filled, it never started its audio port, and its movie player +- * waited forever. ponytail: only that output-size word is filled; the +- * rest of the block is zero until a title reads another field. */ ++ * waited forever. Other titles' PCMOUT handlers take the AU's ++ * PCM size from the same word. ponytail: only that output-size word is ++ * filled; the rest of the block is zero until a title reads another ++ * field. */ + const u32 bsi = ADEC_BSI_EA(handle); + for (u32 o = 0; o < ADEC_BSI_BYTES; o += 4) vm_write32(bsi + o, 0); +- vm_write32(bsi + 0x14, ADEC_PCM_BYTES); ++ vm_write32(bsi + 0x14, bytes); + vm_write32(it + PCMITEM_BSI_INFO, bsi); + /* Echo the AU back, which is what a real decoder does -- the guest + * matches returned PCM against the AU it submitted. */ +- vm_write32(it + PCMITEM_AU_START, +- vm_read32(au + (u32)offsetof(CellAdecAuInfo, startAddr))); +- vm_write32(it + PCMITEM_AU_SIZE, +- vm_read32(au + (u32)offsetof(CellAdecAuInfo, size))); +- vm_write32(it + PCMITEM_AU_PTS_HI, vm_read32(au + 0x08)); +- vm_write32(it + PCMITEM_AU_PTS_LO, vm_read32(au + 0x0C)); +- vm_write32(it + PCMITEM_AU_USERDATA, vm_read32(au + 0x10)); +- vm_write32(it + PCMITEM_AU_USERDATA + 4, vm_read32(au + 0x14)); ++ vm_write32(it + PCMITEM_AU_START, au_addr); ++ vm_write32(it + PCMITEM_AU_SIZE, au_size); ++ vm_write32(it + PCMITEM_AU_PTS_HI, au_w[0]); ++ vm_write32(it + PCMITEM_AU_PTS_LO, au_w[1]); ++ vm_write32(it + PCMITEM_AU_USERDATA, au_w[2]); ++ vm_write32(it + PCMITEM_AU_USERDATA + 4, au_w[3]); + } + a->hasPcm = 1; + +@@ -295,10 +512,13 @@ s32 cellAdecGetPcm(CellAdecHandle handle, void* outBuffer) + if (!s_adec[handle].hasPcm) + return (s32)CELL_ADEC_ERROR_EMPTY; + +- /* outBuffer is the GUEST's buffer. Leaving it untouched hands the title +- * whatever happened to be there, which it then plays. */ ++ /* outBuffer is the GUEST's buffer: the AU's PCM block goes there, the ++ * size the item and bsiInfo+0x14 announced. Leaving it untouched hands the ++ * title whatever happened to be there, which it then plays. */ + { const u32 out = GUEST_EA(outBuffer); +- if (out) for (u32 o = 0; o < ADEC_PCM_BYTES; o += 4) vm_write32(out + o, 0); } ++ const AdecSlot* a = &s_adec[handle]; ++ if (out && a->pcmBytes) ++ vm_memcpy_to(out, vm_ptr8(a->pcmEa), a->pcmBytes); } + + s_adec[handle].hasPcm = 0; + return CELL_OK; +diff --git a/libs/codec/tests/CMakeLists.txt b/libs/codec/tests/CMakeLists.txt +index f3f8670d..ec7a1499 100644 +--- a/libs/codec/tests/CMakeLists.txt ++++ b/libs/codec/tests/CMakeLists.txt +@@ -4,6 +4,8 @@ if(UNIX) + set(VDEC_TEST_LIBS m) + endif() + ++include("${CMAKE_CURRENT_SOURCE_DIR}/adec_tests.cmake") ++ + # The callback-only decoder, as every build without FFmpeg has it. + add_executable(test_vdec_stub test_vdec_decode.c) + target_include_directories(test_vdec_stub PRIVATE "${PROJECT_SOURCE_DIR}/include") +diff --git a/libs/codec/tests/adec_tests.cmake b/libs/codec/tests/adec_tests.cmake +new file mode 100644 +index 00000000..94a58c42 +--- /dev/null ++++ b/libs/codec/tests/adec_tests.cmake +@@ -0,0 +1,52 @@ ++# cellAdec AC3, driven through its guest API (test_adec_ac3.c). Included from ++# CMakeLists.txt. The streams are made by the ffmpeg program at test time. ++find_program(PS3RECOMP_FFMPEG_EXECUTABLE ffmpeg) ++if(NOT PS3RECOMP_FFMPEG_EXECUTABLE) ++ message(STATUS " FFmpeg: no ffmpeg program; cellAdec AC3 tests not added") ++ return() ++endif() ++ ++set(ADEC_MEDIA "${CMAKE_CURRENT_BINARY_DIR}/adec_media") ++add_test(NAME adec_media_gen COMMAND "${CMAKE_COMMAND}" ++ -DFFMPEG=${PS3RECOMP_FFMPEG_EXECUTABLE} -DOUT=${ADEC_MEDIA} ++ -P "${CMAKE_CURRENT_SOURCE_DIR}/gen_adec_media.cmake") ++set_tests_properties(adec_media_gen PROPERTIES FIXTURES_SETUP adec_media) ++ ++# Without FFmpeg: silence of the real AC3 frame size. ++add_executable(test_adec_stub test_adec_ac3.c) ++target_include_directories(test_adec_stub PRIVATE "${PROJECT_SOURCE_DIR}/include") ++target_link_libraries(test_adec_stub PRIVATE ${VDEC_TEST_LIBS}) ++add_test(NAME adec_ac3_stub COMMAND test_adec_stub stub ++ ${ADEC_MEDIA}/t51.ac3 ${ADEC_MEDIA}/t20.ac3) ++set_tests_properties(adec_ac3_stub PROPERTIES FIXTURES_REQUIRED adec_media) ++ ++if(NOT PS3RECOMP_FFMPEG_RUNTIME) ++ return() ++endif() ++ ++add_executable(test_adec_ffmpeg test_adec_ac3.c) ++target_include_directories(test_adec_ffmpeg PRIVATE ++ "${PROJECT_SOURCE_DIR}/include" "${PS3RECOMP_FFMPEG_INCLUDE_DIR}") ++target_compile_definitions(test_adec_ffmpeg PRIVATE PS3RECOMP_FFMPEG_RUNTIME) ++target_link_libraries(test_adec_ffmpeg PRIVATE ${VDEC_TEST_LIBS} ${CMAKE_DL_LIBS}) ++ ++# Where the system's libavcodec is, as for the cellVdec tests below. ++find_library(PS3RECOMP_AVCODEC_LIBRARY NAMES avcodec) ++set(ADEC_LIB_ENV "") ++if(PS3RECOMP_AVCODEC_LIBRARY AND UNIX) ++ get_filename_component(ADEC_LIB_DIR "${PS3RECOMP_AVCODEC_LIBRARY}" DIRECTORY) ++ if(APPLE) ++ set(ADEC_LIB_ENV "DYLD_LIBRARY_PATH=${ADEC_LIB_DIR}") ++ else() ++ set(ADEC_LIB_ENV "LD_LIBRARY_PATH=${ADEC_LIB_DIR}") ++ endif() ++endif() ++ ++add_test(NAME adec_ac3_disabled COMMAND test_adec_ffmpeg stub ++ ${ADEC_MEDIA}/t51.ac3 ${ADEC_MEDIA}/t20.ac3) ++set_tests_properties(adec_ac3_disabled PROPERTIES ++ ENVIRONMENT "PS3RECOMP_FFMPEG=0;${ADEC_LIB_ENV}" FIXTURES_REQUIRED adec_media) ++add_test(NAME adec_ac3_decode COMMAND test_adec_ffmpeg decode ++ ${ADEC_MEDIA}/t51.ac3 ${ADEC_MEDIA}/t51.f32) ++set_tests_properties(adec_ac3_decode PROPERTIES ++ ENVIRONMENT "${ADEC_LIB_ENV}" FIXTURES_REQUIRED adec_media SKIP_RETURN_CODE 77) +diff --git a/libs/codec/tests/gen_adec_media.cmake b/libs/codec/tests/gen_adec_media.cmake +new file mode 100644 +index 00000000..39956f77 +--- /dev/null ++++ b/libs/codec/tests/gen_adec_media.cmake +@@ -0,0 +1,26 @@ ++# Generates the AC3 streams test_adec_ac3 feeds through cellAdec, and FFmpeg's ++# own decode of the 5.1 one as the reference. Nothing here is committed: ++# everything is written to the build tree at test time. ++# ++# cmake -DFFMPEG=<ffmpeg> -DOUT=<dir> -P gen_adec_media.cmake ++# ++# 448 kb/s at 48 kHz makes every frame 1792 bytes. A different tone on each ++# channel, so a channel swap shows. ++if(NOT FFMPEG OR NOT OUT) ++ message(FATAL_ERROR "pass -DFFMPEG=<ffmpeg> -DOUT=<dir>") ++endif() ++file(MAKE_DIRECTORY "${OUT}") ++ ++function(run) ++ execute_process(COMMAND "${FFMPEG}" -nostdin -hide_banner -loglevel error -y ${ARGN} ++ RESULT_VARIABLE rc) ++ if(NOT rc EQUAL 0) ++ message(FATAL_ERROR "ffmpeg failed (${rc}): ${ARGN}") ++ endif() ++endfunction() ++ ++run(-f lavfi -i "aevalsrc=0.5*sin(2*PI*330*t)|0.4*sin(2*PI*440*t)|0.3*sin(2*PI*550*t)|0.2*sin(2*PI*60*t)|0.3*sin(2*PI*660*t)|0.25*sin(2*PI*770*t):s=48000:c=5.1:d=0.4" ++ -c:a ac3 -b:a 448k -f ac3 "${OUT}/t51.ac3") ++run(-f lavfi -i "aevalsrc=0.5*sin(2*PI*330*t)|0.4*sin(2*PI*440*t):s=48000:c=stereo:d=0.2" ++ -c:a ac3 -b:a 448k -f ac3 "${OUT}/t20.ac3") ++run(-i "${OUT}/t51.ac3" -f f32le "${OUT}/t51.f32") +diff --git a/libs/codec/tests/test_adec_ac3.c b/libs/codec/tests/test_adec_ac3.c +new file mode 100644 +index 00000000..c52be176 +--- /dev/null ++++ b/libs/codec/tests/test_adec_ac3.c +@@ -0,0 +1,211 @@ ++/* ++ * cellAdec AC3, driven through its guest API. ++ * ++ * Built twice by CMakeLists.txt (adec_tests.cmake): ++ * without PS3RECOMP_FFMPEG_RUNTIME mode "stub" ++ * with it modes "stub" (PS3RECOMP_FFMPEG=0) and "decode" ++ * Modes: ++ * stub AC3 AC3_2CH AC3 5.1 frames give 1536 x 6 float of silence (36864 bytes in the PcmItem size, in ++ * bsiInfo+0x14 and through cellAdecGetPcm), 2.0 frames 1536 x 2 (12288), codecType 5 ++ * the old 1024 x 2 (8192); AUDONE then PCMOUT for every AU. ++ * decode AC3 REF every AU of a 5.1 AC3 stream through cellAdecDecodeAu; the PCM handed to the guest ++ * (big-endian float, interleaved) must equal FFmpeg's own decode REF (f32le) sample ++ * for sample. Negative controls: two channels swapped and one AU dropped must both ++ * be caught. ++ * The AC3 files are CBR 448 kb/s at 48 kHz, so every frame (= AU) is 1792 bytes (gen_adec_media.cmake). ++ */ ++#include "../cellAdec.c" ++#ifdef PS3RECOMP_FFMPEG_RUNTIME ++#include "../ffmpeg_runtime.c" ++#endif ++ ++#include <math.h> ++#include <stdlib.h> ++ ++/* What the runtime would provide (the same stand-ins test_vdec_decode.c uses). */ ++uint8_t* vm_base; ++uint32_t ppu_vm_size; ++uint32_t ppu_hle_inject_base = 0x01000000u; ++int g_resv_store_active; ++uint32_t g_ww_lo, g_ww_hi; ++PPU_THREAD_LOCAL ppu_context* g_active_ctx; ++void ppu_resv_break_store(uint64_t ea) { (void)ea; } ++void ps3_ww_report_inline(uint32_t a, uint64_t v, int w) { (void)a; (void)v; (void)w; } ++int spu_coh_is_reserved(uint32_t a) { (void)a; return 0; } ++void spu_coh_notify_write(uint32_t a) { (void)a; } ++void spu_lockline_lock(void) {} ++void spu_lockline_unlock(void) {} ++ ++#define CHECK(c) do { if (!(c)) { printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); exit(1); } } while (0) ++ ++#define MEM_SIZE (64u << 20) ++#define G_TYPE 0x10000u ++#define G_CB 0x10010u ++#define G_HANDLE 0x10020u ++#define G_AUINFO 0x10040u ++#define G_ITEMPTR 0x100A0u ++#define G_AU 0x00100000u ++#define G_OUT 0x00200000u ++#define CB_OPD 0x00001000u ++#define AC3_FRAME 1792u ++ ++static u32 s_msgs[8192]; ++static int s_nmsg; ++static u32 s_handle; ++static void fake_guest_call(uint32_t opd, uint64_t a0, uint64_t a1, uint64_t a2, ++ uint64_t a3, uint64_t a4, uint64_t a5, uint64_t a6, uint64_t a7) ++{ ++ (void)a2; (void)a4; (void)a5; (void)a6; (void)a7; ++ CHECK(opd == CB_OPD && a3 == 0xC0FFEEu && a0 == s_handle); ++ /* AUDONE hands the AU back: a title's demuxer may refill it at once. */ ++ if ((u32)a1 == CELL_ADEC_MSG_TYPE_AUDONE) memset(vm_base + G_AU, 0xA5, 0x10000); ++ if (s_nmsg < 8192) s_msgs[s_nmsg++] = (u32)a1; ++} ++ps3_guest_caller_fn g_ps3_guest_caller = fake_guest_call; ++ ++static u8* read_file(const char* path, size_t* len) ++{ ++ FILE* f = fopen(path, "rb"); ++ if (!f) { printf("cannot open %s\n", path); exit(1); } ++ fseek(f, 0, SEEK_END); ++ long n = ftell(f); ++ fseek(f, 0, SEEK_SET); ++ u8* p = (u8*)malloc((size_t)n + 1); ++ CHECK(p && fread(p, 1, (size_t)n, f) == (size_t)n); ++ fclose(f); ++ *len = (size_t)n; ++ return p; ++} ++ ++static void open_adec(u32 codec) ++{ ++ vm_write32(G_TYPE, codec); ++ vm_write32(G_CB, CB_OPD); ++ vm_write32(G_CB + 4, 0xC0FFEEu); ++ CHECK(cellAdecOpen((const CellAdecType*)(uintptr_t)G_TYPE, NULL, ++ (const CellAdecCb*)(uintptr_t)G_CB, (CellAdecHandle*)(uintptr_t)G_HANDLE) == CELL_OK); ++ s_handle = vm_read32(G_HANDLE); ++ CHECK(cellAdecStartSeq(s_handle, NULL) == CELL_OK); ++} ++ ++/* One AU through the guest API: returns the PCM size the item announced and leaves the PCM at G_OUT. */ ++static u32 decode_one(const u8* au, u32 size) ++{ ++ memcpy(vm_base + G_AU, au, size); ++ vm_write32(G_AUINFO + 0, G_AU); ++ vm_write32(G_AUINFO + 4, size); ++ int before = s_nmsg; ++ CHECK(cellAdecDecodeAu(s_handle, (const CellAdecAuInfo*)(uintptr_t)G_AUINFO) == CELL_OK); ++ CHECK(s_nmsg == before + 2 && s_msgs[before] == CELL_ADEC_MSG_TYPE_AUDONE && ++ s_msgs[before + 1] == CELL_ADEC_MSG_TYPE_PCMOUT); ++ CHECK(cellAdecGetPcmItem(s_handle, (const CellAdecPcmItem**)(uintptr_t)G_ITEMPTR) == CELL_OK); ++ u32 item = vm_read32(G_ITEMPTR); ++ u32 bytes = vm_read32(item + PCMITEM_SIZE); ++ u32 bsi = vm_read32(item + PCMITEM_BSI_INFO); ++ CHECK(bsi && vm_read32(bsi + 0x14) == bytes); ++ CHECK(vm_read32(item + PCMITEM_AU_START) == G_AU && vm_read32(item + PCMITEM_AU_SIZE) == size); ++ memset(vm_base + G_OUT, 0x5A, bytes + 64); ++ CHECK(cellAdecGetPcm(s_handle, (void*)(uintptr_t)G_OUT) == CELL_OK); ++ CHECK(vm_base[G_OUT + bytes] == 0x5A); /* exactly `bytes` written */ ++ return bytes; ++} ++ ++static int all_zero(u32 ea, u32 n) ++{ ++ for (u32 i = 0; i < n; i++) if (vm_base[ea + i]) return 0; ++ return 1; ++} ++ ++static int mode_stub(int argc, char** argv) ++{ ++ CHECK(argc >= 4); ++ size_t n6, n2; ++ u8* a6 = read_file(argv[2], &n6); ++ u8* a2 = read_file(argv[3], &n2); ++ CHECK(n6 >= AC3_FRAME && n2 >= AC3_FRAME && a6[0] == 0x0B && a6[1] == 0x77); ++ CHECK(adec_ac3_channels(a6, AC3_FRAME) == 6 && adec_ac3_channels(a2, AC3_FRAME) == 2); ++ open_adec(CELL_ADEC_TYPE_AC3); ++ CHECK(s_adec[s_handle].ff == NULL); ++ for (int i = 0; i < 3; i++) { ++ u32 b = decode_one(a6 + (size_t)i * AC3_FRAME, AC3_FRAME); ++ CHECK(b == 1536u * 6u * 4u && all_zero(G_OUT, b)); ++ } ++ u32 b = decode_one(a2, AC3_FRAME); ++ CHECK(b == 1536u * 2u * 4u && all_zero(G_OUT, b)); ++ CHECK(cellAdecClose(s_handle) == CELL_OK); ++ open_adec(5); ++ b = decode_one(a6, AC3_FRAME); ++ CHECK(b == 1024u * 2u * 4u && all_zero(G_OUT, b)); ++ CHECK(cellAdecClose(s_handle) == CELL_OK); ++ printf("OK stub: AC3 5.1 36864, 2.0 12288, codecType 5 8192 bytes of silence per AU\n"); ++ return 0; ++} ++ ++#ifdef PS3RECOMP_FFMPEG_RUNTIME ++/* Decode the whole stream; compare against REF. swap: exchange channels 0 and 1 of the guest PCM; drop: skip AU 3. */ ++static int run_decode(const u8* ac3, size_t n, const float* ref, size_t nref, int swap, int drop) ++{ ++ open_adec(CELL_ADEC_TYPE_AC3); ++ CHECK(s_adec[s_handle].ff != NULL); ++ size_t at = 0; ++ int bad = 0; ++ for (size_t off = 0, k = 0; off + AC3_FRAME <= n; off += AC3_FRAME, k++) { ++ if (drop && k == 3) continue; ++ u32 b = decode_one(ac3 + off, AC3_FRAME); ++ if (b != 1536u * 6u * 4u) { printf("AU %zu: %u bytes\n", k, b); bad = 1; break; } ++ for (u32 i = 0; i < b / 4u; i++) { ++ u32 idx = i; ++ if (swap && (i % 6u) < 2u) idx = i ^ 1u; ++ u32 w = vm_read32(G_OUT + idx * 4u); ++ float v; ++ memcpy(&v, &w, 4); ++ if (at + i >= nref || v != ref[at + i]) { ++ if (!bad) printf("sample %zu (AU %zu): %g vs %g\n", at + i, k, v, at + i < nref ? ref[at + i] : -1.f); ++ bad = 1; ++ break; ++ } ++ } ++ if (bad) break; ++ at += b / 4u; ++ } ++ if (!bad && at != nref) { printf("%zu samples, reference has %zu\n", at, nref); bad = 1; } ++ CHECK(cellAdecClose(s_handle) == CELL_OK); ++ return bad; ++} ++ ++static int mode_decode(int argc, char** argv) ++{ ++ CHECK(argc >= 4); ++ if (!ps3_ffmpeg_get()) { printf("SKIP: libavcodec not loadable\n"); return 77; } ++ size_t n, nr; ++ u8* ac3 = read_file(argv[2], &n); ++ u8* refb = read_file(argv[3], &nr); ++ CHECK(n % AC3_FRAME == 0 && n / AC3_FRAME >= 8 && nr % 4 == 0); ++ const float* ref = (const float*)refb; ++ CHECK(run_decode(ac3, n, ref, nr / 4, 0, 0) == 0); ++ /* Nonzero audio came through, not silence. */ ++ double e = 0; ++ for (size_t i = 0; i < nr / 4; i++) e += fabs(ref[i]); ++ CHECK(e > 1.0); ++ printf("OK decode: %zu AUs, %zu samples equal FFmpeg's own decode\n", n / AC3_FRAME, nr / 4); ++ CHECK(run_decode(ac3, n, ref, nr / 4, 1, 0) != 0); ++ CHECK(run_decode(ac3, n, ref, nr / 4, 0, 1) != 0); ++ printf("OK negative controls: swapped channels and a dropped AU are caught\n"); ++ return 0; ++} ++#endif ++ ++int main(int argc, char** argv) ++{ ++ setvbuf(stdout, NULL, _IONBF, 0); ++ vm_base = (uint8_t*)calloc(1, MEM_SIZE); ++ CHECK(vm_base); ++ ppu_vm_size = MEM_SIZE; ++ const char* mode = argc > 1 ? argv[1] : "stub"; ++ if (strcmp(mode, "stub") == 0) return mode_stub(argc, argv); ++#ifdef PS3RECOMP_FFMPEG_RUNTIME ++ if (strcmp(mode, "decode") == 0) return mode_decode(argc, argv); ++#endif ++ printf("unknown mode %s\n", mode); ++ return 2; ++} diff --git a/tasks/sp00nznet__ps3recomp-671/solution/solve.sh b/tasks/sp00nznet__ps3recomp-671/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-671/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-671/task.toml b/tasks/sp00nznet__ps3recomp-671/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e12709c27d17cf11b8471e828bf7044cafdeee05 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-671/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-671" +description = "cellAdec: decode AC3 through the run-time FFmpeg loader" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/671" +source_access = "auto" +built_at = "2026-11-16T16:09:59.732017+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:949ebb3c1a0c033157c50732ccd2e33ae2491d7012ed64d5125ab644ab06b1f9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/codec/cellAdec.c", + "libs/codec/tests/CMakeLists.txt", + "libs/codec/tests/adec_tests.cmake", + "libs/codec/tests/gen_adec_media.cmake", + "libs/codec/tests/test_adec_ac3.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 577 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.149801+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-671/tests/capture.py b/tasks/sp00nznet__ps3recomp-671/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-671/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-671/tests/instruction.md b/tasks/sp00nznet__ps3recomp-671/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2b08ac9d1eef733c8865b0729fff06d7aff47482 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-671/tests/instruction.md @@ -0,0 +1,54 @@ +# Issue + +**Title:** cellAdec: decode AC3 through the run-time FFmpeg loader + +## Description + +### Why + +cellAdec returned silence for every codec: 1024 stereo samples (8192 bytes) per access unit. A downstream title sizes its PCM ring from bsiInfo+0x14 as channels x 4 bytes a sample. It then took 341 sample frames per AC3 frame instead of 1536, so an AC3 5.1 movie track lost most of its audio (and what was left was silence). + +### Change + +Size: +544/-33. The code is `cellAdec.c` (+253/-33). The rest is tests: `test_adec_ac3.c` (211 lines), `adec_tests.cmake` (52), `gen_adec_media.cmake` (26), and 2 lines in `libs/codec/tests/CMakeLists.txt`. + +- AC3 (codecType 2) decodes through `ps3_ffmpeg_get()`, the loader cellVdec already uses. No new FFmpeg symbols, nothing linked at build time. +- Output is interleaved big-endian float in the decoder's channel order, one 1536-sample frame per AU, with its size in the PcmItem and bsiInfo+0x14. +- StartSeq flushes the decoder and Close frees it. The AU bytes and info are copied before AUDONE, which hands the AU buffer back. +- Without a decoder (no FFmpeg build, `PS3RECOMP_FFMPEG=0`, or a damaged AU), AC3 gives silence of the real size: 1536 samples in the channel count that acmod + lfeon give (A/52 5.4.2), or 2 channels if the header is not AC3. +- Other codecs keep 1024 x 2. +- The PCM block (up to 48 KB) moves out of the 16 KB per-handle scratch into its own 64 KB per handle at VM_HLE_INJECT_BASE + 0x80000. +- FFmpeg is only called (LGPL, separate libraries), as cellVdec already does. + +### Tests + +They mirror the cellVdec ones: + +- `libs/codec/tests/test_adec_ac3.c` includes `../cellAdec.c` with the same runtime stand-ins as `test_vdec_decode.c`. +- `gen_adec_media.cmake` uses the ffmpeg program at test time to make 5.1 and 2.0 AC3 at 448 kb/s, plus FFmpeg's own f32 decode of the 5.1 file as the reference. +- `adec_tests.cmake` is included from `libs/codec/tests/CMakeLists.txt`. `.gitignore` ignores `*.cmake`, so the two new .cmake files were added with `git add -f`, as `gen_vdec_media.cmake` was. + +ctest: `adec_media_gen`; `adec_ac3_stub` (no FFmpeg: 36864 / 12288 / 8192 byte silences); `adec_ac3_disabled` (`PS3RECOMP_FFMPEG=0`); `adec_ac3_decode` (13 AUs, 119808 samples equal to FFmpeg's decode; swapped channels and a dropped AU are caught; exit 77 = skipped when libavcodec cannot load). + +How I ran them, all with FFmpeg 9.0.1 headers and libavcodec 63.1 on Linux: + +- **Whole tree with `-DPS3RECOMP_FFMPEG_RUNTIME=ON -DPS3RECOMP_BUILD_TESTS=ON`** (Release; gcc 16.2 and clang 19.1): configures and builds on master and on this branch. + - `ctest -R 'adec|vdec'` on this branch: the 4 adec tests pass with both compilers. + - 4 cellVdec tests (`vdec_idle_avc`, `vdec_idle_off_avc`, `vdec_idle_mpeg2`, `vdec_idle_off_mpeg2`) fail on master and on this branch alike, with both compilers. They are unrelated to this change, but worth knowing before reading CI. + - On master the new test does not compile (no `adec_ac3_channels`, no `ff` in `AdecSlot`). +- **What master does with the same input.** The new test cannot build against master, so I compiled a small probe against master's `cellAdec.c` and against this branch's (both without FFmpeg, gcc and clang). The probe drives the same guest-API path as `test_adec_ac3.c`: the same runtime stand-ins, `cellAdecOpen` for AC3, `cellAdecDecodeAu`, `cellAdecGetPcmItem`, `cellAdecGetPcm`. It feeds the first 3 AUs of the 5.1 and the 2.0 test streams, made at test time by `gen_adec_media.cmake` with the local ffmpeg. + - Master: every AU gives a PcmItem size and bsiInfo+0x14 of **8192** bytes of silence, for 5.1 and 2.0 alike. + - This branch without a decoder: **36864** for 5.1 and **12288** for 2.0 (also silence). + - With FFmpeg, the PCM is the real decode (`adec_ac3_decode` above). + The probe is not part of the PR. +- linux.yml, all 40 steps, run locally (not on GitHub) on master and on this branch, each with gcc 16.2 and with clang 19.1 (CMAKE_BUILD_TYPE=Release). The 39 steps after "Install dependencies" all pass, on both trees and with both compilers. That includes Configure, Build, the archive check, the lifter suites, the pad tests, guest shader translation, the boot smoke title, the game template, the POSIX host, sync_stress, fiber_switch. "Install dependencies" (apt) was replaced by the same packages from nixpkgs: SDL2 is sdl2-compat 2.32.72 (the SDL2 API on SDL3), plus glslang 16.4, spirv-tools and spirv-cross 1.4.357. Not run: the Debug half of the build-type matrix, macos.yml, windows.yml (no macOS or Windows host here). + +Not run: the Windows and macOS jobs, MSVC, or a real title on this project's own backend. + +Overlap with open PRs: I took the current diff of each of the 90 open PRs for the files this branch touches and ran `git apply --check` against master and against this branch, whole and hunk by hunk. +- Only #213 touches them (`cellAdec.c`). It does not apply to master itself: none of its 3 hunks there applies to master, so it needs a rebase whichever lands first. +- No other open PR touches `cellAdec.c` or `libs/codec/tests/`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-671/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-671/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..17d4e9c1b81951418acdca30b6a6dc7cfb8929fb --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-671/tests/oracle.patch @@ -0,0 +1,712 @@ +diff --git a/libs/codec/cellAdec.c b/libs/codec/cellAdec.c +index 9bacce2d..c32d7676 100644 +--- a/libs/codec/cellAdec.c ++++ b/libs/codec/cellAdec.c +@@ -1,9 +1,12 @@ + /* + * ps3recomp - cellAdec HLE implementation + * +- * Stub audio decoder. Accepts AU data and delivers AUDONE callbacks. +- * Actual decoding (AAC, ATRAC3+, etc.) requires integration with +- * an audio codec library (e.g., FFmpeg). ++ * Audio decoder. Accepts AU data and delivers AUDONE + PCMOUT callbacks. ++ * AC3 decodes through FFmpeg loaded at run time (PS3RECOMP_FFMPEG_RUNTIME, ++ * ffmpeg_runtime.c, the loader cellVdec uses) into interleaved big-endian ++ * float PCM, one 1536-sample frame per AU in the stream's own channels. ++ * Every other codec, and AC3 when FFmpeg is absent or PS3RECOMP_FFMPEG=0, ++ * delivers silence of the codec's frame size. + */ + + #include "cellAdec.h" +@@ -16,6 +19,7 @@ + #include "ps3emu/guest_call.h" /* g_ps3_guest_caller -- cbFunc is a GUEST OPD */ + #include "../../runtime/memory/vm.h" /* VM_HLE_INJECT_BASE */ + #include "ps3emu/log_first.h" ++#include "ffmpeg_runtime.h" /* PS3FFmpeg; empty without PS3RECOMP_FFMPEG_RUNTIME */ + + /* CellAdecPcmItem as the guest reads it, from RPCS3 Modules/cellAdec.h:339. + * ps1_netemu copies the whole thing out with six 8-byte loads from offsets +@@ -34,12 +38,20 @@ + #define PCMITEM_AU_USERDATA 0x28u + #define PCMITEM_BYTES 0x30u + +-/* ponytail: one fixed-size silence buffer per handle, 1024 stereo float samples +- * -- the ATRAC3 frame this title (codecType 5) decodes. The ceiling is that it +- * is SILENCE and always this size; wire a real decoder in here when the audio +- * itself matters, without changing the guest-visible contract. */ ++/* PCM per AU, float (4 bytes a sample), interleaved. ++ * - AC3: one A/52 frame is 1536 samples (6 blocks of 256) in the frame's own ++ * channels (acmod + LFE from its header: 6 for a 5.1 track). A movie ++ * player that sizes its ring as channels x 4 bytes a sample and takes each ++ * AU's PCM size from bsiInfo+0x14 needs the block to be the real frame: ++ * 1024 stereo samples (8 KB) fed its 5.1 mixer a third of the audio an AU ++ * stands for. ++ * - the other codecs: 1024 stereo float samples of silence, the ATRAC3 frame ++ * the first title on this stub (codecType 5) decodes. */ + #define ADEC_PCM_SAMPLES 1024u + #define ADEC_PCM_BYTES (ADEC_PCM_SAMPLES * 2u * 4u) ++#define ADEC_AC3_SAMPLES 1536u ++/* The largest block one AU produces here: an AC3 frame in 7.1. */ ++#define ADEC_PCM_MAX_BYTES (ADEC_AC3_SAMPLES * 8u * 4u) + + /* Guest-visible scratch, in the HLE inject window rather than from the guest's + * own heap. Taking 8 KB out of that heap in cellAdecOpen stalled the title +@@ -53,7 +65,10 @@ + #define ADEC_SCRATCH_BASE (VM_HLE_INJECT_BASE + 0x40000u) + #define ADEC_SCRATCH_STRIDE 0x4000u + #define ADEC_ITEM_EA(h) (ADEC_SCRATCH_BASE + (u32)(h) * ADEC_SCRATCH_STRIDE) +-#define ADEC_PCM_EA(h) (ADEC_ITEM_EA(h) + 0x100u) ++/* The PCM block is up to 48 KB (ADEC_PCM_MAX_BYTES), more than the 16 KB ++ * stride holds, so it lives in its own 64 KB per handle at +0x80000..+0xC0000, ++ * past cellVdec's pic items at +0x50000. */ ++#define ADEC_PCM_EA(h) (VM_HLE_INJECT_BASE + 0x80000u + (u32)(h) * 0x10000u) + /* The codec info block the PcmItem's bsiInfo points to, in the gap between + * the 0x30-byte item and the PCM buffer. */ + #define ADEC_BSI_EA(h) (ADEC_ITEM_EA(h) + 0x40u) +@@ -73,11 +88,176 @@ typedef struct { + u32 itemEa; /* guest EA of the 0x30-byte CellAdecPcmItem */ + u32 pcmEa; /* guest EA of the PCM buffer it points at */ + int hasPcm; ++ u32 pcmBytes; /* size of the PCM block at pcmEa */ + u32 auCount; /* total AUs decoded */ ++ void* ff; /* AdecFf: the libavcodec decoder, or NULL */ ++ u8* au; /* host copy of the AU being decoded */ ++ u32 auCap; + } AdecSlot; + + static AdecSlot s_adec[MAX_ADEC]; + ++/* --------------------------------------------------------------------------- ++ * AC3 frame header: the frame's channel count (A/52 5.4.2), for the size of ++ * the silent block when there is no decoder. 0 when it is not an AC3 frame. ++ * -----------------------------------------------------------------------*/ ++static u32 adec_ac3_channels(const u8* f, u32 n) ++{ ++ static const u8 nfchans[8] = { 2, 1, 2, 3, 3, 4, 4, 5 }; ++ if (!f || n < 8 || f[0] != 0x0B || f[1] != 0x77) return 0; ++ if ((f[5] >> 3) > 10) return 0; /* bsid > 10: E-AC3, not parsed */ ++ u32 bits = ((u32)f[6] << 8) | f[7]; /* acmod(3) [cmixlev surmixlev dsurmod] lfeon */ ++ u32 acmod = bits >> 13; ++ int pos = 3; ++ if ((acmod & 1u) && acmod != 1u) pos += 2; /* cmixlev */ ++ if (acmod & 4u) pos += 2; /* surmixlev */ ++ if (acmod == 2u) pos += 2; /* dsurmod */ ++ return nfchans[acmod] + ((bits >> (15 - pos)) & 1u); ++} ++ ++/* --------------------------------------------------------------------------- ++ * libavcodec back end (AC3) ++ * -----------------------------------------------------------------------*/ ++#ifdef PS3RECOMP_FFMPEG_RUNTIME ++ ++typedef struct AdecFf { ++ const PS3FFmpeg* ff; ++ AVCodecContext* ctx; ++ AVPacket* pkt; ++ AVFrame* frame; ++ u8* buf; /* the AU plus FFmpeg's zeroed input padding */ ++ u32 bufCap; ++ u32* pcm; /* big-endian float words, ADEC_PCM_MAX_BYTES */ ++} AdecFf; ++ ++static void adec_ff_close(void* p) ++{ ++ AdecFf* d = (AdecFf*)p; ++ if (!d) return; ++ if (d->ctx) d->ff->avcodec_free_context(&d->ctx); ++ if (d->pkt) d->ff->av_packet_free(&d->pkt); ++ if (d->frame) d->ff->av_frame_free(&d->frame); ++ free(d->buf); ++ free(d->pcm); ++ free(d); ++} ++ ++static void* adec_ff_open(u32 codec_type) ++{ ++ if (codec_type != CELL_ADEC_TYPE_AC3) return NULL; ++ const PS3FFmpeg* ff = ps3_ffmpeg_get(); ++ if (!ff) return NULL; ++ const AVCodec* codec = ff->avcodec_find_decoder(AV_CODEC_ID_AC3); ++ if (!codec) { ++ printf("[cellAdec] libavcodec has no AC3 decoder; silence\n"); ++ return NULL; ++ } ++ AdecFf* d = (AdecFf*)calloc(1, sizeof(*d)); ++ if (!d) return NULL; ++ d->ff = ff; ++ d->ctx = ff->avcodec_alloc_context3(codec); ++ d->pkt = ff->av_packet_alloc(); ++ d->frame = ff->av_frame_alloc(); ++ d->pcm = (u32*)malloc(ADEC_PCM_MAX_BYTES); ++ if (!d->ctx || !d->pkt || !d->frame || !d->pcm || ++ ff->avcodec_open2(d->ctx, codec, NULL) < 0) { ++ printf("[cellAdec] could not open the libavcodec AC3 decoder; silence\n"); ++ adec_ff_close(d); ++ return NULL; ++ } ++ return d; ++} ++ ++static void adec_ff_flush(void* p) ++{ ++ AdecFf* d = (AdecFf*)p; ++ if (d) d->ff->avcodec_flush_buffers(d->ctx); ++} ++ ++static float adec_ff_sample(const AVFrame* f, int ch, int c, int s) ++{ ++ const u8* const* x = (const u8* const*)f->extended_data; ++ switch (f->format) { ++ case AV_SAMPLE_FMT_FLTP: return ((const float*)x[c])[s]; ++ case AV_SAMPLE_FMT_FLT: return ((const float*)x[0])[s * ch + c]; ++ case AV_SAMPLE_FMT_S16P: return ((const int16_t*)x[c])[s] * (1.0f / 32768.0f); ++ case AV_SAMPLE_FMT_S16: return ((const int16_t*)x[0])[s * ch + c] * (1.0f / 32768.0f); ++ case AV_SAMPLE_FMT_S32P: return (float)((const int32_t*)x[c])[s] * (1.0f / 2147483648.0f); ++ case AV_SAMPLE_FMT_S32: return (float)((const int32_t*)x[0])[s * ch + c] * (1.0f / 2147483648.0f); ++ default: return 0.0f; ++ } ++} ++ ++/* Decode one AU and store its PCM at guest dst as interleaved big-endian ++ * float, frame after frame. Returns the bytes stored (0: nothing came out); ++ * *channels gets the last frame's channel count. */ ++static u32 adec_ff_decode(void* p, const u8* au, u32 size, u32 dst, u32* channels) ++{ ++ AdecFf* d = (AdecFf*)p; ++ const PS3FFmpeg* ff = d->ff; ++ if (size + AV_INPUT_BUFFER_PADDING_SIZE > d->bufCap) { ++ u8* nb = (u8*)realloc(d->buf, size + AV_INPUT_BUFFER_PADDING_SIZE); ++ if (!nb) return 0; ++ d->buf = nb; ++ d->bufCap = size + AV_INPUT_BUFFER_PADDING_SIZE; ++ } ++ memcpy(d->buf, au, size); ++ memset(d->buf + size, 0, AV_INPUT_BUFFER_PADDING_SIZE); ++ d->pkt->data = d->buf; ++ d->pkt->size = (int)size; ++ int r = ff->avcodec_send_packet(d->ctx, d->pkt); ++ d->pkt->data = NULL; ++ d->pkt->size = 0; ++ u32 out = 0; ++ if (r < 0) { ++ static int _n = 0; ++ if (PS3_LOG_FIRST(_n, 8)) ++ printf("[cellAdec] AC3 AU of %u bytes did not decode (%d)\n", size, r); ++ } ++ for (;;) { ++ AVFrame* f = d->frame; ++ if (ff->avcodec_receive_frame(d->ctx, f) < 0) ++ break; /* EAGAIN / EOF / error */ ++ int ch = f->ch_layout.nb_channels, ns = f->nb_samples; ++ u32 bytes = (u32)ns * (u32)ch * 4u; ++ if (ch < 1 || ch > 8 || ns <= 0 || out + bytes > ADEC_PCM_MAX_BYTES) { ++ static int _n = 0; ++ if (PS3_LOG_FIRST(_n, 4)) ++ printf("[cellAdec] dropping a decoded frame (%d samples x %d ch, %u bytes held)\n", ++ ns, ch, out); ++ ff->av_frame_unref(f); ++ continue; ++ } ++ u32 i = 0; ++ for (int s = 0; s < ns; s++) ++ for (int c = 0; c < ch; c++) { ++ float v = adec_ff_sample(f, ch, c, s); ++ u32 w; ++ memcpy(&w, &v, 4); ++ d->pcm[i++] = (w >> 24) | ((w >> 8) & 0xFF00u) | ((w << 8) & 0xFF0000u) | (w << 24); ++ } ++ vm_memcpy_to(dst + out, d->pcm, bytes); ++ { static int _n = 0; ++ if (PS3_LOG_FIRST(_n, 1)) ++ printf("[cellAdec] AC3 through libavcodec: %d samples x %d ch at %d Hz, %u bytes an AU\n", ++ ns, ch, f->sample_rate, bytes); } ++ out += bytes; ++ *channels = (u32)ch; ++ ff->av_frame_unref(f); ++ } ++ return out; ++} ++ ++#else /* !PS3RECOMP_FFMPEG_RUNTIME */ ++ ++static void* adec_ff_open(u32 codec_type) { (void)codec_type; return NULL; } ++static void adec_ff_close(void* p) { (void)p; } ++static void adec_ff_flush(void* p) { (void)p; } ++static u32 adec_ff_decode(void* p, const u8* au, u32 size, u32 dst, u32* channels) ++{ (void)p; (void)au; (void)size; (void)dst; (void)channels; return 0; } ++ ++#endif /* PS3RECOMP_FFMPEG_RUNTIME */ ++ + /* Fire one guest callback. + * + * The guest's cbFunc is a guest EA naming an OPD, so it goes through the +@@ -164,9 +344,11 @@ s32 cellAdecOpen(const CellAdecType* type, const CellAdecResource* res, + * once already. */ + s_adec[i].itemEa = ADEC_ITEM_EA(i); + s_adec[i].pcmEa = ADEC_PCM_EA(i); ++ s_adec[i].ff = adec_ff_open(codec_type); + vm_write32(handle_ea, (u32)i); +- printf("[cellAdec] Open -> handle=%u item=0x%08X pcm=0x%08X\n", +- i, s_adec[i].itemEa, s_adec[i].pcmEa); ++ printf("[cellAdec] Open -> handle=%u item=0x%08X pcm=0x%08X%s\n", ++ i, s_adec[i].itemEa, s_adec[i].pcmEa, ++ s_adec[i].ff ? " (decoding with libavcodec)" : ""); + return CELL_OK; + } + } +@@ -180,6 +362,11 @@ s32 cellAdecClose(CellAdecHandle handle) + if (handle >= MAX_ADEC || !s_adec[handle].in_use) + return (s32)CELL_ADEC_ERROR_ARG; + ++ adec_ff_close(s_adec[handle].ff); ++ free(s_adec[handle].au); ++ s_adec[handle].ff = NULL; ++ s_adec[handle].au = NULL; ++ s_adec[handle].auCap = 0; + s_adec[handle].in_use = 0; + return CELL_OK; + } +@@ -193,6 +380,7 @@ s32 cellAdecStartSeq(CellAdecHandle handle, void* param) + return (s32)CELL_ADEC_ERROR_ARG; + + s_adec[handle].seqStarted = 1; ++ adec_ff_flush(s_adec[handle].ff); /* a new sequence starts clean */ + return CELL_OK; + } + +@@ -233,49 +421,78 @@ s32 cellAdecDecodeAu(CellAdecHandle handle, const CellAdecAuInfo* auInfo) + return (s32)CELL_ADEC_ERROR_ARG; + + AdecSlot* a = &s_adec[handle]; ++ const u32 au = GUEST_EA(auInfo); ++ const u32 au_addr = vm_read32(au + (u32)offsetof(CellAdecAuInfo, startAddr)); ++ const u32 au_size = vm_read32(au + (u32)offsetof(CellAdecAuInfo, size)); ++ /* The AU info, read before AUDONE gives it back to the title. */ ++ const u32 au_w[4] = { vm_read32(au + 0x08), vm_read32(au + 0x0C), ++ vm_read32(au + 0x10), vm_read32(au + 0x14) }; + + printf("[cellAdec] DecodeAu(handle=%u, addr=0x%X, size=%u)\n", +- handle, vm_read32(GUEST_EA(auInfo) + (u32)offsetof(CellAdecAuInfo, startAddr)), +- vm_read32(GUEST_EA(auInfo) + (u32)offsetof(CellAdecAuInfo, size))); ++ handle, au_addr, au_size); ++ ++ /* The AC3 bytes are copied out first, too: AUDONE hands their buffer back ++ * to the title's demuxer, which may refill it at once. */ ++ const u8* data = NULL; ++ if (a->codecType == CELL_ADEC_TYPE_AC3 && au_addr && au_size && au_size <= 0x10000u) { ++ if (au_size > a->auCap) { ++ u8* nb = (u8*)realloc(a->au, au_size); ++ if (nb) { a->au = nb; a->auCap = au_size; } ++ } ++ if (au_size <= a->auCap) { ++ vm_memcpy_from(a->au, au_addr, au_size); ++ data = a->au; ++ } ++ } + + /* Step 1: report the AU consumed. msgData is the AU INFO ADDRESS, not a + * status -- see RPCS3 Modules/cellAdec.cpp:1345. A decoder that tracks its + * outstanding AUs by address gets a null back if this is CELL_OK. */ +- adec_notify(handle, CELL_ADEC_MSG_TYPE_AUDONE, (s32)GUEST_EA(auInfo)); ++ adec_notify(handle, CELL_ADEC_MSG_TYPE_AUDONE, (s32)au); + +- /* Step 2: Generate PCMOUT callback with dummy PCM info. +- * Without FFmpeg, we produce silence. But games that check for +- * decode completion via callbacks will proceed correctly. */ ++ /* Step 2: the PCM. AC3 through libavcodec when it is there; otherwise ++ * silence of the codec's frame size (AC3: 1536 samples in the frame's ++ * channels), so a title that counts PCM against time still runs. */ + a->auCount++; + { +- const u32 au = GUEST_EA(auInfo); + const u32 it = a->itemEa; +- for (u32 o = 0; o < ADEC_PCM_BYTES; o += 4) vm_write32(a->pcmEa + o, 0); ++ u32 ch = 0; ++ u32 bytes = (a->ff && data) ? adec_ff_decode(a->ff, data, au_size, a->pcmEa, &ch) : 0; ++ if (bytes == 0) { ++ if (a->codecType == CELL_ADEC_TYPE_AC3) { ++ ch = adec_ac3_channels(data, data ? au_size : 0); ++ bytes = ADEC_AC3_SAMPLES * (ch ? ch : 2u) * 4u; ++ } else { ++ bytes = ADEC_PCM_BYTES; ++ } ++ vm_memset(a->pcmEa, 0, bytes); ++ } ++ a->pcmBytes = bytes; + + vm_write32(it + PCMITEM_PCM_HANDLE, (u32)handle); + vm_write32(it + PCMITEM_STATUS, 0); /* CELL_OK */ + vm_write32(it + PCMITEM_START_ADDR, a->pcmEa); +- vm_write32(it + PCMITEM_SIZE, ADEC_PCM_BYTES); ++ vm_write32(it + PCMITEM_SIZE, bytes); + /* bsiInfo must point at a codec info block, not be null. Resistance: + * Fall of Man sizes each AC3 block from bsiInfo+0x14; with a null + * pointer that read address 0x14 and came back 0, so its ring buffer + * never filled, it never started its audio port, and its movie player +- * waited forever. ponytail: only that output-size word is filled; the +- * rest of the block is zero until a title reads another field. */ ++ * waited forever. Other titles' PCMOUT handlers take the AU's ++ * PCM size from the same word. ponytail: only that output-size word is ++ * filled; the rest of the block is zero until a title reads another ++ * field. */ + const u32 bsi = ADEC_BSI_EA(handle); + for (u32 o = 0; o < ADEC_BSI_BYTES; o += 4) vm_write32(bsi + o, 0); +- vm_write32(bsi + 0x14, ADEC_PCM_BYTES); ++ vm_write32(bsi + 0x14, bytes); + vm_write32(it + PCMITEM_BSI_INFO, bsi); + /* Echo the AU back, which is what a real decoder does -- the guest + * matches returned PCM against the AU it submitted. */ +- vm_write32(it + PCMITEM_AU_START, +- vm_read32(au + (u32)offsetof(CellAdecAuInfo, startAddr))); +- vm_write32(it + PCMITEM_AU_SIZE, +- vm_read32(au + (u32)offsetof(CellAdecAuInfo, size))); +- vm_write32(it + PCMITEM_AU_PTS_HI, vm_read32(au + 0x08)); +- vm_write32(it + PCMITEM_AU_PTS_LO, vm_read32(au + 0x0C)); +- vm_write32(it + PCMITEM_AU_USERDATA, vm_read32(au + 0x10)); +- vm_write32(it + PCMITEM_AU_USERDATA + 4, vm_read32(au + 0x14)); ++ vm_write32(it + PCMITEM_AU_START, au_addr); ++ vm_write32(it + PCMITEM_AU_SIZE, au_size); ++ vm_write32(it + PCMITEM_AU_PTS_HI, au_w[0]); ++ vm_write32(it + PCMITEM_AU_PTS_LO, au_w[1]); ++ vm_write32(it + PCMITEM_AU_USERDATA, au_w[2]); ++ vm_write32(it + PCMITEM_AU_USERDATA + 4, au_w[3]); + } + a->hasPcm = 1; + +@@ -295,10 +512,13 @@ s32 cellAdecGetPcm(CellAdecHandle handle, void* outBuffer) + if (!s_adec[handle].hasPcm) + return (s32)CELL_ADEC_ERROR_EMPTY; + +- /* outBuffer is the GUEST's buffer. Leaving it untouched hands the title +- * whatever happened to be there, which it then plays. */ ++ /* outBuffer is the GUEST's buffer: the AU's PCM block goes there, the ++ * size the item and bsiInfo+0x14 announced. Leaving it untouched hands the ++ * title whatever happened to be there, which it then plays. */ + { const u32 out = GUEST_EA(outBuffer); +- if (out) for (u32 o = 0; o < ADEC_PCM_BYTES; o += 4) vm_write32(out + o, 0); } ++ const AdecSlot* a = &s_adec[handle]; ++ if (out && a->pcmBytes) ++ vm_memcpy_to(out, vm_ptr8(a->pcmEa), a->pcmBytes); } + + s_adec[handle].hasPcm = 0; + return CELL_OK; +diff --git a/libs/codec/tests/CMakeLists.txt b/libs/codec/tests/CMakeLists.txt +index f3f8670d..ec7a1499 100644 +--- a/libs/codec/tests/CMakeLists.txt ++++ b/libs/codec/tests/CMakeLists.txt +@@ -4,6 +4,8 @@ if(UNIX) + set(VDEC_TEST_LIBS m) + endif() + ++include("${CMAKE_CURRENT_SOURCE_DIR}/adec_tests.cmake") ++ + # The callback-only decoder, as every build without FFmpeg has it. + add_executable(test_vdec_stub test_vdec_decode.c) + target_include_directories(test_vdec_stub PRIVATE "${PROJECT_SOURCE_DIR}/include") +diff --git a/libs/codec/tests/adec_tests.cmake b/libs/codec/tests/adec_tests.cmake +new file mode 100644 +index 00000000..94a58c42 +--- /dev/null ++++ b/libs/codec/tests/adec_tests.cmake +@@ -0,0 +1,52 @@ ++# cellAdec AC3, driven through its guest API (test_adec_ac3.c). Included from ++# CMakeLists.txt. The streams are made by the ffmpeg program at test time. ++find_program(PS3RECOMP_FFMPEG_EXECUTABLE ffmpeg) ++if(NOT PS3RECOMP_FFMPEG_EXECUTABLE) ++ message(STATUS " FFmpeg: no ffmpeg program; cellAdec AC3 tests not added") ++ return() ++endif() ++ ++set(ADEC_MEDIA "${CMAKE_CURRENT_BINARY_DIR}/adec_media") ++add_test(NAME adec_media_gen COMMAND "${CMAKE_COMMAND}" ++ -DFFMPEG=${PS3RECOMP_FFMPEG_EXECUTABLE} -DOUT=${ADEC_MEDIA} ++ -P "${CMAKE_CURRENT_SOURCE_DIR}/gen_adec_media.cmake") ++set_tests_properties(adec_media_gen PROPERTIES FIXTURES_SETUP adec_media) ++ ++# Without FFmpeg: silence of the real AC3 frame size. ++add_executable(test_adec_stub test_adec_ac3.c) ++target_include_directories(test_adec_stub PRIVATE "${PROJECT_SOURCE_DIR}/include") ++target_link_libraries(test_adec_stub PRIVATE ${VDEC_TEST_LIBS}) ++add_test(NAME adec_ac3_stub COMMAND test_adec_stub stub ++ ${ADEC_MEDIA}/t51.ac3 ${ADEC_MEDIA}/t20.ac3) ++set_tests_properties(adec_ac3_stub PROPERTIES FIXTURES_REQUIRED adec_media) ++ ++if(NOT PS3RECOMP_FFMPEG_RUNTIME) ++ return() ++endif() ++ ++add_executable(test_adec_ffmpeg test_adec_ac3.c) ++target_include_directories(test_adec_ffmpeg PRIVATE ++ "${PROJECT_SOURCE_DIR}/include" "${PS3RECOMP_FFMPEG_INCLUDE_DIR}") ++target_compile_definitions(test_adec_ffmpeg PRIVATE PS3RECOMP_FFMPEG_RUNTIME) ++target_link_libraries(test_adec_ffmpeg PRIVATE ${VDEC_TEST_LIBS} ${CMAKE_DL_LIBS}) ++ ++# Where the system's libavcodec is, as for the cellVdec tests below. ++find_library(PS3RECOMP_AVCODEC_LIBRARY NAMES avcodec) ++set(ADEC_LIB_ENV "") ++if(PS3RECOMP_AVCODEC_LIBRARY AND UNIX) ++ get_filename_component(ADEC_LIB_DIR "${PS3RECOMP_AVCODEC_LIBRARY}" DIRECTORY) ++ if(APPLE) ++ set(ADEC_LIB_ENV "DYLD_LIBRARY_PATH=${ADEC_LIB_DIR}") ++ else() ++ set(ADEC_LIB_ENV "LD_LIBRARY_PATH=${ADEC_LIB_DIR}") ++ endif() ++endif() ++ ++add_test(NAME adec_ac3_disabled COMMAND test_adec_ffmpeg stub ++ ${ADEC_MEDIA}/t51.ac3 ${ADEC_MEDIA}/t20.ac3) ++set_tests_properties(adec_ac3_disabled PROPERTIES ++ ENVIRONMENT "PS3RECOMP_FFMPEG=0;${ADEC_LIB_ENV}" FIXTURES_REQUIRED adec_media) ++add_test(NAME adec_ac3_decode COMMAND test_adec_ffmpeg decode ++ ${ADEC_MEDIA}/t51.ac3 ${ADEC_MEDIA}/t51.f32) ++set_tests_properties(adec_ac3_decode PROPERTIES ++ ENVIRONMENT "${ADEC_LIB_ENV}" FIXTURES_REQUIRED adec_media SKIP_RETURN_CODE 77) +diff --git a/libs/codec/tests/gen_adec_media.cmake b/libs/codec/tests/gen_adec_media.cmake +new file mode 100644 +index 00000000..39956f77 +--- /dev/null ++++ b/libs/codec/tests/gen_adec_media.cmake +@@ -0,0 +1,26 @@ ++# Generates the AC3 streams test_adec_ac3 feeds through cellAdec, and FFmpeg's ++# own decode of the 5.1 one as the reference. Nothing here is committed: ++# everything is written to the build tree at test time. ++# ++# cmake -DFFMPEG=<ffmpeg> -DOUT=<dir> -P gen_adec_media.cmake ++# ++# 448 kb/s at 48 kHz makes every frame 1792 bytes. A different tone on each ++# channel, so a channel swap shows. ++if(NOT FFMPEG OR NOT OUT) ++ message(FATAL_ERROR "pass -DFFMPEG=<ffmpeg> -DOUT=<dir>") ++endif() ++file(MAKE_DIRECTORY "${OUT}") ++ ++function(run) ++ execute_process(COMMAND "${FFMPEG}" -nostdin -hide_banner -loglevel error -y ${ARGN} ++ RESULT_VARIABLE rc) ++ if(NOT rc EQUAL 0) ++ message(FATAL_ERROR "ffmpeg failed (${rc}): ${ARGN}") ++ endif() ++endfunction() ++ ++run(-f lavfi -i "aevalsrc=0.5*sin(2*PI*330*t)|0.4*sin(2*PI*440*t)|0.3*sin(2*PI*550*t)|0.2*sin(2*PI*60*t)|0.3*sin(2*PI*660*t)|0.25*sin(2*PI*770*t):s=48000:c=5.1:d=0.4" ++ -c:a ac3 -b:a 448k -f ac3 "${OUT}/t51.ac3") ++run(-f lavfi -i "aevalsrc=0.5*sin(2*PI*330*t)|0.4*sin(2*PI*440*t):s=48000:c=stereo:d=0.2" ++ -c:a ac3 -b:a 448k -f ac3 "${OUT}/t20.ac3") ++run(-i "${OUT}/t51.ac3" -f f32le "${OUT}/t51.f32") +diff --git a/libs/codec/tests/test_adec_ac3.c b/libs/codec/tests/test_adec_ac3.c +new file mode 100644 +index 00000000..c52be176 +--- /dev/null ++++ b/libs/codec/tests/test_adec_ac3.c +@@ -0,0 +1,211 @@ ++/* ++ * cellAdec AC3, driven through its guest API. ++ * ++ * Built twice by CMakeLists.txt (adec_tests.cmake): ++ * without PS3RECOMP_FFMPEG_RUNTIME mode "stub" ++ * with it modes "stub" (PS3RECOMP_FFMPEG=0) and "decode" ++ * Modes: ++ * stub AC3 AC3_2CH AC3 5.1 frames give 1536 x 6 float of silence (36864 bytes in the PcmItem size, in ++ * bsiInfo+0x14 and through cellAdecGetPcm), 2.0 frames 1536 x 2 (12288), codecType 5 ++ * the old 1024 x 2 (8192); AUDONE then PCMOUT for every AU. ++ * decode AC3 REF every AU of a 5.1 AC3 stream through cellAdecDecodeAu; the PCM handed to the guest ++ * (big-endian float, interleaved) must equal FFmpeg's own decode REF (f32le) sample ++ * for sample. Negative controls: two channels swapped and one AU dropped must both ++ * be caught. ++ * The AC3 files are CBR 448 kb/s at 48 kHz, so every frame (= AU) is 1792 bytes (gen_adec_media.cmake). ++ */ ++#include "../cellAdec.c" ++#ifdef PS3RECOMP_FFMPEG_RUNTIME ++#include "../ffmpeg_runtime.c" ++#endif ++ ++#include <math.h> ++#include <stdlib.h> ++ ++/* What the runtime would provide (the same stand-ins test_vdec_decode.c uses). */ ++uint8_t* vm_base; ++uint32_t ppu_vm_size; ++uint32_t ppu_hle_inject_base = 0x01000000u; ++int g_resv_store_active; ++uint32_t g_ww_lo, g_ww_hi; ++PPU_THREAD_LOCAL ppu_context* g_active_ctx; ++void ppu_resv_break_store(uint64_t ea) { (void)ea; } ++void ps3_ww_report_inline(uint32_t a, uint64_t v, int w) { (void)a; (void)v; (void)w; } ++int spu_coh_is_reserved(uint32_t a) { (void)a; return 0; } ++void spu_coh_notify_write(uint32_t a) { (void)a; } ++void spu_lockline_lock(void) {} ++void spu_lockline_unlock(void) {} ++ ++#define CHECK(c) do { if (!(c)) { printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); exit(1); } } while (0) ++ ++#define MEM_SIZE (64u << 20) ++#define G_TYPE 0x10000u ++#define G_CB 0x10010u ++#define G_HANDLE 0x10020u ++#define G_AUINFO 0x10040u ++#define G_ITEMPTR 0x100A0u ++#define G_AU 0x00100000u ++#define G_OUT 0x00200000u ++#define CB_OPD 0x00001000u ++#define AC3_FRAME 1792u ++ ++static u32 s_msgs[8192]; ++static int s_nmsg; ++static u32 s_handle; ++static void fake_guest_call(uint32_t opd, uint64_t a0, uint64_t a1, uint64_t a2, ++ uint64_t a3, uint64_t a4, uint64_t a5, uint64_t a6, uint64_t a7) ++{ ++ (void)a2; (void)a4; (void)a5; (void)a6; (void)a7; ++ CHECK(opd == CB_OPD && a3 == 0xC0FFEEu && a0 == s_handle); ++ /* AUDONE hands the AU back: a title's demuxer may refill it at once. */ ++ if ((u32)a1 == CELL_ADEC_MSG_TYPE_AUDONE) memset(vm_base + G_AU, 0xA5, 0x10000); ++ if (s_nmsg < 8192) s_msgs[s_nmsg++] = (u32)a1; ++} ++ps3_guest_caller_fn g_ps3_guest_caller = fake_guest_call; ++ ++static u8* read_file(const char* path, size_t* len) ++{ ++ FILE* f = fopen(path, "rb"); ++ if (!f) { printf("cannot open %s\n", path); exit(1); } ++ fseek(f, 0, SEEK_END); ++ long n = ftell(f); ++ fseek(f, 0, SEEK_SET); ++ u8* p = (u8*)malloc((size_t)n + 1); ++ CHECK(p && fread(p, 1, (size_t)n, f) == (size_t)n); ++ fclose(f); ++ *len = (size_t)n; ++ return p; ++} ++ ++static void open_adec(u32 codec) ++{ ++ vm_write32(G_TYPE, codec); ++ vm_write32(G_CB, CB_OPD); ++ vm_write32(G_CB + 4, 0xC0FFEEu); ++ CHECK(cellAdecOpen((const CellAdecType*)(uintptr_t)G_TYPE, NULL, ++ (const CellAdecCb*)(uintptr_t)G_CB, (CellAdecHandle*)(uintptr_t)G_HANDLE) == CELL_OK); ++ s_handle = vm_read32(G_HANDLE); ++ CHECK(cellAdecStartSeq(s_handle, NULL) == CELL_OK); ++} ++ ++/* One AU through the guest API: returns the PCM size the item announced and leaves the PCM at G_OUT. */ ++static u32 decode_one(const u8* au, u32 size) ++{ ++ memcpy(vm_base + G_AU, au, size); ++ vm_write32(G_AUINFO + 0, G_AU); ++ vm_write32(G_AUINFO + 4, size); ++ int before = s_nmsg; ++ CHECK(cellAdecDecodeAu(s_handle, (const CellAdecAuInfo*)(uintptr_t)G_AUINFO) == CELL_OK); ++ CHECK(s_nmsg == before + 2 && s_msgs[before] == CELL_ADEC_MSG_TYPE_AUDONE && ++ s_msgs[before + 1] == CELL_ADEC_MSG_TYPE_PCMOUT); ++ CHECK(cellAdecGetPcmItem(s_handle, (const CellAdecPcmItem**)(uintptr_t)G_ITEMPTR) == CELL_OK); ++ u32 item = vm_read32(G_ITEMPTR); ++ u32 bytes = vm_read32(item + PCMITEM_SIZE); ++ u32 bsi = vm_read32(item + PCMITEM_BSI_INFO); ++ CHECK(bsi && vm_read32(bsi + 0x14) == bytes); ++ CHECK(vm_read32(item + PCMITEM_AU_START) == G_AU && vm_read32(item + PCMITEM_AU_SIZE) == size); ++ memset(vm_base + G_OUT, 0x5A, bytes + 64); ++ CHECK(cellAdecGetPcm(s_handle, (void*)(uintptr_t)G_OUT) == CELL_OK); ++ CHECK(vm_base[G_OUT + bytes] == 0x5A); /* exactly `bytes` written */ ++ return bytes; ++} ++ ++static int all_zero(u32 ea, u32 n) ++{ ++ for (u32 i = 0; i < n; i++) if (vm_base[ea + i]) return 0; ++ return 1; ++} ++ ++static int mode_stub(int argc, char** argv) ++{ ++ CHECK(argc >= 4); ++ size_t n6, n2; ++ u8* a6 = read_file(argv[2], &n6); ++ u8* a2 = read_file(argv[3], &n2); ++ CHECK(n6 >= AC3_FRAME && n2 >= AC3_FRAME && a6[0] == 0x0B && a6[1] == 0x77); ++ CHECK(adec_ac3_channels(a6, AC3_FRAME) == 6 && adec_ac3_channels(a2, AC3_FRAME) == 2); ++ open_adec(CELL_ADEC_TYPE_AC3); ++ CHECK(s_adec[s_handle].ff == NULL); ++ for (int i = 0; i < 3; i++) { ++ u32 b = decode_one(a6 + (size_t)i * AC3_FRAME, AC3_FRAME); ++ CHECK(b == 1536u * 6u * 4u && all_zero(G_OUT, b)); ++ } ++ u32 b = decode_one(a2, AC3_FRAME); ++ CHECK(b == 1536u * 2u * 4u && all_zero(G_OUT, b)); ++ CHECK(cellAdecClose(s_handle) == CELL_OK); ++ open_adec(5); ++ b = decode_one(a6, AC3_FRAME); ++ CHECK(b == 1024u * 2u * 4u && all_zero(G_OUT, b)); ++ CHECK(cellAdecClose(s_handle) == CELL_OK); ++ printf("OK stub: AC3 5.1 36864, 2.0 12288, codecType 5 8192 bytes of silence per AU\n"); ++ return 0; ++} ++ ++#ifdef PS3RECOMP_FFMPEG_RUNTIME ++/* Decode the whole stream; compare against REF. swap: exchange channels 0 and 1 of the guest PCM; drop: skip AU 3. */ ++static int run_decode(const u8* ac3, size_t n, const float* ref, size_t nref, int swap, int drop) ++{ ++ open_adec(CELL_ADEC_TYPE_AC3); ++ CHECK(s_adec[s_handle].ff != NULL); ++ size_t at = 0; ++ int bad = 0; ++ for (size_t off = 0, k = 0; off + AC3_FRAME <= n; off += AC3_FRAME, k++) { ++ if (drop && k == 3) continue; ++ u32 b = decode_one(ac3 + off, AC3_FRAME); ++ if (b != 1536u * 6u * 4u) { printf("AU %zu: %u bytes\n", k, b); bad = 1; break; } ++ for (u32 i = 0; i < b / 4u; i++) { ++ u32 idx = i; ++ if (swap && (i % 6u) < 2u) idx = i ^ 1u; ++ u32 w = vm_read32(G_OUT + idx * 4u); ++ float v; ++ memcpy(&v, &w, 4); ++ if (at + i >= nref || v != ref[at + i]) { ++ if (!bad) printf("sample %zu (AU %zu): %g vs %g\n", at + i, k, v, at + i < nref ? ref[at + i] : -1.f); ++ bad = 1; ++ break; ++ } ++ } ++ if (bad) break; ++ at += b / 4u; ++ } ++ if (!bad && at != nref) { printf("%zu samples, reference has %zu\n", at, nref); bad = 1; } ++ CHECK(cellAdecClose(s_handle) == CELL_OK); ++ return bad; ++} ++ ++static int mode_decode(int argc, char** argv) ++{ ++ CHECK(argc >= 4); ++ if (!ps3_ffmpeg_get()) { printf("SKIP: libavcodec not loadable\n"); return 77; } ++ size_t n, nr; ++ u8* ac3 = read_file(argv[2], &n); ++ u8* refb = read_file(argv[3], &nr); ++ CHECK(n % AC3_FRAME == 0 && n / AC3_FRAME >= 8 && nr % 4 == 0); ++ const float* ref = (const float*)refb; ++ CHECK(run_decode(ac3, n, ref, nr / 4, 0, 0) == 0); ++ /* Nonzero audio came through, not silence. */ ++ double e = 0; ++ for (size_t i = 0; i < nr / 4; i++) e += fabs(ref[i]); ++ CHECK(e > 1.0); ++ printf("OK decode: %zu AUs, %zu samples equal FFmpeg's own decode\n", n / AC3_FRAME, nr / 4); ++ CHECK(run_decode(ac3, n, ref, nr / 4, 1, 0) != 0); ++ CHECK(run_decode(ac3, n, ref, nr / 4, 0, 1) != 0); ++ printf("OK negative controls: swapped channels and a dropped AU are caught\n"); ++ return 0; ++} ++#endif ++ ++int main(int argc, char** argv) ++{ ++ setvbuf(stdout, NULL, _IONBF, 0); ++ vm_base = (uint8_t*)calloc(1, MEM_SIZE); ++ CHECK(vm_base); ++ ppu_vm_size = MEM_SIZE; ++ const char* mode = argc > 1 ? argv[1] : "stub"; ++ if (strcmp(mode, "stub") == 0) return mode_stub(argc, argv); ++#ifdef PS3RECOMP_FFMPEG_RUNTIME ++ if (strcmp(mode, "decode") == 0) return mode_decode(argc, argv); ++#endif ++ printf("unknown mode %s\n", mode); ++ return 2; ++} diff --git a/tasks/sp00nznet__ps3recomp-671/tests/test.sh b/tasks/sp00nznet__ps3recomp-671/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-671/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-671/tests/verifier.py b/tasks/sp00nznet__ps3recomp-671/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-671/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-672/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-672/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-672/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-672/instruction.md b/tasks/sp00nznet__ps3recomp-672/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..152683176f10f98e7c11b4b7d78a44a5658f7d85 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-672/instruction.md @@ -0,0 +1,58 @@ +# Issue + +**Title:** spu_coherency: holder list as a contiguous array, prefetched + +## Description + +## What + +`s_coh_ctxs`, the reservation-holder set, becomes a contiguous array of context pointers instead of a malloc'd linked list. The two notify walks prefetch each holder's `resv_valid` four entries ahead. + +- **Membership rules:** unchanged. A context is appended on its first reservation and swap-removed on `spu_coh_unregister` and `spu_coh_forget_range`. +- **Locking:** unchanged. The array has the same lock-line lock that guarded the list, so the Dekker argument in the file's comment still applies as written. + +## Why + +Every notifier walks the whole set with the lock line held: PUTLLC, PUTLLUC, plain PUTs to marked lines, and every PPU store to a marked line. + +A title can keep dozens of holders registered. God of War: Ascension keeps 38, steady over a run, with ~120-165k lock-line acquisitions a second. + +Each step of the list walk cost a miss on the node, then another on the holder's `resv_valid`. The array removes the first miss, and the prefetch overlaps the second, so the line is held for less time. + +## Evidence + +Downstream branch based on v0.17.0, God of War: Ascension, loaded host (two busy processes), host sampler on the EDGE workload from 120 s, 480 s per run. + +`spu_coh_notify_write`: + +| Run | Holder set | Share of EDGE samples | +|---|---|---| +| before | list | 2.92% | +| after | array | 1.16% | + +`spu_wrch_impl` went from 1.50% to 1.08%. + +Both of those profile runs also had a separate change that has since been reverted downstream (`SPU_WrEventAck` without the lock, #667, closed). The array is independent of it. + +**Tail test with the array in and the ack lock as on master.** Five busy processes on a 6-core / 12-thread host, 300 s, two runs, with `SPU_LOCKLINE_STATS=1`: + +- No wait over 5 ms in either run. +- Last `[lockline]` line of each run: + +``` +[lockline] 454311.333 65536 contended of 2004351 acquisitions, 28.2 ms waited, longest 0.991 ms +[lockline] 455384.417 65536 contended of 1169619 acquisitions, 23.5 ms waited, longest 0.394 ms +``` + +No frame-rate claim: the quiet-host A/B was level within noise. + +## Not yet verified + +- Built against `master`: no. This was a `clang -fsyntax-only` check of `spu_coherency.c` only. The coherency and lock-line tests in CI (Linux) should cover the array paths. +- Other titles: not tested. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-672/solution/patch.diff b/tasks/sp00nznet__ps3recomp-672/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3f6ceab313c50aedcf87e4f4f22b30e76137077e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-672/solution/patch.diff @@ -0,0 +1,144 @@ +diff --git a/runtime/spu/spu_coherency.c b/runtime/spu/spu_coherency.c +index ed2bcf58..3e8a1aeb 100644 +--- a/runtime/spu/spu_coherency.c ++++ b/runtime/spu/spu_coherency.c +@@ -131,12 +131,19 @@ static unsigned char s_coh_bitmap[SPU_COH_BITMAP_SZ]; + + /* Every live virtual context may retain a reservation between scheduling + * quanta; physical SPU count is not a bound on this set. All access is under +- * the lock-line lock. Nodes are removed before their context's lifetime ends. */ +-typedef struct spu_coh_entry { +- spu_context* ctx; +- struct spu_coh_entry* next; +-} spu_coh_entry; +-static spu_coh_entry* s_coh_ctxs; ++ * the lock-line lock. Entries are removed before their context's lifetime ends. ++ * ++ * A contiguous array, not a linked list: every notifier walks all of it with ++ * the line held, and a list's scattered nodes were a cache miss per holder on ++ * top of the one on each holder's resv_valid, which the walk now prefetches a ++ * few entries ahead. */ ++static spu_context** s_coh_ctxs; ++static unsigned s_coh_n, s_coh_cap; ++#define SPU_COH_PREFETCH 4 ++static inline void spu_coh_prefetch_holder(unsigned i) ++{ ++ if (i < s_coh_n) __builtin_prefetch(&s_coh_ctxs[i]->resv_valid); ++} + static spu_coh_watch* s_coh_watches; + + unsigned long g_spu_lr_raise = 0; +@@ -155,17 +162,20 @@ void spu_coh_reserve(spu_context* ctx, uint32_t ea) + g_spu_coh_bits = s_coh_bitmap; + + if (!ctx) return; +- for (spu_coh_entry* entry = s_coh_ctxs; entry; entry = entry->next) +- if (entry->ctx == ctx) { __atomic_store_n(&ctx->coh_listed, 1, __ATOMIC_RELAXED); return; } +- spu_coh_entry* entry = (spu_coh_entry*)malloc(sizeof(*entry)); +- if (!entry) { +- fprintf(stderr, "[spu-coh] cannot register reservation holder %p\n", (void*)ctx); +- fflush(stderr); +- abort(); /* A missed holder loses invalidation events, including ABA. */ ++ for (unsigned i = 0; i < s_coh_n; i++) ++ if (s_coh_ctxs[i] == ctx) { __atomic_store_n(&ctx->coh_listed, 1, __ATOMIC_RELAXED); return; } ++ if (s_coh_n == s_coh_cap) { ++ unsigned cap = s_coh_cap ? s_coh_cap * 2u : 64u; ++ spu_context** grown = (spu_context**)realloc(s_coh_ctxs, cap * sizeof(*grown)); ++ if (!grown) { ++ fprintf(stderr, "[spu-coh] cannot register reservation holder %p\n", (void*)ctx); ++ fflush(stderr); ++ abort(); /* A missed holder loses invalidation events, including ABA. */ ++ } ++ s_coh_ctxs = grown; ++ s_coh_cap = cap; + } +- entry->ctx = ctx; +- entry->next = s_coh_ctxs; +- s_coh_ctxs = entry; ++ s_coh_ctxs[s_coh_n++] = ctx; + __atomic_store_n(&ctx->coh_listed, 1, __ATOMIC_RELAXED); + } + +@@ -217,11 +227,9 @@ void spu_coh_unregister(spu_context* ctx) + * (or its whole async thread) was gone. GH3 at -O2 crashed that way in + * spu_coh_notify_write, reading a freed thread stack. */ + spu_lockline_lock(); +- for (spu_coh_entry** link = &s_coh_ctxs; *link; link = &(*link)->next) { +- if ((*link)->ctx != ctx) continue; +- spu_coh_entry* entry = *link; +- *link = entry->next; +- free(entry); ++ for (unsigned i = 0; i < s_coh_n; i++) { ++ if (s_coh_ctxs[i] != ctx) continue; ++ s_coh_ctxs[i] = s_coh_ctxs[--s_coh_n]; /* order does not matter */ + break; + } + __atomic_store_n(&ctx->coh_listed, 0, __ATOMIC_RELAXED); +@@ -237,18 +245,16 @@ void spu_coh_unregister(spu_context* ctx) + void spu_coh_forget_range(uintptr_t lo, uintptr_t hi) + { + spu_lockline_lock(); +- for (spu_coh_entry** link = &s_coh_ctxs; *link;) { +- spu_coh_entry* entry = *link; +- uintptr_t c = (uintptr_t)entry->ctx; ++ for (unsigned i = 0; i < s_coh_n;) { ++ uintptr_t c = (uintptr_t)s_coh_ctxs[i]; + if (c >= lo && c < hi) { + static int _n = 0; + if (PS3_LOG_FIRST(_n, 16)) + fprintf(stderr, "[spu-coh] leaked ctx %p (img=%d) dropped at thread exit\n", +- (void*)c, entry->ctx->image_id); +- *link = entry->next; +- free(entry); ++ (void*)c, s_coh_ctxs[i]->image_id); ++ s_coh_ctxs[i] = s_coh_ctxs[--s_coh_n]; /* re-check slot i */ + } else { +- link = &entry->next; ++ i++; + } + } + spu_lockline_unlock(); +@@ -288,7 +294,7 @@ __attribute__((weak)) void ppu_resv_break_line(uint32_t ea) { (void)ea; } + * + * Every SPURS policy module polls its workload lines with GETLLAR, so taking + * the one global lock for each poll serialized every SPU on a 128-byte copy. +- * A poll is almost always a context that already holds a node in s_coh_ctxs ++ * A poll is almost always a context that is already in s_coh_ctxs + * re-reading a line that is already marked, and for that case the lock buys + * nothing the reservation itself does not: + * +@@ -314,7 +320,7 @@ __attribute__((weak)) void ppu_resv_break_line(uint32_t ea) { (void)ea; } + * Two preconditions keep every writer of the line on that right-hand side: + * - the line is already marked. Marks are never cleared, so every store path + * that checks spu_coh_is_reserved takes the notifier for this line. +- * - ctx is already in s_coh_ctxs (coh_listed). The node was linked under the ++ * - ctx is already in s_coh_ctxs (coh_listed). The entry was added under the + * lock by an earlier GETLLAR of this same thread, so any writer whose + * critical section could overlap this read walks past it. + * Anything else takes the lock and spu_coh_reserve as before. +@@ -353,8 +359,10 @@ void spu_coh_notify_write_except(uint32_t ea, const void* self) + ppu_resv_break_line(ea); + spu_coh_writer_fence(); + spu_coh_wake_watches(line); +- for (spu_coh_entry* entry = s_coh_ctxs; entry; entry = entry->next) { +- spu_context* c = entry->ctx; ++ for (unsigned i = 0; i < SPU_COH_PREFETCH; i++) spu_coh_prefetch_holder(i); ++ for (unsigned i = 0; i < s_coh_n; i++) { ++ spu_coh_prefetch_holder(i + SPU_COH_PREFETCH); ++ spu_context* c = s_coh_ctxs[i]; + if (!c || (const void*)c == self) continue; + if (spu_coh_holds(c, line)) { + SPU_EVENT_SET(c, SPU_EVENT_LR); +@@ -371,8 +379,10 @@ void spu_coh_notify_write(uint32_t ea) + ppu_resv_break_line(ea); + spu_coh_writer_fence(); + spu_coh_wake_watches(line); +- for (spu_coh_entry* entry = s_coh_ctxs; entry; entry = entry->next) { +- spu_context* c = entry->ctx; ++ for (unsigned i = 0; i < SPU_COH_PREFETCH; i++) spu_coh_prefetch_holder(i); ++ for (unsigned i = 0; i < s_coh_n; i++) { ++ spu_coh_prefetch_holder(i + SPU_COH_PREFETCH); ++ spu_context* c = s_coh_ctxs[i]; + if (!c) continue; + if (spu_coh_holds(c, line)) { + SPU_EVENT_SET(c, SPU_EVENT_LR); diff --git a/tasks/sp00nznet__ps3recomp-672/solution/solve.sh b/tasks/sp00nznet__ps3recomp-672/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-672/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-672/task.toml b/tasks/sp00nznet__ps3recomp-672/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fab2e9fa359c238502cdfa0bff9d88b07dab3772 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-672/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-672" +description = "spu_coherency: holder list as a contiguous array, prefetched" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/672" +source_access = "auto" +built_at = "2026-11-16T16:09:59.640259+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d6ce85b228fb55c0c48f66f5e02fc9057c8cdac7484c0c3c1a1cf675ada0ac44" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "runtime/spu/spu_coherency.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 78 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.150431+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-672/tests/capture.py b/tasks/sp00nznet__ps3recomp-672/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-672/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-672/tests/instruction.md b/tasks/sp00nznet__ps3recomp-672/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..152683176f10f98e7c11b4b7d78a44a5658f7d85 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-672/tests/instruction.md @@ -0,0 +1,58 @@ +# Issue + +**Title:** spu_coherency: holder list as a contiguous array, prefetched + +## Description + +## What + +`s_coh_ctxs`, the reservation-holder set, becomes a contiguous array of context pointers instead of a malloc'd linked list. The two notify walks prefetch each holder's `resv_valid` four entries ahead. + +- **Membership rules:** unchanged. A context is appended on its first reservation and swap-removed on `spu_coh_unregister` and `spu_coh_forget_range`. +- **Locking:** unchanged. The array has the same lock-line lock that guarded the list, so the Dekker argument in the file's comment still applies as written. + +## Why + +Every notifier walks the whole set with the lock line held: PUTLLC, PUTLLUC, plain PUTs to marked lines, and every PPU store to a marked line. + +A title can keep dozens of holders registered. God of War: Ascension keeps 38, steady over a run, with ~120-165k lock-line acquisitions a second. + +Each step of the list walk cost a miss on the node, then another on the holder's `resv_valid`. The array removes the first miss, and the prefetch overlaps the second, so the line is held for less time. + +## Evidence + +Downstream branch based on v0.17.0, God of War: Ascension, loaded host (two busy processes), host sampler on the EDGE workload from 120 s, 480 s per run. + +`spu_coh_notify_write`: + +| Run | Holder set | Share of EDGE samples | +|---|---|---| +| before | list | 2.92% | +| after | array | 1.16% | + +`spu_wrch_impl` went from 1.50% to 1.08%. + +Both of those profile runs also had a separate change that has since been reverted downstream (`SPU_WrEventAck` without the lock, #667, closed). The array is independent of it. + +**Tail test with the array in and the ack lock as on master.** Five busy processes on a 6-core / 12-thread host, 300 s, two runs, with `SPU_LOCKLINE_STATS=1`: + +- No wait over 5 ms in either run. +- Last `[lockline]` line of each run: + +``` +[lockline] 454311.333 65536 contended of 2004351 acquisitions, 28.2 ms waited, longest 0.991 ms +[lockline] 455384.417 65536 contended of 1169619 acquisitions, 23.5 ms waited, longest 0.394 ms +``` + +No frame-rate claim: the quiet-host A/B was level within noise. + +## Not yet verified + +- Built against `master`: no. This was a `clang -fsyntax-only` check of `spu_coherency.c` only. The coherency and lock-line tests in CI (Linux) should cover the array paths. +- Other titles: not tested. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-672/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-672/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3f6ceab313c50aedcf87e4f4f22b30e76137077e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-672/tests/oracle.patch @@ -0,0 +1,144 @@ +diff --git a/runtime/spu/spu_coherency.c b/runtime/spu/spu_coherency.c +index ed2bcf58..3e8a1aeb 100644 +--- a/runtime/spu/spu_coherency.c ++++ b/runtime/spu/spu_coherency.c +@@ -131,12 +131,19 @@ static unsigned char s_coh_bitmap[SPU_COH_BITMAP_SZ]; + + /* Every live virtual context may retain a reservation between scheduling + * quanta; physical SPU count is not a bound on this set. All access is under +- * the lock-line lock. Nodes are removed before their context's lifetime ends. */ +-typedef struct spu_coh_entry { +- spu_context* ctx; +- struct spu_coh_entry* next; +-} spu_coh_entry; +-static spu_coh_entry* s_coh_ctxs; ++ * the lock-line lock. Entries are removed before their context's lifetime ends. ++ * ++ * A contiguous array, not a linked list: every notifier walks all of it with ++ * the line held, and a list's scattered nodes were a cache miss per holder on ++ * top of the one on each holder's resv_valid, which the walk now prefetches a ++ * few entries ahead. */ ++static spu_context** s_coh_ctxs; ++static unsigned s_coh_n, s_coh_cap; ++#define SPU_COH_PREFETCH 4 ++static inline void spu_coh_prefetch_holder(unsigned i) ++{ ++ if (i < s_coh_n) __builtin_prefetch(&s_coh_ctxs[i]->resv_valid); ++} + static spu_coh_watch* s_coh_watches; + + unsigned long g_spu_lr_raise = 0; +@@ -155,17 +162,20 @@ void spu_coh_reserve(spu_context* ctx, uint32_t ea) + g_spu_coh_bits = s_coh_bitmap; + + if (!ctx) return; +- for (spu_coh_entry* entry = s_coh_ctxs; entry; entry = entry->next) +- if (entry->ctx == ctx) { __atomic_store_n(&ctx->coh_listed, 1, __ATOMIC_RELAXED); return; } +- spu_coh_entry* entry = (spu_coh_entry*)malloc(sizeof(*entry)); +- if (!entry) { +- fprintf(stderr, "[spu-coh] cannot register reservation holder %p\n", (void*)ctx); +- fflush(stderr); +- abort(); /* A missed holder loses invalidation events, including ABA. */ ++ for (unsigned i = 0; i < s_coh_n; i++) ++ if (s_coh_ctxs[i] == ctx) { __atomic_store_n(&ctx->coh_listed, 1, __ATOMIC_RELAXED); return; } ++ if (s_coh_n == s_coh_cap) { ++ unsigned cap = s_coh_cap ? s_coh_cap * 2u : 64u; ++ spu_context** grown = (spu_context**)realloc(s_coh_ctxs, cap * sizeof(*grown)); ++ if (!grown) { ++ fprintf(stderr, "[spu-coh] cannot register reservation holder %p\n", (void*)ctx); ++ fflush(stderr); ++ abort(); /* A missed holder loses invalidation events, including ABA. */ ++ } ++ s_coh_ctxs = grown; ++ s_coh_cap = cap; + } +- entry->ctx = ctx; +- entry->next = s_coh_ctxs; +- s_coh_ctxs = entry; ++ s_coh_ctxs[s_coh_n++] = ctx; + __atomic_store_n(&ctx->coh_listed, 1, __ATOMIC_RELAXED); + } + +@@ -217,11 +227,9 @@ void spu_coh_unregister(spu_context* ctx) + * (or its whole async thread) was gone. GH3 at -O2 crashed that way in + * spu_coh_notify_write, reading a freed thread stack. */ + spu_lockline_lock(); +- for (spu_coh_entry** link = &s_coh_ctxs; *link; link = &(*link)->next) { +- if ((*link)->ctx != ctx) continue; +- spu_coh_entry* entry = *link; +- *link = entry->next; +- free(entry); ++ for (unsigned i = 0; i < s_coh_n; i++) { ++ if (s_coh_ctxs[i] != ctx) continue; ++ s_coh_ctxs[i] = s_coh_ctxs[--s_coh_n]; /* order does not matter */ + break; + } + __atomic_store_n(&ctx->coh_listed, 0, __ATOMIC_RELAXED); +@@ -237,18 +245,16 @@ void spu_coh_unregister(spu_context* ctx) + void spu_coh_forget_range(uintptr_t lo, uintptr_t hi) + { + spu_lockline_lock(); +- for (spu_coh_entry** link = &s_coh_ctxs; *link;) { +- spu_coh_entry* entry = *link; +- uintptr_t c = (uintptr_t)entry->ctx; ++ for (unsigned i = 0; i < s_coh_n;) { ++ uintptr_t c = (uintptr_t)s_coh_ctxs[i]; + if (c >= lo && c < hi) { + static int _n = 0; + if (PS3_LOG_FIRST(_n, 16)) + fprintf(stderr, "[spu-coh] leaked ctx %p (img=%d) dropped at thread exit\n", +- (void*)c, entry->ctx->image_id); +- *link = entry->next; +- free(entry); ++ (void*)c, s_coh_ctxs[i]->image_id); ++ s_coh_ctxs[i] = s_coh_ctxs[--s_coh_n]; /* re-check slot i */ + } else { +- link = &entry->next; ++ i++; + } + } + spu_lockline_unlock(); +@@ -288,7 +294,7 @@ __attribute__((weak)) void ppu_resv_break_line(uint32_t ea) { (void)ea; } + * + * Every SPURS policy module polls its workload lines with GETLLAR, so taking + * the one global lock for each poll serialized every SPU on a 128-byte copy. +- * A poll is almost always a context that already holds a node in s_coh_ctxs ++ * A poll is almost always a context that is already in s_coh_ctxs + * re-reading a line that is already marked, and for that case the lock buys + * nothing the reservation itself does not: + * +@@ -314,7 +320,7 @@ __attribute__((weak)) void ppu_resv_break_line(uint32_t ea) { (void)ea; } + * Two preconditions keep every writer of the line on that right-hand side: + * - the line is already marked. Marks are never cleared, so every store path + * that checks spu_coh_is_reserved takes the notifier for this line. +- * - ctx is already in s_coh_ctxs (coh_listed). The node was linked under the ++ * - ctx is already in s_coh_ctxs (coh_listed). The entry was added under the + * lock by an earlier GETLLAR of this same thread, so any writer whose + * critical section could overlap this read walks past it. + * Anything else takes the lock and spu_coh_reserve as before. +@@ -353,8 +359,10 @@ void spu_coh_notify_write_except(uint32_t ea, const void* self) + ppu_resv_break_line(ea); + spu_coh_writer_fence(); + spu_coh_wake_watches(line); +- for (spu_coh_entry* entry = s_coh_ctxs; entry; entry = entry->next) { +- spu_context* c = entry->ctx; ++ for (unsigned i = 0; i < SPU_COH_PREFETCH; i++) spu_coh_prefetch_holder(i); ++ for (unsigned i = 0; i < s_coh_n; i++) { ++ spu_coh_prefetch_holder(i + SPU_COH_PREFETCH); ++ spu_context* c = s_coh_ctxs[i]; + if (!c || (const void*)c == self) continue; + if (spu_coh_holds(c, line)) { + SPU_EVENT_SET(c, SPU_EVENT_LR); +@@ -371,8 +379,10 @@ void spu_coh_notify_write(uint32_t ea) + ppu_resv_break_line(ea); + spu_coh_writer_fence(); + spu_coh_wake_watches(line); +- for (spu_coh_entry* entry = s_coh_ctxs; entry; entry = entry->next) { +- spu_context* c = entry->ctx; ++ for (unsigned i = 0; i < SPU_COH_PREFETCH; i++) spu_coh_prefetch_holder(i); ++ for (unsigned i = 0; i < s_coh_n; i++) { ++ spu_coh_prefetch_holder(i + SPU_COH_PREFETCH); ++ spu_context* c = s_coh_ctxs[i]; + if (!c) continue; + if (spu_coh_holds(c, line)) { + SPU_EVENT_SET(c, SPU_EVENT_LR); diff --git a/tasks/sp00nznet__ps3recomp-672/tests/test.sh b/tasks/sp00nznet__ps3recomp-672/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-672/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-672/tests/verifier.py b/tasks/sp00nznet__ps3recomp-672/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-672/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-674/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-674/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-674/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-674/instruction.md b/tasks/sp00nznet__ps3recomp-674/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..70bd7f4655e57a7512684d1c15a9bf4ab197b099 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-674/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** vmx: compute vmaddfp/vnmsubfp without a libm call per lane + +## Description + +## What +`vmx_vmaddfp` and `vmx_vnmsubfp` called `fmaf` once per lane. Without `-mfma`, MinGW implements `fmaf` as a slow software routine. This adds `vmx_fmaf`: +- With `__FMA__` it calls `fmaf`, which the compiler turns into the FMA instruction. +- Otherwise it computes the exact double product and sum, then rounds to float. +- It calls `fmaf` only in the rare cases where that is not enough: a float rounding midpoint, or a value outside the normal float range (zero, subnormal, overflow, inf, NaN). + +## Why +Games with VMX-heavy matrix code spend a noticeable share of the main thread in these two functions. In a profile of one scene, `vmx_vmaddfp` plus libm `fmaf` was about a fifth of the main thread's busy samples. + +## How +- A float product is exact in double, so one double sum rounded to float equals the fused result, except on a midpoint (low 29 bits `0x10000000`) or outside the normal range. +- Those cases fall back to `fmaf`, so every lane is bit-identical to the old path. +- Both instructions now call `vmx_fmaf`. The negate and flush steps are unchanged. +- The same rule is used in the Killzone 3 port's SPU fmaf (github.com/undecuple/project-helghast). + +## Testing +- New test `tests/test_vmx_fmaf.c` (ctest `vmx_fmaf`, built with `-mno-fma` on x86-64 so the double path is the one tested). It compares `vmx_fmaf` with `fmaf` bit for bit on random inputs, mid-exponent inputs and near-cancellation inputs, and checks `vmx_vmaddfp` and `vnmsubfp` lanes against `fmaf`. The default is 20 million cases; the argument sets the count. +- A 200 million case run on Linux (gcc): 0 differ. +- On master the test does not build, because `vmx_fmaf` does not exist. The result is bit-identical by design, so there is no behavioural failure to show. +- It did not change the frame rate by itself in the scene I profiled (20.0 against 20.0 and 19.9 fps under Proton on Linux). The gain is less CPU in these functions, not a visible fps change. + +## Risk +Low, and bit-identical by construction. The code assumes the host rounding mode is round-to-nearest; nothing in the runtime changes MXCSR, and the comment says so. On compilers where `fmaf` is already fast (hardware or glibc), the new path may not be faster, but gives the same results. + +## Overlap +- No open PR touches `runtime/ppu/ppu_vmx.h`. +- `CMakeLists.txt`: the new test entry sits next to #658's (line 431); whichever lands second needs a one-line rebase there. #671 and #650 apply cleanly. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-674/solution/patch.diff b/tasks/sp00nznet__ps3recomp-674/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f55ab0c898d8e9172586ad0743b8fe9a39c5ae68 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-674/solution/patch.diff @@ -0,0 +1,136 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..b6cdbec3 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -431,6 +431,19 @@ if(PS3RECOMP_BUILD_TESTS) + "${CMAKE_CURRENT_SOURCE_DIR}/libs/video") + add_test(NAME rsx_present_policy COMMAND test_rsx_present_policy) + ++ # vmx_fmaf (fused multiply-add without a libm call per lane) against fmaf. ++ # Without -mfma it takes the double-rounding path; with it, the builtin. ++ add_executable(test_vmx_fmaf tests/test_vmx_fmaf.c) ++ target_compile_options(test_vmx_fmaf PRIVATE -UNDEBUG) ++ if(NOT MSVC AND CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64") ++ target_compile_options(test_vmx_fmaf PRIVATE -mno-fma) ++ endif() ++ if(NOT WIN32) ++ target_link_libraries(test_vmx_fmaf PRIVATE m) ++ endif() ++ add_test(NAME vmx_fmaf COMMAND test_vmx_fmaf) ++ set_tests_properties(vmx_fmaf PROPERTIES TIMEOUT 120) ++ + + find_package(Python3 3.10 COMPONENTS Interpreter QUIET) + if(Python3_Interpreter_FOUND) +diff --git a/runtime/ppu/ppu_vmx.h b/runtime/ppu/ppu_vmx.h +index 35052c67..0492f9b7 100644 +--- a/runtime/ppu/ppu_vmx.h ++++ b/runtime/ppu/ppu_vmx.h +@@ -275,16 +275,37 @@ VMX_FBIN(vmx_vsubfp, vmx_f(x) - vmx_f(y), 1) + VMX_FBIN(vmx_vmaxfp, vmx_maxf(vmx_f(x), vmx_f(y)), 0) + VMX_FBIN(vmx_vminfp, vmx_minf(vmx_f(x), vmx_f(y)), 0) + ++/* Fused multiply-add without a libm call per lane. Without -mfma, fmaf is a ++ * software routine on MinGW, and vmaddfp/vnmsubfp called it once per lane. The ++ * product of two floats is exact in double, so s = x*z + y has one double ++ * rounding; rounding s to float then equals the correctly rounded fused result ++ * unless s sits exactly on a float rounding midpoint (low 29 bits 0x10000000) ++ * or outside the normal float range (zero, subnormal, overflow, inf, NaN). ++ * Those rare cases still call fmaf, so every lane is bit-identical to fmaf. ++ * ASSUMPTION: the host rounding mode is round-to-nearest (nothing in the ++ * runtime changes MXCSR). */ ++VMX_INL float vmx_fmaf(float x, float z, float y) { ++#if defined(__FMA__) ++ return fmaf(x, z, y); /* one instruction with -mfma */ ++#else ++ const double s = (double)x * (double)z + (double)y; ++ uint64_t u; memcpy(&u, &s, sizeof u); ++ const uint32_t e = (uint32_t)(u >> 52) & 0x7FFu; ++ if ((u & 0x1FFFFFFFull) != 0x10000000ull && e - (1023u - 126u) < 254u) ++ return (float)s; ++ return fmaf(x, z, y); ++#endif ++} + VMX_INL void vmx_vmaddfp(VMX_D, VMX_A, VMX_B, VMX_C, uint32_t vscr) { VMX_ARGS_PREP; const uint8_t* c = (const uint8_t*)c_; + for (int i = 0; i < 4; i++) { + float x = vmx_f(vmx_flush(vmx_w(a, i), vscr)), y = vmx_f(vmx_flush(vmx_w(b, i), vscr)), + z = vmx_f(vmx_flush(vmx_w(c, i), vscr)); +- vmx_sw(r, i, vmx_flush(vmx_fix(vmx_u(fmaf(x, z, y))), vscr)); } VMX_OUT; } ++ vmx_sw(r, i, vmx_flush(vmx_fix(vmx_u(vmx_fmaf(x, z, y))), vscr)); } VMX_OUT; } + VMX_INL void vmx_vnmsubfp(VMX_D, VMX_A, VMX_B, VMX_C, uint32_t vscr) { VMX_ARGS_PREP; const uint8_t* c = (const uint8_t*)c_; + for (int i = 0; i < 4; i++) { + float x = vmx_f(vmx_flush(vmx_w(a, i), vscr)), y = vmx_f(vmx_flush(vmx_w(b, i), vscr)), + z = vmx_f(vmx_flush(vmx_w(c, i), vscr)); +- vmx_sw(r, i, vmx_flush(vmx_fix(vmx_u(-fmaf(x, z, -y))), vscr)); } VMX_OUT; } ++ vmx_sw(r, i, vmx_flush(vmx_fix(vmx_u(-vmx_fmaf(x, z, -y))), vscr)); } VMX_OUT; } + + #define VMX_FUN(name, expr, flush_in, nanmode) \ + VMX_INL void name(VMX_D, VMX_B, uint32_t vscr) { const uint8_t* b = (const uint8_t*)b_; uint8_t r[16]; \ +diff --git a/tests/test_vmx_fmaf.c b/tests/test_vmx_fmaf.c +new file mode 100644 +index 00000000..31a48096 +--- /dev/null ++++ b/tests/test_vmx_fmaf.c +@@ -0,0 +1,62 @@ ++/* vmx_fmaf (runtime/ppu/ppu_vmx.h) against libm fmaf, and vmaddfp / vnmsubfp against fmaf lane by lane. ++ * ++ * vmx_fmaf must be bit-identical to fmaf for every input (NaNs compare as NaN). The inputs are random words, ++ * random words limited to a mid exponent range (so sums stay normal and the double path is the one taken), and ++ * products made to nearly cancel the addend (the subnormal and rounding-midpoint edges). Built with -mno-fma on ++ * x86-64 so the double-rounding path is the one tested. ++ * ++ * test_vmx_fmaf [count] default 20 million cases ++ */ ++#include <stdio.h> ++#include <stdint.h> ++#include <string.h> ++#include <math.h> ++#include <stdlib.h> ++#include "../runtime/ppu/ppu_vmx.h" ++ ++static uint64_t st = 88172645463325252ull; ++static uint32_t rnd(void) { st ^= st << 13; st ^= st >> 7; st ^= st << 17; return (uint32_t)st; } ++static float f(uint32_t u) { float x; memcpy(&x, &u, 4); return x; } ++static uint32_t U(float x) { uint32_t u; memcpy(&u, &x, 4); return u; } ++static void put(uint8_t* v, int i, float x) { vmx_sw(v, i, U(x)); } ++ ++int main(int argc, char** argv) ++{ ++ const long count = argc > 1 ? atol(argv[1]) : 20000000L; ++ unsigned long long n = 0, bad = 0, lane_bad = 0; ++ for (long i = 0; i < count; i++) { ++ uint32_t a = rnd(), b = rnd(), c = rnd(); ++ if (i & 1) { ++ a = (a & 0x80FFFFFF) | ((0x60 + (rnd() % 0x40)) << 23); ++ b = (b & 0x80FFFFFF) | ((0x60 + (rnd() % 0x40)) << 23); ++ c = (c & 0x80FFFFFF) | ((0x60 + (rnd() % 0x40)) << 23); ++ } ++ if ((i & 7) == 2) c = U(-f(a) * f(b)) ^ (rnd() & 0xF); /* near cancellation */ ++ const float x = f(a), z = f(b), y = f(c); ++ const uint32_t r1 = U(vmx_fmaf(x, z, y)), r2 = U(fmaf(x, z, y)); ++ n++; ++ if (r1 != r2 && !(isnan(f(r1)) && isnan(f(r2)))) { ++ if (bad < 5) printf("diff %08x %08x %08x: %08x vs %08x\n", a, b, c, r1, r2); ++ bad++; ++ } ++ if ((i & 63) == 0) { ++ /* vmaddfp: d = a * c + b; vnmsubfp: d = -(a * c - b). Four lanes, no flush, no NaNs. */ ++ uint8_t va[16], vb[16], vc[16], d1[16], d2[16]; ++ float xs[4], zs[4], ys[4]; ++ for (int l = 0; l < 4; l++) { ++ xs[l] = f(rnd()); zs[l] = f(rnd()); ys[l] = f(rnd()); ++ if (!isfinite(xs[l]) || !isfinite(zs[l]) || !isfinite(ys[l])) { xs[l] = 1.5f; zs[l] = -2.25f; ys[l] = 0.75f; } ++ put(va, l, xs[l]); put(vc, l, zs[l]); put(vb, l, ys[l]); ++ } ++ vmx_vmaddfp(d1, va, vb, vc, 0); ++ vmx_vnmsubfp(d2, va, vb, vc, 0); ++ for (int l = 0; l < 4; l++) { ++ const float e1 = fmaf(xs[l], zs[l], ys[l]), e2 = -fmaf(xs[l], zs[l], -ys[l]); ++ if (isnan(e1) || isnan(e2)) continue; ++ if (vmx_w(d1, l) != U(e1) || vmx_w(d2, l) != U(e2)) lane_bad++; ++ } ++ } ++ } ++ printf("%llu cases, %llu differ; vmaddfp/vnmsubfp lanes: %llu differ\n", n, bad, lane_bad); ++ return (bad || lane_bad) ? 1 : 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-674/solution/solve.sh b/tasks/sp00nznet__ps3recomp-674/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-674/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-674/task.toml b/tasks/sp00nznet__ps3recomp-674/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8ac9eda3691d7b73d759e159923165db2ebc9ee7 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-674/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-674" +description = "vmx: compute vmaddfp/vnmsubfp without a libm call per lane" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/674" +source_access = "auto" +built_at = "2026-11-16T16:09:59.729793+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:fb3b518ffcbeb950aa1c44841dd81462a994662999b19d373c012cba8003a625" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "CMakeLists.txt", + "runtime/ppu/ppu_vmx.h", + "tests/test_vmx_fmaf.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 100 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.150970+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-674/tests/capture.py b/tasks/sp00nznet__ps3recomp-674/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-674/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-674/tests/instruction.md b/tasks/sp00nznet__ps3recomp-674/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..70bd7f4655e57a7512684d1c15a9bf4ab197b099 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-674/tests/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** vmx: compute vmaddfp/vnmsubfp without a libm call per lane + +## Description + +## What +`vmx_vmaddfp` and `vmx_vnmsubfp` called `fmaf` once per lane. Without `-mfma`, MinGW implements `fmaf` as a slow software routine. This adds `vmx_fmaf`: +- With `__FMA__` it calls `fmaf`, which the compiler turns into the FMA instruction. +- Otherwise it computes the exact double product and sum, then rounds to float. +- It calls `fmaf` only in the rare cases where that is not enough: a float rounding midpoint, or a value outside the normal float range (zero, subnormal, overflow, inf, NaN). + +## Why +Games with VMX-heavy matrix code spend a noticeable share of the main thread in these two functions. In a profile of one scene, `vmx_vmaddfp` plus libm `fmaf` was about a fifth of the main thread's busy samples. + +## How +- A float product is exact in double, so one double sum rounded to float equals the fused result, except on a midpoint (low 29 bits `0x10000000`) or outside the normal range. +- Those cases fall back to `fmaf`, so every lane is bit-identical to the old path. +- Both instructions now call `vmx_fmaf`. The negate and flush steps are unchanged. +- The same rule is used in the Killzone 3 port's SPU fmaf (github.com/undecuple/project-helghast). + +## Testing +- New test `tests/test_vmx_fmaf.c` (ctest `vmx_fmaf`, built with `-mno-fma` on x86-64 so the double path is the one tested). It compares `vmx_fmaf` with `fmaf` bit for bit on random inputs, mid-exponent inputs and near-cancellation inputs, and checks `vmx_vmaddfp` and `vnmsubfp` lanes against `fmaf`. The default is 20 million cases; the argument sets the count. +- A 200 million case run on Linux (gcc): 0 differ. +- On master the test does not build, because `vmx_fmaf` does not exist. The result is bit-identical by design, so there is no behavioural failure to show. +- It did not change the frame rate by itself in the scene I profiled (20.0 against 20.0 and 19.9 fps under Proton on Linux). The gain is less CPU in these functions, not a visible fps change. + +## Risk +Low, and bit-identical by construction. The code assumes the host rounding mode is round-to-nearest; nothing in the runtime changes MXCSR, and the comment says so. On compilers where `fmaf` is already fast (hardware or glibc), the new path may not be faster, but gives the same results. + +## Overlap +- No open PR touches `runtime/ppu/ppu_vmx.h`. +- `CMakeLists.txt`: the new test entry sits next to #658's (line 431); whichever lands second needs a one-line rebase there. #671 and #650 apply cleanly. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-674/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-674/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f55ab0c898d8e9172586ad0743b8fe9a39c5ae68 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-674/tests/oracle.patch @@ -0,0 +1,136 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..b6cdbec3 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -431,6 +431,19 @@ if(PS3RECOMP_BUILD_TESTS) + "${CMAKE_CURRENT_SOURCE_DIR}/libs/video") + add_test(NAME rsx_present_policy COMMAND test_rsx_present_policy) + ++ # vmx_fmaf (fused multiply-add without a libm call per lane) against fmaf. ++ # Without -mfma it takes the double-rounding path; with it, the builtin. ++ add_executable(test_vmx_fmaf tests/test_vmx_fmaf.c) ++ target_compile_options(test_vmx_fmaf PRIVATE -UNDEBUG) ++ if(NOT MSVC AND CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64") ++ target_compile_options(test_vmx_fmaf PRIVATE -mno-fma) ++ endif() ++ if(NOT WIN32) ++ target_link_libraries(test_vmx_fmaf PRIVATE m) ++ endif() ++ add_test(NAME vmx_fmaf COMMAND test_vmx_fmaf) ++ set_tests_properties(vmx_fmaf PROPERTIES TIMEOUT 120) ++ + + find_package(Python3 3.10 COMPONENTS Interpreter QUIET) + if(Python3_Interpreter_FOUND) +diff --git a/runtime/ppu/ppu_vmx.h b/runtime/ppu/ppu_vmx.h +index 35052c67..0492f9b7 100644 +--- a/runtime/ppu/ppu_vmx.h ++++ b/runtime/ppu/ppu_vmx.h +@@ -275,16 +275,37 @@ VMX_FBIN(vmx_vsubfp, vmx_f(x) - vmx_f(y), 1) + VMX_FBIN(vmx_vmaxfp, vmx_maxf(vmx_f(x), vmx_f(y)), 0) + VMX_FBIN(vmx_vminfp, vmx_minf(vmx_f(x), vmx_f(y)), 0) + ++/* Fused multiply-add without a libm call per lane. Without -mfma, fmaf is a ++ * software routine on MinGW, and vmaddfp/vnmsubfp called it once per lane. The ++ * product of two floats is exact in double, so s = x*z + y has one double ++ * rounding; rounding s to float then equals the correctly rounded fused result ++ * unless s sits exactly on a float rounding midpoint (low 29 bits 0x10000000) ++ * or outside the normal float range (zero, subnormal, overflow, inf, NaN). ++ * Those rare cases still call fmaf, so every lane is bit-identical to fmaf. ++ * ASSUMPTION: the host rounding mode is round-to-nearest (nothing in the ++ * runtime changes MXCSR). */ ++VMX_INL float vmx_fmaf(float x, float z, float y) { ++#if defined(__FMA__) ++ return fmaf(x, z, y); /* one instruction with -mfma */ ++#else ++ const double s = (double)x * (double)z + (double)y; ++ uint64_t u; memcpy(&u, &s, sizeof u); ++ const uint32_t e = (uint32_t)(u >> 52) & 0x7FFu; ++ if ((u & 0x1FFFFFFFull) != 0x10000000ull && e - (1023u - 126u) < 254u) ++ return (float)s; ++ return fmaf(x, z, y); ++#endif ++} + VMX_INL void vmx_vmaddfp(VMX_D, VMX_A, VMX_B, VMX_C, uint32_t vscr) { VMX_ARGS_PREP; const uint8_t* c = (const uint8_t*)c_; + for (int i = 0; i < 4; i++) { + float x = vmx_f(vmx_flush(vmx_w(a, i), vscr)), y = vmx_f(vmx_flush(vmx_w(b, i), vscr)), + z = vmx_f(vmx_flush(vmx_w(c, i), vscr)); +- vmx_sw(r, i, vmx_flush(vmx_fix(vmx_u(fmaf(x, z, y))), vscr)); } VMX_OUT; } ++ vmx_sw(r, i, vmx_flush(vmx_fix(vmx_u(vmx_fmaf(x, z, y))), vscr)); } VMX_OUT; } + VMX_INL void vmx_vnmsubfp(VMX_D, VMX_A, VMX_B, VMX_C, uint32_t vscr) { VMX_ARGS_PREP; const uint8_t* c = (const uint8_t*)c_; + for (int i = 0; i < 4; i++) { + float x = vmx_f(vmx_flush(vmx_w(a, i), vscr)), y = vmx_f(vmx_flush(vmx_w(b, i), vscr)), + z = vmx_f(vmx_flush(vmx_w(c, i), vscr)); +- vmx_sw(r, i, vmx_flush(vmx_fix(vmx_u(-fmaf(x, z, -y))), vscr)); } VMX_OUT; } ++ vmx_sw(r, i, vmx_flush(vmx_fix(vmx_u(-vmx_fmaf(x, z, -y))), vscr)); } VMX_OUT; } + + #define VMX_FUN(name, expr, flush_in, nanmode) \ + VMX_INL void name(VMX_D, VMX_B, uint32_t vscr) { const uint8_t* b = (const uint8_t*)b_; uint8_t r[16]; \ +diff --git a/tests/test_vmx_fmaf.c b/tests/test_vmx_fmaf.c +new file mode 100644 +index 00000000..31a48096 +--- /dev/null ++++ b/tests/test_vmx_fmaf.c +@@ -0,0 +1,62 @@ ++/* vmx_fmaf (runtime/ppu/ppu_vmx.h) against libm fmaf, and vmaddfp / vnmsubfp against fmaf lane by lane. ++ * ++ * vmx_fmaf must be bit-identical to fmaf for every input (NaNs compare as NaN). The inputs are random words, ++ * random words limited to a mid exponent range (so sums stay normal and the double path is the one taken), and ++ * products made to nearly cancel the addend (the subnormal and rounding-midpoint edges). Built with -mno-fma on ++ * x86-64 so the double-rounding path is the one tested. ++ * ++ * test_vmx_fmaf [count] default 20 million cases ++ */ ++#include <stdio.h> ++#include <stdint.h> ++#include <string.h> ++#include <math.h> ++#include <stdlib.h> ++#include "../runtime/ppu/ppu_vmx.h" ++ ++static uint64_t st = 88172645463325252ull; ++static uint32_t rnd(void) { st ^= st << 13; st ^= st >> 7; st ^= st << 17; return (uint32_t)st; } ++static float f(uint32_t u) { float x; memcpy(&x, &u, 4); return x; } ++static uint32_t U(float x) { uint32_t u; memcpy(&u, &x, 4); return u; } ++static void put(uint8_t* v, int i, float x) { vmx_sw(v, i, U(x)); } ++ ++int main(int argc, char** argv) ++{ ++ const long count = argc > 1 ? atol(argv[1]) : 20000000L; ++ unsigned long long n = 0, bad = 0, lane_bad = 0; ++ for (long i = 0; i < count; i++) { ++ uint32_t a = rnd(), b = rnd(), c = rnd(); ++ if (i & 1) { ++ a = (a & 0x80FFFFFF) | ((0x60 + (rnd() % 0x40)) << 23); ++ b = (b & 0x80FFFFFF) | ((0x60 + (rnd() % 0x40)) << 23); ++ c = (c & 0x80FFFFFF) | ((0x60 + (rnd() % 0x40)) << 23); ++ } ++ if ((i & 7) == 2) c = U(-f(a) * f(b)) ^ (rnd() & 0xF); /* near cancellation */ ++ const float x = f(a), z = f(b), y = f(c); ++ const uint32_t r1 = U(vmx_fmaf(x, z, y)), r2 = U(fmaf(x, z, y)); ++ n++; ++ if (r1 != r2 && !(isnan(f(r1)) && isnan(f(r2)))) { ++ if (bad < 5) printf("diff %08x %08x %08x: %08x vs %08x\n", a, b, c, r1, r2); ++ bad++; ++ } ++ if ((i & 63) == 0) { ++ /* vmaddfp: d = a * c + b; vnmsubfp: d = -(a * c - b). Four lanes, no flush, no NaNs. */ ++ uint8_t va[16], vb[16], vc[16], d1[16], d2[16]; ++ float xs[4], zs[4], ys[4]; ++ for (int l = 0; l < 4; l++) { ++ xs[l] = f(rnd()); zs[l] = f(rnd()); ys[l] = f(rnd()); ++ if (!isfinite(xs[l]) || !isfinite(zs[l]) || !isfinite(ys[l])) { xs[l] = 1.5f; zs[l] = -2.25f; ys[l] = 0.75f; } ++ put(va, l, xs[l]); put(vc, l, zs[l]); put(vb, l, ys[l]); ++ } ++ vmx_vmaddfp(d1, va, vb, vc, 0); ++ vmx_vnmsubfp(d2, va, vb, vc, 0); ++ for (int l = 0; l < 4; l++) { ++ const float e1 = fmaf(xs[l], zs[l], ys[l]), e2 = -fmaf(xs[l], zs[l], -ys[l]); ++ if (isnan(e1) || isnan(e2)) continue; ++ if (vmx_w(d1, l) != U(e1) || vmx_w(d2, l) != U(e2)) lane_bad++; ++ } ++ } ++ } ++ printf("%llu cases, %llu differ; vmaddfp/vnmsubfp lanes: %llu differ\n", n, bad, lane_bad); ++ return (bad || lane_bad) ? 1 : 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-674/tests/test.sh b/tasks/sp00nznet__ps3recomp-674/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-674/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-674/tests/verifier.py b/tasks/sp00nznet__ps3recomp-674/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-674/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-675/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-675/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-675/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-675/instruction.md b/tasks/sp00nznet__ps3recomp-675/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7afbb07ac4ffbf5b1f75683044f279a2e34d1ff9 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-675/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** gcm: decode the new-style JUMP in the FIFO walker + +## Description + +## What +The RSX has two JUMP encodings: the old `0x20000000 | offset` and the new `offset | 1`. The FIFO walker only decoded the old one. A new-style word was read as a count-0 method header (for example `0x00007D01` became subchannel 3, method 0x1D00). + +## Why +The walker did not follow the jump. It fell through into the data after it and wrote that data into registers until it resynced. A game then saw corrupt GPU state. In the case that showed this, junk landed in `NV4097_SET_TRANSFORM_BRANCH_BITS` (0x1FF8), which the game sets only on change, and every vertex program with branches took the wrong path. The scene came out black or scrambled. Reading the word back 50 ms later showed it unchanged, so the decode was at fault, not a buffer still being written. + +## How +- New helper `gcm_fifo_jump_target(w, &tgt)`: `(w >> 29) == 1` gives the old target `w & 0x1FFFFFFC`; `(w & 0xE0000003) == 1` gives the new target `w & 0xFFFFFFFC`. +- The walker's main loop and its "park" check (a JUMP to its own address) both use it, so a new-style self-JUMP parks like the old one. The `GCM_RECDBG` print shows the real target. +- Old-style JUMP and CALL decoding is unchanged. + +## Testing +- New test `tests/gcm_fifo_jump` (ctest `gcm_fifo_jump`). It builds a ring with an old-form and a new-form JUMP, each over a GET_REPORT, and checks the skipped report is not written and the landing report is. +- On master the test fails: `[FAIL] new-form JUMP: skipped report written, landing report written`. On this branch it passes. The existing `gcm_reports` test still passes. +- Linux, gcc, `cmake -DPS3RECOMP_BUILD_TESTS=ON`, then `ctest -R "gcm_fifo_jump|gcm_reports"`. +- Under Proton on Linux, a 470 s run of a scene that failed before, done twice: 0 FIFO resyncs, only the game's own 0x1FF8 values, and the scene drew correctly. + +## Risk +Low. The new branch only matches words that were previously mis-decoded as count-0 method headers. A real count-0 header whose low bits are `01` would now be a jump, but bits 0-1 of a method header are normally 0. Other code in this file (the resync scan) already treats `(w & 3) == 1` as a JUMP. + +## Overlap +- Open PRs that touch `libs/video/cellGcmSys.c` (#673, #660, #657, #654, #653, #652, #651, #650, #648, #647) apply cleanly on top of this one. +- `CMakeLists.txt`: the new test entry sits next to #650's (line 402); whichever lands second needs a one-line rebase there. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-675/solution/patch.diff b/tasks/sp00nznet__ps3recomp-675/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e33b2c97d088972af84240faf884dfd594063c1d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-675/solution/patch.diff @@ -0,0 +1,209 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..b5bbffd1 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -401,6 +401,8 @@ if(PS3RECOMP_BUILD_TESTS) + # each report DMA context. Links the runtime like the POSIX host below. + if(UNIX) + add_subdirectory(tests/gcm_reports) ++ # The same walker's JUMP decode: the old and the new form. ++ add_subdirectory(tests/gcm_fifo_jump) + endif() + # PS3_LOG_FIRST, the saturating counter behind the "first n times" log lines. + add_executable(test_log_first tests/test_log_first.c) +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..176c4fd5 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -164,6 +164,17 @@ static void gcm_set_current_display_buffer(u32 bufferId) + } + + ++/* The two JUMP encodings of the RSX FIFO: the old 0x20000000 | offset, and the new offset | 1 (the low two bits are 01 ++ * and the top three are 000, so the offset is the whole word with those bits cleared). Returns 1 and the target for ++ * either. A new-style word read as a method header would be a count-0 header, and the walker would run on into the ++ * data after the jump. */ ++static inline int gcm_fifo_jump_target(u32 w, u32* tgt) ++{ ++ if ((w >> 29) == 1u) { *tgt = w & 0x1FFFFFFCu; return 1; } ++ if ((w & 0xE0000003u) == 1u) { *tgt = w & 0xFFFFFFFCu; return 1; } ++ return 0; ++} ++ + /* The RSX puts its 3D state back to the reset values at a flip, and a title + * may count on that: one sets ZSTENCIL_CLEAR_VALUE to 0 for a single clear + * and never writes it again, so its later depth clears are to the far plane +@@ -2275,8 +2286,9 @@ static void gcm_rsx_process_fifo_unlocked(void) + * does that -- and that park then inherited a grace that had already + * run out, so the jump-park resync fired at once and dropped the + * commands the title was about to link in. */ +- if (park_off && (s_fifo_getoff != park_off || +- (w & 0xE0000003u) != 0x20000000u || (w & 0x1FFFFFFCu) != park_off)) ++ u32 jump_tgt = 0; ++ const int is_jump = gcm_fifo_jump_target(w, &jump_tgt); ++ if (park_off && (s_fifo_getoff != park_off || !is_jump || jump_tgt != park_off)) + park_off = 0; + + if ((w & 0xFFFF0000u) == 0xFEAD0000u) { +@@ -2333,11 +2345,11 @@ static void gcm_rsx_process_fifo_unlocked(void) + continue; + } + +- if (type == 1) { /* JUMP: 0x20000000 | offset */ ++ if (is_jump) { /* JUMP: 0x20000000 | offset, or offset | 1 */ + { static int _rd = -1; if (_rd < 0) _rd = getenv("GCM_RECDBG") ? 1 : 0; + if (_rd) fprintf(stderr, "[JMP] %08X -> %08X (put=%08X)\n", +- s_fifo_getoff, w & 0x1FFFFFFCu, put); } +- { u32 tgt = w & 0x1FFFFFFCu; ++ s_fifo_getoff, jump_tgt, put); } ++ { u32 tgt = jump_tgt; + if (!gcm_io2ea(tgt)) { gcm_fifo_bad_branch("JUMP", tgt, w); gcm_fifo_dump_around(s_fifo_getoff); gcm_fifo_resync_why("unmapped-JUMP", &s_fifo_getoff, put); break; } + /* A JUMP to its own address is the "park the RSX here" idiom: + * the title leaves it at the write head so the GPU stops if it +diff --git a/tests/gcm_fifo_jump/CMakeLists.txt b/tests/gcm_fifo_jump/CMakeLists.txt +new file mode 100644 +index 00000000..d3909474 +--- /dev/null ++++ b/tests/gcm_fifo_jump/CMakeLists.txt +@@ -0,0 +1,24 @@ ++# ps3recomp - tests/gcm_fifo_jump ++# ++# The cellGcm FIFO walker's JUMP decode, old (0x20000000 | offset) and new ++# (offset | 1), with no graphics backend and no lifted game. Built with the ++# runtime (PS3RECOMP_BUILD_TESTS). ++# ++# ctest --test-dir build-tests -R gcm_fifo_jump --output-on-failure ++ ++add_executable(test_gcm_fifo_jump ++ main.c ++ "${PROJECT_SOURCE_DIR}/runtime/host/host_stubs.c" ++) ++target_link_libraries(test_gcm_fifo_jump PRIVATE ps3recomp_runtime) ++if(NOT WIN32) ++ target_link_libraries(test_gcm_fifo_jump PRIVATE m) ++endif() ++target_include_directories(test_gcm_fifo_jump PRIVATE ++ "${PROJECT_SOURCE_DIR}/libs/video" ++ "${PROJECT_SOURCE_DIR}/include" ++ "${PROJECT_SOURCE_DIR}/runtime" ++) ++# The runtime carries C++, so the C++ driver does the final link. ++set_target_properties(test_gcm_fifo_jump PROPERTIES LINKER_LANGUAGE CXX) ++add_test(NAME gcm_fifo_jump COMMAND test_gcm_fifo_jump) +diff --git a/tests/gcm_fifo_jump/main.c b/tests/gcm_fifo_jump/main.c +new file mode 100644 +index 00000000..78327fbc +--- /dev/null ++++ b/tests/gcm_fifo_jump/main.c +@@ -0,0 +1,111 @@ ++/* ++ * ps3recomp - tests/gcm_fifo_jump ++ * ++ * JUMP decode in the cellGcm FIFO walker. A small command ring is built in ++ * guest memory and drained with cellGcm_rsx_process_fifo; no graphics backend ++ * is involved. Each segment ends in a JUMP over a "skipped" stretch that holds ++ * a GET_REPORT, and lands on a GET_REPORT of its own. A walker that follows ++ * the JUMP writes the landing report and leaves the skipped slot alone. ++ * ++ * - old form 0x20000000 | offset; ++ * - new form offset | 1 (a count-0 method header if it is not decoded: the ++ * walker then runs into the skipped stretch). ++ * ++ * Exit code 0 when every check passes. ++ */ ++#include "cellGcmSys.h" ++#include <stdint.h> ++#include <stdio.h> ++#include <stdlib.h> ++#include <string.h> ++ ++extern void cellGcm_rsx_process_fifo(void); ++extern void vm_write32(uint64_t addr, uint32_t v); ++extern uint32_t vm_read32(uint64_t addr); ++extern uint32_t ppu_vm_size; ++extern uint32_t ppu_hle_inject_base; ++ ++uint8_t* vm_base = NULL; ++ ++#define IO_ADDR 0x00100000u ++#define IO_SIZE 0x00200000u ++#define CMD_SIZE 0x00010000u ++#define HEAP_BASE 0x00400000u ++ ++static void gw32(uint32_t ea, uint32_t v) ++{ ++ uint8_t* p = vm_base + ea; ++ p[0] = (uint8_t)(v >> 24); p[1] = (uint8_t)(v >> 16); p[2] = (uint8_t)(v >> 8); p[3] = (uint8_t)v; ++} ++ ++static uint32_t g_heap = HEAP_BASE; ++static u32 host_alloc(u32 size, u32 align) ++{ ++ if (!align) align = 4; ++ g_heap = (g_heap + align - 1u) & ~(align - 1u); ++ u32 r = g_heap; ++ g_heap += size; ++ return r; ++} ++static void host_w32(u32 ea, u32 v) { gw32(ea, v); } ++ ++static uint32_t g_head; ++static void emit_word(uint32_t v) { gw32(IO_ADDR + g_head, v); g_head += 4; } ++static void emit(uint32_t m, uint32_t d) { emit_word((1u << 18) | (m & 0x1FFCu)); emit_word(d); } ++static void report(uint32_t slot) { emit(0x1800, (1u << 24) | (slot * 16u)); } ++ ++static int g_fail; ++#define CHECK(c, ...) do { if (c) printf("[PASS] " __VA_ARGS__); \ ++ else { g_fail++; printf("[FAIL] " __VA_ARGS__); } printf("\n"); } while (0) ++ ++/* Local report slots (the default report context). */ ++static int written(uint32_t slot) ++{ ++ CellGcmReportData* r = cellGcmGetReportDataAddress(slot); ++ return r && r->timestamp != 0; ++} ++ ++int main(void) ++{ ++ setvbuf(stdout, NULL, _IONBF, 0); ++ const uint32_t vm_size = ppu_hle_inject_base + 0x10000u; ++ vm_base = (uint8_t*)calloc(1, vm_size); ++ if (!vm_base) { printf("[FAIL] guest VM alloc\n"); return 1; } ++ ppu_vm_size = vm_size; ++ ++ u32 ctx_out = host_alloc(4, 4); ++ u32 cdata = cellGcmSetupContext(ctx_out, CMD_SIZE, IO_SIZE, IO_ADDR, host_alloc, host_w32); ++ uint32_t ctrl = (uint32_t)(uintptr_t)cellGcmGetControlRegister(); ++ ++ /* Report slots: 1 before the jumps, 2 skipped by the old-form jump, 3 landed on after it, 4 skipped by the ++ * new-form jump, 5 landed on after it. */ ++ g_head = 0; ++ report(1); ++ { /* old form: JUMP over one report (3 words) to the next */ ++ const uint32_t tgt = g_head + 4u + 8u; ++ emit_word(0x20000000u | tgt); ++ report(2); ++ report(3); ++ } ++ { /* new form: offset | 1 */ ++ const uint32_t tgt = g_head + 4u + 8u; ++ emit_word(tgt | 1u); ++ report(4); ++ report(5); ++ } ++ gw32(cdata + 0x8, IO_ADDR + g_head); ++ vm_write32(ctrl + 0, g_head); ++ cellGcm_rsx_process_fifo(); ++ ++ CHECK(vm_read32(ctrl + 4) == g_head, "walker drained the ring (get 0x%X, put 0x%X)", ++ vm_read32(ctrl + 4), g_head); ++ CHECK(written(1), "report before the jumps written"); ++ CHECK(!written(2) && written(3), "old-form JUMP: skipped report %s, landing report %s", ++ written(2) ? "written" : "not written", written(3) ? "written" : "not written"); ++ CHECK(!written(4) && written(5), "new-form JUMP: skipped report %s, landing report %s", ++ written(4) ? "written" : "not written", written(5) ? "written" : "not written"); ++ ++ printf("[gcm_fifo_jump] %s (%d failed)\n", g_fail ? "FAIL" : "PASS", g_fail); ++ free(vm_base); ++ return g_fail ? 1 : 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-675/solution/solve.sh b/tasks/sp00nznet__ps3recomp-675/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-675/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-675/task.toml b/tasks/sp00nznet__ps3recomp-675/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7bb2dd270841d916d4acfe4c962b8794463e5fe6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-675/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-675" +description = "gcm: decode the new-style JUMP in the FIFO walker" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/675" +source_access = "auto" +built_at = "2026-11-16T16:09:59.727960+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:be5514e64d89677f9a43ee1181110b99fd7e7cef9dbd2eda1cdb39a8d6b35446" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "CMakeLists.txt", + "libs/video/cellGcmSys.c", + "tests/gcm_fifo_jump/CMakeLists.txt", + "tests/gcm_fifo_jump/main.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 159 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.151513+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-675/tests/capture.py b/tasks/sp00nznet__ps3recomp-675/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-675/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-675/tests/instruction.md b/tasks/sp00nznet__ps3recomp-675/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7afbb07ac4ffbf5b1f75683044f279a2e34d1ff9 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-675/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** gcm: decode the new-style JUMP in the FIFO walker + +## Description + +## What +The RSX has two JUMP encodings: the old `0x20000000 | offset` and the new `offset | 1`. The FIFO walker only decoded the old one. A new-style word was read as a count-0 method header (for example `0x00007D01` became subchannel 3, method 0x1D00). + +## Why +The walker did not follow the jump. It fell through into the data after it and wrote that data into registers until it resynced. A game then saw corrupt GPU state. In the case that showed this, junk landed in `NV4097_SET_TRANSFORM_BRANCH_BITS` (0x1FF8), which the game sets only on change, and every vertex program with branches took the wrong path. The scene came out black or scrambled. Reading the word back 50 ms later showed it unchanged, so the decode was at fault, not a buffer still being written. + +## How +- New helper `gcm_fifo_jump_target(w, &tgt)`: `(w >> 29) == 1` gives the old target `w & 0x1FFFFFFC`; `(w & 0xE0000003) == 1` gives the new target `w & 0xFFFFFFFC`. +- The walker's main loop and its "park" check (a JUMP to its own address) both use it, so a new-style self-JUMP parks like the old one. The `GCM_RECDBG` print shows the real target. +- Old-style JUMP and CALL decoding is unchanged. + +## Testing +- New test `tests/gcm_fifo_jump` (ctest `gcm_fifo_jump`). It builds a ring with an old-form and a new-form JUMP, each over a GET_REPORT, and checks the skipped report is not written and the landing report is. +- On master the test fails: `[FAIL] new-form JUMP: skipped report written, landing report written`. On this branch it passes. The existing `gcm_reports` test still passes. +- Linux, gcc, `cmake -DPS3RECOMP_BUILD_TESTS=ON`, then `ctest -R "gcm_fifo_jump|gcm_reports"`. +- Under Proton on Linux, a 470 s run of a scene that failed before, done twice: 0 FIFO resyncs, only the game's own 0x1FF8 values, and the scene drew correctly. + +## Risk +Low. The new branch only matches words that were previously mis-decoded as count-0 method headers. A real count-0 header whose low bits are `01` would now be a jump, but bits 0-1 of a method header are normally 0. Other code in this file (the resync scan) already treats `(w & 3) == 1` as a JUMP. + +## Overlap +- Open PRs that touch `libs/video/cellGcmSys.c` (#673, #660, #657, #654, #653, #652, #651, #650, #648, #647) apply cleanly on top of this one. +- `CMakeLists.txt`: the new test entry sits next to #650's (line 402); whichever lands second needs a one-line rebase there. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-675/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-675/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e33b2c97d088972af84240faf884dfd594063c1d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-675/tests/oracle.patch @@ -0,0 +1,209 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..b5bbffd1 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -401,6 +401,8 @@ if(PS3RECOMP_BUILD_TESTS) + # each report DMA context. Links the runtime like the POSIX host below. + if(UNIX) + add_subdirectory(tests/gcm_reports) ++ # The same walker's JUMP decode: the old and the new form. ++ add_subdirectory(tests/gcm_fifo_jump) + endif() + # PS3_LOG_FIRST, the saturating counter behind the "first n times" log lines. + add_executable(test_log_first tests/test_log_first.c) +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..176c4fd5 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -164,6 +164,17 @@ static void gcm_set_current_display_buffer(u32 bufferId) + } + + ++/* The two JUMP encodings of the RSX FIFO: the old 0x20000000 | offset, and the new offset | 1 (the low two bits are 01 ++ * and the top three are 000, so the offset is the whole word with those bits cleared). Returns 1 and the target for ++ * either. A new-style word read as a method header would be a count-0 header, and the walker would run on into the ++ * data after the jump. */ ++static inline int gcm_fifo_jump_target(u32 w, u32* tgt) ++{ ++ if ((w >> 29) == 1u) { *tgt = w & 0x1FFFFFFCu; return 1; } ++ if ((w & 0xE0000003u) == 1u) { *tgt = w & 0xFFFFFFFCu; return 1; } ++ return 0; ++} ++ + /* The RSX puts its 3D state back to the reset values at a flip, and a title + * may count on that: one sets ZSTENCIL_CLEAR_VALUE to 0 for a single clear + * and never writes it again, so its later depth clears are to the far plane +@@ -2275,8 +2286,9 @@ static void gcm_rsx_process_fifo_unlocked(void) + * does that -- and that park then inherited a grace that had already + * run out, so the jump-park resync fired at once and dropped the + * commands the title was about to link in. */ +- if (park_off && (s_fifo_getoff != park_off || +- (w & 0xE0000003u) != 0x20000000u || (w & 0x1FFFFFFCu) != park_off)) ++ u32 jump_tgt = 0; ++ const int is_jump = gcm_fifo_jump_target(w, &jump_tgt); ++ if (park_off && (s_fifo_getoff != park_off || !is_jump || jump_tgt != park_off)) + park_off = 0; + + if ((w & 0xFFFF0000u) == 0xFEAD0000u) { +@@ -2333,11 +2345,11 @@ static void gcm_rsx_process_fifo_unlocked(void) + continue; + } + +- if (type == 1) { /* JUMP: 0x20000000 | offset */ ++ if (is_jump) { /* JUMP: 0x20000000 | offset, or offset | 1 */ + { static int _rd = -1; if (_rd < 0) _rd = getenv("GCM_RECDBG") ? 1 : 0; + if (_rd) fprintf(stderr, "[JMP] %08X -> %08X (put=%08X)\n", +- s_fifo_getoff, w & 0x1FFFFFFCu, put); } +- { u32 tgt = w & 0x1FFFFFFCu; ++ s_fifo_getoff, jump_tgt, put); } ++ { u32 tgt = jump_tgt; + if (!gcm_io2ea(tgt)) { gcm_fifo_bad_branch("JUMP", tgt, w); gcm_fifo_dump_around(s_fifo_getoff); gcm_fifo_resync_why("unmapped-JUMP", &s_fifo_getoff, put); break; } + /* A JUMP to its own address is the "park the RSX here" idiom: + * the title leaves it at the write head so the GPU stops if it +diff --git a/tests/gcm_fifo_jump/CMakeLists.txt b/tests/gcm_fifo_jump/CMakeLists.txt +new file mode 100644 +index 00000000..d3909474 +--- /dev/null ++++ b/tests/gcm_fifo_jump/CMakeLists.txt +@@ -0,0 +1,24 @@ ++# ps3recomp - tests/gcm_fifo_jump ++# ++# The cellGcm FIFO walker's JUMP decode, old (0x20000000 | offset) and new ++# (offset | 1), with no graphics backend and no lifted game. Built with the ++# runtime (PS3RECOMP_BUILD_TESTS). ++# ++# ctest --test-dir build-tests -R gcm_fifo_jump --output-on-failure ++ ++add_executable(test_gcm_fifo_jump ++ main.c ++ "${PROJECT_SOURCE_DIR}/runtime/host/host_stubs.c" ++) ++target_link_libraries(test_gcm_fifo_jump PRIVATE ps3recomp_runtime) ++if(NOT WIN32) ++ target_link_libraries(test_gcm_fifo_jump PRIVATE m) ++endif() ++target_include_directories(test_gcm_fifo_jump PRIVATE ++ "${PROJECT_SOURCE_DIR}/libs/video" ++ "${PROJECT_SOURCE_DIR}/include" ++ "${PROJECT_SOURCE_DIR}/runtime" ++) ++# The runtime carries C++, so the C++ driver does the final link. ++set_target_properties(test_gcm_fifo_jump PROPERTIES LINKER_LANGUAGE CXX) ++add_test(NAME gcm_fifo_jump COMMAND test_gcm_fifo_jump) +diff --git a/tests/gcm_fifo_jump/main.c b/tests/gcm_fifo_jump/main.c +new file mode 100644 +index 00000000..78327fbc +--- /dev/null ++++ b/tests/gcm_fifo_jump/main.c +@@ -0,0 +1,111 @@ ++/* ++ * ps3recomp - tests/gcm_fifo_jump ++ * ++ * JUMP decode in the cellGcm FIFO walker. A small command ring is built in ++ * guest memory and drained with cellGcm_rsx_process_fifo; no graphics backend ++ * is involved. Each segment ends in a JUMP over a "skipped" stretch that holds ++ * a GET_REPORT, and lands on a GET_REPORT of its own. A walker that follows ++ * the JUMP writes the landing report and leaves the skipped slot alone. ++ * ++ * - old form 0x20000000 | offset; ++ * - new form offset | 1 (a count-0 method header if it is not decoded: the ++ * walker then runs into the skipped stretch). ++ * ++ * Exit code 0 when every check passes. ++ */ ++#include "cellGcmSys.h" ++#include <stdint.h> ++#include <stdio.h> ++#include <stdlib.h> ++#include <string.h> ++ ++extern void cellGcm_rsx_process_fifo(void); ++extern void vm_write32(uint64_t addr, uint32_t v); ++extern uint32_t vm_read32(uint64_t addr); ++extern uint32_t ppu_vm_size; ++extern uint32_t ppu_hle_inject_base; ++ ++uint8_t* vm_base = NULL; ++ ++#define IO_ADDR 0x00100000u ++#define IO_SIZE 0x00200000u ++#define CMD_SIZE 0x00010000u ++#define HEAP_BASE 0x00400000u ++ ++static void gw32(uint32_t ea, uint32_t v) ++{ ++ uint8_t* p = vm_base + ea; ++ p[0] = (uint8_t)(v >> 24); p[1] = (uint8_t)(v >> 16); p[2] = (uint8_t)(v >> 8); p[3] = (uint8_t)v; ++} ++ ++static uint32_t g_heap = HEAP_BASE; ++static u32 host_alloc(u32 size, u32 align) ++{ ++ if (!align) align = 4; ++ g_heap = (g_heap + align - 1u) & ~(align - 1u); ++ u32 r = g_heap; ++ g_heap += size; ++ return r; ++} ++static void host_w32(u32 ea, u32 v) { gw32(ea, v); } ++ ++static uint32_t g_head; ++static void emit_word(uint32_t v) { gw32(IO_ADDR + g_head, v); g_head += 4; } ++static void emit(uint32_t m, uint32_t d) { emit_word((1u << 18) | (m & 0x1FFCu)); emit_word(d); } ++static void report(uint32_t slot) { emit(0x1800, (1u << 24) | (slot * 16u)); } ++ ++static int g_fail; ++#define CHECK(c, ...) do { if (c) printf("[PASS] " __VA_ARGS__); \ ++ else { g_fail++; printf("[FAIL] " __VA_ARGS__); } printf("\n"); } while (0) ++ ++/* Local report slots (the default report context). */ ++static int written(uint32_t slot) ++{ ++ CellGcmReportData* r = cellGcmGetReportDataAddress(slot); ++ return r && r->timestamp != 0; ++} ++ ++int main(void) ++{ ++ setvbuf(stdout, NULL, _IONBF, 0); ++ const uint32_t vm_size = ppu_hle_inject_base + 0x10000u; ++ vm_base = (uint8_t*)calloc(1, vm_size); ++ if (!vm_base) { printf("[FAIL] guest VM alloc\n"); return 1; } ++ ppu_vm_size = vm_size; ++ ++ u32 ctx_out = host_alloc(4, 4); ++ u32 cdata = cellGcmSetupContext(ctx_out, CMD_SIZE, IO_SIZE, IO_ADDR, host_alloc, host_w32); ++ uint32_t ctrl = (uint32_t)(uintptr_t)cellGcmGetControlRegister(); ++ ++ /* Report slots: 1 before the jumps, 2 skipped by the old-form jump, 3 landed on after it, 4 skipped by the ++ * new-form jump, 5 landed on after it. */ ++ g_head = 0; ++ report(1); ++ { /* old form: JUMP over one report (3 words) to the next */ ++ const uint32_t tgt = g_head + 4u + 8u; ++ emit_word(0x20000000u | tgt); ++ report(2); ++ report(3); ++ } ++ { /* new form: offset | 1 */ ++ const uint32_t tgt = g_head + 4u + 8u; ++ emit_word(tgt | 1u); ++ report(4); ++ report(5); ++ } ++ gw32(cdata + 0x8, IO_ADDR + g_head); ++ vm_write32(ctrl + 0, g_head); ++ cellGcm_rsx_process_fifo(); ++ ++ CHECK(vm_read32(ctrl + 4) == g_head, "walker drained the ring (get 0x%X, put 0x%X)", ++ vm_read32(ctrl + 4), g_head); ++ CHECK(written(1), "report before the jumps written"); ++ CHECK(!written(2) && written(3), "old-form JUMP: skipped report %s, landing report %s", ++ written(2) ? "written" : "not written", written(3) ? "written" : "not written"); ++ CHECK(!written(4) && written(5), "new-form JUMP: skipped report %s, landing report %s", ++ written(4) ? "written" : "not written", written(5) ? "written" : "not written"); ++ ++ printf("[gcm_fifo_jump] %s (%d failed)\n", g_fail ? "FAIL" : "PASS", g_fail); ++ free(vm_base); ++ return g_fail ? 1 : 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-675/tests/test.sh b/tasks/sp00nznet__ps3recomp-675/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-675/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-675/tests/verifier.py b/tasks/sp00nznet__ps3recomp-675/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-675/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-676/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-676/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-676/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-676/instruction.md b/tasks/sp00nznet__ps3recomp-676/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cd32966d02f78858a0ea8fe9143edcefdefae87e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-676/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** gcm: print tile and zcull call lines only in verbose mode + +## Description + +## What +`cellGcmSetTile`, `cellGcmSetZcull`, `cellGcmBindTile`, `cellGcmBindZcull`, `cellGcmUnbindTile` and `cellGcmUnbindZcull` always printed a line. Other per-call lines in the runtime (`[WAIT]`, `[spurs-job]`, the null backend's) are gated on `ps3_log_verbose()`. These six now are too. + +## Why +A title that rebinds tiles every frame (about 8 calls a frame on its main thread in the case I saw) pays an unbuffered stdout write per call. Under Proton on Linux that cost 0.2-0.7 ms each, inside the frame that has to finish before the next vblank. It also floods the log. The runtime is verbose by default whenever stderr is not a terminal, so many launchers hit this. + +## How +- Each `printf` is wrapped in `if (ps3_log_verbose())`. +- `cellGcmSys.c` includes `runtime/ps3_log.h`. +- State changes and return values are untouched. + +## Testing +- New test `tests/gcm_tile_log`: two ctest entries, `gcm_tile_log_quiet` (PS3_VERBOSE=0, expects no output) and `gcm_tile_log_verbose` (PS3_VERBOSE=1, expects 6 lines). Each is its own process because `ps3_log_verbose()` reads the variable once. +- On master `gcm_tile_log_quiet` fails: `[FAIL] PS3_VERBOSE=0: 6 lines for six calls (want 0)`. On this branch both pass. +- Linux, gcc: `ctest -R gcm_tile_log`. +- Under Proton on Linux, a 25 s title-screen run on the same build: + +| Setting | Frame rate | Log lines | +|---|---|---| +| `PS3_VERBOSE=0` | 27.5 fps | 2,587 | +| `PS3_VERBOSE=1` | 26.2 fps | 74,272 | + +## Risk +Very low: only log output changes. Anyone who relied on these lines in default logs must now set `PS3_VERBOSE=1`. + +## Overlap +- Open PRs that touch `libs/video/cellGcmSys.c` (#673, #660, #657, #654, #653, #652, #651, #650, #648, #647) apply cleanly on top of this one. +- `CMakeLists.txt`: the new test entry sits next to #650's (line 402); whichever lands second needs a one-line rebase there. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-676/solution/patch.diff b/tasks/sp00nznet__ps3recomp-676/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cdb61034222cf0de698e85b575e37bd2bc62a633 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-676/solution/patch.diff @@ -0,0 +1,198 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..29fd7465 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -401,6 +401,8 @@ if(PS3RECOMP_BUILD_TESTS) + # each report DMA context. Links the runtime like the POSIX host below. + if(UNIX) + add_subdirectory(tests/gcm_reports) ++ # The per-call tile and zcull log lines, gated on PS3_VERBOSE. ++ add_subdirectory(tests/gcm_tile_log) + endif() + # PS3_LOG_FIRST, the saturating counter behind the "first n times" log lines. + add_executable(test_log_first tests/test_log_first.c) +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..cf0b27ce 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -27,6 +27,7 @@ static u32 s_gcm_context_ea = 0; + #include <stdlib.h> + #include <stdint.h> + #include "ps3emu/log_first.h" ++#include "../../runtime/ps3_log.h" /* ps3_log_verbose: the per-call tile/zcull lines */ + + #ifdef _WIN32 + #include <windows.h> +@@ -3783,8 +3784,9 @@ s32 cellGcmSetTile(u8 index, u8 location, u32 offset, u32 size, + if (index >= CELL_GCM_MAX_TILE_COUNT) + return CELL_GCM_ERROR_INVALID_VALUE; + +- printf("[cellGcmSys] SetTile(index=%u, loc=%u, offset=0x%X, size=0x%X, pitch=%u)\n", +- index, location, offset, size, pitch); ++ if (ps3_log_verbose()) ++ printf("[cellGcmSys] SetTile(index=%u, loc=%u, offset=0x%X, size=0x%X, pitch=%u)\n", ++ index, location, offset, size, pitch); + + s_tiles[index].offset = offset; + s_tiles[index].size = size; +@@ -3810,8 +3812,9 @@ s32 cellGcmSetZcull(u8 index, u32 offset, u32 width, u32 height, + if (index >= CELL_GCM_MAX_ZCULL_COUNT) + return CELL_GCM_ERROR_INVALID_VALUE; + +- printf("[cellGcmSys] SetZcull(index=%u, offset=0x%X, %ux%u)\n", +- index, offset, width, height); ++ if (ps3_log_verbose()) ++ printf("[cellGcmSys] SetZcull(index=%u, offset=0x%X, %ux%u)\n", ++ index, offset, width, height); + + s_zcull[index].offset = offset; + s_zcull[index].width = width; +@@ -3835,7 +3838,7 @@ s32 cellGcmBindTile(u8 index) + if (index >= CELL_GCM_MAX_TILE_COUNT) + return CELL_GCM_ERROR_INVALID_VALUE; + +- printf("[cellGcmSys] BindTile(index=%u)\n", index); ++ if (ps3_log_verbose()) printf("[cellGcmSys] BindTile(index=%u)\n", index); + s_tiles[index].bound = 1; + return CELL_OK; + } +@@ -3846,7 +3849,7 @@ s32 cellGcmBindZcull(u8 index) + if (index >= CELL_GCM_MAX_ZCULL_COUNT) + return CELL_GCM_ERROR_INVALID_VALUE; + +- printf("[cellGcmSys] BindZcull(index=%u)\n", index); ++ if (ps3_log_verbose()) printf("[cellGcmSys] BindZcull(index=%u)\n", index); + s_zcull[index].bound = 1; + return CELL_OK; + } +@@ -3857,7 +3860,7 @@ s32 cellGcmUnbindTile(u8 index) + if (index >= CELL_GCM_MAX_TILE_COUNT) + return CELL_GCM_ERROR_INVALID_VALUE; + +- printf("[cellGcmSys] UnbindTile(index=%u)\n", index); ++ if (ps3_log_verbose()) printf("[cellGcmSys] UnbindTile(index=%u)\n", index); + s_tiles[index].bound = 0; + return CELL_OK; + } +@@ -3868,7 +3871,7 @@ s32 cellGcmUnbindZcull(u8 index) + if (index >= CELL_GCM_MAX_ZCULL_COUNT) + return CELL_GCM_ERROR_INVALID_VALUE; + +- printf("[cellGcmSys] UnbindZcull(index=%u)\n", index); ++ if (ps3_log_verbose()) printf("[cellGcmSys] UnbindZcull(index=%u)\n", index); + s_zcull[index].bound = 0; + return CELL_OK; + } +diff --git a/tests/gcm_tile_log/CMakeLists.txt b/tests/gcm_tile_log/CMakeLists.txt +new file mode 100644 +index 00000000..d07dfa73 +--- /dev/null ++++ b/tests/gcm_tile_log/CMakeLists.txt +@@ -0,0 +1,26 @@ ++# ps3recomp - tests/gcm_tile_log ++# ++# The per-call lines of cellGcmSetTile / SetZcull / BindTile / BindZcull / ++# UnbindTile / UnbindZcull are printed only when ps3_log_verbose() is on. ++# Built with the runtime (PS3RECOMP_BUILD_TESTS). ++# ++# ctest --test-dir build-tests -R gcm_tile_log --output-on-failure ++ ++add_executable(test_gcm_tile_log ++ main.c ++ "${PROJECT_SOURCE_DIR}/runtime/host/host_stubs.c" ++) ++target_link_libraries(test_gcm_tile_log PRIVATE ps3recomp_runtime) ++if(NOT WIN32) ++ target_link_libraries(test_gcm_tile_log PRIVATE m) ++endif() ++target_include_directories(test_gcm_tile_log PRIVATE ++ "${PROJECT_SOURCE_DIR}/libs/video" ++ "${PROJECT_SOURCE_DIR}/include" ++ "${PROJECT_SOURCE_DIR}/runtime" ++) ++# The runtime carries C++, so the C++ driver does the final link. ++set_target_properties(test_gcm_tile_log PROPERTIES LINKER_LANGUAGE CXX) ++# ps3_log_verbose() reads PS3_VERBOSE once, so each setting is its own process. ++add_test(NAME gcm_tile_log_quiet COMMAND test_gcm_tile_log quiet) ++add_test(NAME gcm_tile_log_verbose COMMAND test_gcm_tile_log verbose) +diff --git a/tests/gcm_tile_log/main.c b/tests/gcm_tile_log/main.c +new file mode 100644 +index 00000000..f1b8c237 +--- /dev/null ++++ b/tests/gcm_tile_log/main.c +@@ -0,0 +1,75 @@ ++/* ++ * ps3recomp - tests/gcm_tile_log ++ * ++ * cellGcmSetTile, SetZcull, BindTile, BindZcull, UnbindTile and UnbindZcull ++ * print a line per call only when ps3_log_verbose() is on (PS3_VERBOSE=1). ++ * stdout is redirected to a file around the six calls and read back. ++ * ++ * test_gcm_tile_log quiet PS3_VERBOSE=0: no output, every call returns CELL_OK ++ * test_gcm_tile_log verbose PS3_VERBOSE=1: one line per call ++ * ++ * Exit code 0 when every check passes. ++ */ ++#include "cellGcmSys.h" ++#include <stdint.h> ++#include <stdio.h> ++#include <stdlib.h> ++#include <string.h> ++#ifdef _WIN32 ++#include <io.h> ++#define dup _dup ++#define dup2 _dup2 ++#define close _close ++#define fileno _fileno ++#else ++#include <unistd.h> ++#endif ++ ++uint8_t* vm_base = NULL; ++ ++static int g_fail; ++#define CHECK(c, ...) do { if (c) printf("[PASS] " __VA_ARGS__); \ ++ else { g_fail++; printf("[FAIL] " __VA_ARGS__); } printf("\n"); } while (0) ++ ++int main(int argc, char** argv) ++{ ++ const int want_lines = argc > 1 && !strcmp(argv[1], "verbose"); ++ if (argc < 2 || (!want_lines && strcmp(argv[1], "quiet"))) { ++ fprintf(stderr, "usage: %s quiet|verbose\n", argv[0]); ++ return 2; ++ } ++ setenv("PS3_VERBOSE", want_lines ? "1" : "0", 1); ++ setvbuf(stdout, NULL, _IONBF, 0); ++ ++ FILE* cap = tmpfile(); ++ if (!cap) { printf("[FAIL] tmpfile\n"); return 1; } ++ fflush(stdout); ++ const int saved = dup(fileno(stdout)); ++ dup2(fileno(cap), fileno(stdout)); ++ ++ s32 rc[6]; ++ rc[0] = cellGcmSetTile(1, 0, 0x100000, 0x100000, 0x400, 0, 0, 0); ++ rc[1] = cellGcmSetZcull(1, 0x200000, 1280, 720, 0, 0, 0, 0, 0, 0, 0, 0); ++ rc[2] = cellGcmBindTile(1); ++ rc[3] = cellGcmBindZcull(1); ++ rc[4] = cellGcmUnbindTile(1); ++ rc[5] = cellGcmUnbindZcull(1); ++ ++ fflush(stdout); ++ dup2(saved, fileno(stdout)); ++ close(saved); ++ ++ int lines = 0, c; ++ rewind(cap); ++ while ((c = fgetc(cap)) != EOF) if (c == '\n') lines++; ++ fclose(cap); ++ ++ int ok = 1; ++ for (int i = 0; i < 6; i++) ok &= (rc[i] == CELL_OK); ++ CHECK(ok, "all six calls return CELL_OK"); ++ if (want_lines) CHECK(lines == 6, "PS3_VERBOSE=1: %d lines for six calls (want 6)", lines); ++ else CHECK(lines == 0, "PS3_VERBOSE=0: %d lines for six calls (want 0)", lines); ++ ++ printf("[gcm_tile_log %s] %s (%d failed)\n", argv[1], g_fail ? "FAIL" : "PASS", g_fail); ++ return g_fail ? 1 : 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-676/solution/solve.sh b/tasks/sp00nznet__ps3recomp-676/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-676/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-676/task.toml b/tasks/sp00nznet__ps3recomp-676/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0cd2b6980017b9ee0369b6ffd6f78b1a2bdf5635 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-676/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-676" +description = "gcm: print tile and zcull call lines only in verbose mode" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/676" +source_access = "auto" +built_at = "2026-11-16T16:09:59.726025+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8b31277db3ba52c284ebbb1c255d3511bd361d4bda99dc0cc6b4079936ba52e9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "CMakeLists.txt", + "libs/video/cellGcmSys.c", + "tests/gcm_tile_log/CMakeLists.txt", + "tests/gcm_tile_log/main.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 122 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.152029+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-676/tests/capture.py b/tasks/sp00nznet__ps3recomp-676/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-676/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-676/tests/instruction.md b/tasks/sp00nznet__ps3recomp-676/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cd32966d02f78858a0ea8fe9143edcefdefae87e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-676/tests/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** gcm: print tile and zcull call lines only in verbose mode + +## Description + +## What +`cellGcmSetTile`, `cellGcmSetZcull`, `cellGcmBindTile`, `cellGcmBindZcull`, `cellGcmUnbindTile` and `cellGcmUnbindZcull` always printed a line. Other per-call lines in the runtime (`[WAIT]`, `[spurs-job]`, the null backend's) are gated on `ps3_log_verbose()`. These six now are too. + +## Why +A title that rebinds tiles every frame (about 8 calls a frame on its main thread in the case I saw) pays an unbuffered stdout write per call. Under Proton on Linux that cost 0.2-0.7 ms each, inside the frame that has to finish before the next vblank. It also floods the log. The runtime is verbose by default whenever stderr is not a terminal, so many launchers hit this. + +## How +- Each `printf` is wrapped in `if (ps3_log_verbose())`. +- `cellGcmSys.c` includes `runtime/ps3_log.h`. +- State changes and return values are untouched. + +## Testing +- New test `tests/gcm_tile_log`: two ctest entries, `gcm_tile_log_quiet` (PS3_VERBOSE=0, expects no output) and `gcm_tile_log_verbose` (PS3_VERBOSE=1, expects 6 lines). Each is its own process because `ps3_log_verbose()` reads the variable once. +- On master `gcm_tile_log_quiet` fails: `[FAIL] PS3_VERBOSE=0: 6 lines for six calls (want 0)`. On this branch both pass. +- Linux, gcc: `ctest -R gcm_tile_log`. +- Under Proton on Linux, a 25 s title-screen run on the same build: + +| Setting | Frame rate | Log lines | +|---|---|---| +| `PS3_VERBOSE=0` | 27.5 fps | 2,587 | +| `PS3_VERBOSE=1` | 26.2 fps | 74,272 | + +## Risk +Very low: only log output changes. Anyone who relied on these lines in default logs must now set `PS3_VERBOSE=1`. + +## Overlap +- Open PRs that touch `libs/video/cellGcmSys.c` (#673, #660, #657, #654, #653, #652, #651, #650, #648, #647) apply cleanly on top of this one. +- `CMakeLists.txt`: the new test entry sits next to #650's (line 402); whichever lands second needs a one-line rebase there. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-676/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-676/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cdb61034222cf0de698e85b575e37bd2bc62a633 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-676/tests/oracle.patch @@ -0,0 +1,198 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..29fd7465 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -401,6 +401,8 @@ if(PS3RECOMP_BUILD_TESTS) + # each report DMA context. Links the runtime like the POSIX host below. + if(UNIX) + add_subdirectory(tests/gcm_reports) ++ # The per-call tile and zcull log lines, gated on PS3_VERBOSE. ++ add_subdirectory(tests/gcm_tile_log) + endif() + # PS3_LOG_FIRST, the saturating counter behind the "first n times" log lines. + add_executable(test_log_first tests/test_log_first.c) +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..cf0b27ce 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -27,6 +27,7 @@ static u32 s_gcm_context_ea = 0; + #include <stdlib.h> + #include <stdint.h> + #include "ps3emu/log_first.h" ++#include "../../runtime/ps3_log.h" /* ps3_log_verbose: the per-call tile/zcull lines */ + + #ifdef _WIN32 + #include <windows.h> +@@ -3783,8 +3784,9 @@ s32 cellGcmSetTile(u8 index, u8 location, u32 offset, u32 size, + if (index >= CELL_GCM_MAX_TILE_COUNT) + return CELL_GCM_ERROR_INVALID_VALUE; + +- printf("[cellGcmSys] SetTile(index=%u, loc=%u, offset=0x%X, size=0x%X, pitch=%u)\n", +- index, location, offset, size, pitch); ++ if (ps3_log_verbose()) ++ printf("[cellGcmSys] SetTile(index=%u, loc=%u, offset=0x%X, size=0x%X, pitch=%u)\n", ++ index, location, offset, size, pitch); + + s_tiles[index].offset = offset; + s_tiles[index].size = size; +@@ -3810,8 +3812,9 @@ s32 cellGcmSetZcull(u8 index, u32 offset, u32 width, u32 height, + if (index >= CELL_GCM_MAX_ZCULL_COUNT) + return CELL_GCM_ERROR_INVALID_VALUE; + +- printf("[cellGcmSys] SetZcull(index=%u, offset=0x%X, %ux%u)\n", +- index, offset, width, height); ++ if (ps3_log_verbose()) ++ printf("[cellGcmSys] SetZcull(index=%u, offset=0x%X, %ux%u)\n", ++ index, offset, width, height); + + s_zcull[index].offset = offset; + s_zcull[index].width = width; +@@ -3835,7 +3838,7 @@ s32 cellGcmBindTile(u8 index) + if (index >= CELL_GCM_MAX_TILE_COUNT) + return CELL_GCM_ERROR_INVALID_VALUE; + +- printf("[cellGcmSys] BindTile(index=%u)\n", index); ++ if (ps3_log_verbose()) printf("[cellGcmSys] BindTile(index=%u)\n", index); + s_tiles[index].bound = 1; + return CELL_OK; + } +@@ -3846,7 +3849,7 @@ s32 cellGcmBindZcull(u8 index) + if (index >= CELL_GCM_MAX_ZCULL_COUNT) + return CELL_GCM_ERROR_INVALID_VALUE; + +- printf("[cellGcmSys] BindZcull(index=%u)\n", index); ++ if (ps3_log_verbose()) printf("[cellGcmSys] BindZcull(index=%u)\n", index); + s_zcull[index].bound = 1; + return CELL_OK; + } +@@ -3857,7 +3860,7 @@ s32 cellGcmUnbindTile(u8 index) + if (index >= CELL_GCM_MAX_TILE_COUNT) + return CELL_GCM_ERROR_INVALID_VALUE; + +- printf("[cellGcmSys] UnbindTile(index=%u)\n", index); ++ if (ps3_log_verbose()) printf("[cellGcmSys] UnbindTile(index=%u)\n", index); + s_tiles[index].bound = 0; + return CELL_OK; + } +@@ -3868,7 +3871,7 @@ s32 cellGcmUnbindZcull(u8 index) + if (index >= CELL_GCM_MAX_ZCULL_COUNT) + return CELL_GCM_ERROR_INVALID_VALUE; + +- printf("[cellGcmSys] UnbindZcull(index=%u)\n", index); ++ if (ps3_log_verbose()) printf("[cellGcmSys] UnbindZcull(index=%u)\n", index); + s_zcull[index].bound = 0; + return CELL_OK; + } +diff --git a/tests/gcm_tile_log/CMakeLists.txt b/tests/gcm_tile_log/CMakeLists.txt +new file mode 100644 +index 00000000..d07dfa73 +--- /dev/null ++++ b/tests/gcm_tile_log/CMakeLists.txt +@@ -0,0 +1,26 @@ ++# ps3recomp - tests/gcm_tile_log ++# ++# The per-call lines of cellGcmSetTile / SetZcull / BindTile / BindZcull / ++# UnbindTile / UnbindZcull are printed only when ps3_log_verbose() is on. ++# Built with the runtime (PS3RECOMP_BUILD_TESTS). ++# ++# ctest --test-dir build-tests -R gcm_tile_log --output-on-failure ++ ++add_executable(test_gcm_tile_log ++ main.c ++ "${PROJECT_SOURCE_DIR}/runtime/host/host_stubs.c" ++) ++target_link_libraries(test_gcm_tile_log PRIVATE ps3recomp_runtime) ++if(NOT WIN32) ++ target_link_libraries(test_gcm_tile_log PRIVATE m) ++endif() ++target_include_directories(test_gcm_tile_log PRIVATE ++ "${PROJECT_SOURCE_DIR}/libs/video" ++ "${PROJECT_SOURCE_DIR}/include" ++ "${PROJECT_SOURCE_DIR}/runtime" ++) ++# The runtime carries C++, so the C++ driver does the final link. ++set_target_properties(test_gcm_tile_log PROPERTIES LINKER_LANGUAGE CXX) ++# ps3_log_verbose() reads PS3_VERBOSE once, so each setting is its own process. ++add_test(NAME gcm_tile_log_quiet COMMAND test_gcm_tile_log quiet) ++add_test(NAME gcm_tile_log_verbose COMMAND test_gcm_tile_log verbose) +diff --git a/tests/gcm_tile_log/main.c b/tests/gcm_tile_log/main.c +new file mode 100644 +index 00000000..f1b8c237 +--- /dev/null ++++ b/tests/gcm_tile_log/main.c +@@ -0,0 +1,75 @@ ++/* ++ * ps3recomp - tests/gcm_tile_log ++ * ++ * cellGcmSetTile, SetZcull, BindTile, BindZcull, UnbindTile and UnbindZcull ++ * print a line per call only when ps3_log_verbose() is on (PS3_VERBOSE=1). ++ * stdout is redirected to a file around the six calls and read back. ++ * ++ * test_gcm_tile_log quiet PS3_VERBOSE=0: no output, every call returns CELL_OK ++ * test_gcm_tile_log verbose PS3_VERBOSE=1: one line per call ++ * ++ * Exit code 0 when every check passes. ++ */ ++#include "cellGcmSys.h" ++#include <stdint.h> ++#include <stdio.h> ++#include <stdlib.h> ++#include <string.h> ++#ifdef _WIN32 ++#include <io.h> ++#define dup _dup ++#define dup2 _dup2 ++#define close _close ++#define fileno _fileno ++#else ++#include <unistd.h> ++#endif ++ ++uint8_t* vm_base = NULL; ++ ++static int g_fail; ++#define CHECK(c, ...) do { if (c) printf("[PASS] " __VA_ARGS__); \ ++ else { g_fail++; printf("[FAIL] " __VA_ARGS__); } printf("\n"); } while (0) ++ ++int main(int argc, char** argv) ++{ ++ const int want_lines = argc > 1 && !strcmp(argv[1], "verbose"); ++ if (argc < 2 || (!want_lines && strcmp(argv[1], "quiet"))) { ++ fprintf(stderr, "usage: %s quiet|verbose\n", argv[0]); ++ return 2; ++ } ++ setenv("PS3_VERBOSE", want_lines ? "1" : "0", 1); ++ setvbuf(stdout, NULL, _IONBF, 0); ++ ++ FILE* cap = tmpfile(); ++ if (!cap) { printf("[FAIL] tmpfile\n"); return 1; } ++ fflush(stdout); ++ const int saved = dup(fileno(stdout)); ++ dup2(fileno(cap), fileno(stdout)); ++ ++ s32 rc[6]; ++ rc[0] = cellGcmSetTile(1, 0, 0x100000, 0x100000, 0x400, 0, 0, 0); ++ rc[1] = cellGcmSetZcull(1, 0x200000, 1280, 720, 0, 0, 0, 0, 0, 0, 0, 0); ++ rc[2] = cellGcmBindTile(1); ++ rc[3] = cellGcmBindZcull(1); ++ rc[4] = cellGcmUnbindTile(1); ++ rc[5] = cellGcmUnbindZcull(1); ++ ++ fflush(stdout); ++ dup2(saved, fileno(stdout)); ++ close(saved); ++ ++ int lines = 0, c; ++ rewind(cap); ++ while ((c = fgetc(cap)) != EOF) if (c == '\n') lines++; ++ fclose(cap); ++ ++ int ok = 1; ++ for (int i = 0; i < 6; i++) ok &= (rc[i] == CELL_OK); ++ CHECK(ok, "all six calls return CELL_OK"); ++ if (want_lines) CHECK(lines == 6, "PS3_VERBOSE=1: %d lines for six calls (want 6)", lines); ++ else CHECK(lines == 0, "PS3_VERBOSE=0: %d lines for six calls (want 0)", lines); ++ ++ printf("[gcm_tile_log %s] %s (%d failed)\n", argv[1], g_fail ? "FAIL" : "PASS", g_fail); ++ return g_fail ? 1 : 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-676/tests/test.sh b/tasks/sp00nznet__ps3recomp-676/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-676/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-676/tests/verifier.py b/tasks/sp00nznet__ps3recomp-676/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-676/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-677/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-677/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-677/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-677/instruction.md b/tasks/sp00nznet__ps3recomp-677/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36d75323829a3c40461a8064ab11e470fd276e5e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-677/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** perf(spu): NEON fi and cflts on ARM64 + +## Description + +On ARM64, `spu_fi` (the frest/frsqest Newton step) and `spu_cflts` fall through to per-lane scalar references. They are too large to inline, so lifted float code calls them out of line and spills vector registers. This adds NEON forms next to the AVX2 forms from #500: + +- `fi` splits the 33-bit magnitude on the low-word borrow. +- `cflts` with scales 0–127 multiplies by 2^scale and uses FCVTZS saturation, patching exponent-0 and exponent-255 lanes. Other scales keep the reference. + +All other helpers keep their references; x86 is untouched. + +Test evidence: + +- New `runtime/spu/tests/test_spu_fi_cflts_neon.c` (CTest `spu_fi_cflts_neon`): 5,600,000 vectors, 0 mismatches, under both the default FPCR and round-toward-zero + flush-to-zero (`SPU_FLOAT_RZ`), covering every exponent, fi's borrow edge and all cflts scales. A deliberately broken variant (fraction shift 8→7) produces 71,738 mismatches. +- `-DSPU_SCALAR_HELPERS` build passes; `test_spu_float_exact` passes; `ps3recomp_runtime` builds. +- Synthetic throughput (4,096 random normal-exponent vectors, fi then cflts): about 2.5× faster, 2.2 vs 5.3 ns/vector on an M-series host. When every lane is zero the scalar reference is faster, since the NEON path has no early-out. + +Based on master `4e8f3ca8` (v0.18.0); no dependency on another PR. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-677/solution/patch.diff b/tasks/sp00nznet__ps3recomp-677/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b7a0c143db6ebe34ba6cf7aa97a0db35edefd563 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-677/solution/patch.diff @@ -0,0 +1,158 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..18e6aece 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -417,6 +417,16 @@ if(PS3RECOMP_BUILD_TESTS) + add_test(NAME spu_float_exact COMMAND test_spu_float_exact) + set_tests_properties(spu_float_exact PROPERTIES TIMEOUT 300) + ++ # fi and cflts (NEON on ARM64) against their scalar references, in the ++ # default FPCR and under round-toward-zero plus flush-to-zero. ++ add_executable(test_spu_fi_cflts_neon ++ runtime/spu/tests/test_spu_fi_cflts_neon.c) ++ target_include_directories(test_spu_fi_cflts_neon PRIVATE include runtime/spu) ++ target_compile_options(test_spu_fi_cflts_neon PRIVATE -UNDEBUG) ++ target_link_libraries(test_spu_fi_cflts_neon PRIVATE m) ++ add_test(NAME spu_fi_cflts_neon COMMAND test_spu_fi_cflts_neon) ++ set_tests_properties(spu_fi_cflts_neon PROPERTIES TIMEOUT 300) ++ + add_executable(test_spu_lockline_wait + runtime/spu/tests/test_spu_lockline_wait.c) + target_include_directories(test_spu_lockline_wait PRIVATE include) +diff --git a/runtime/spu/spu_helpers.h b/runtime/spu/spu_helpers.h +index f04fda63..23039b0e 100644 +--- a/runtime/spu/spu_helpers.h ++++ b/runtime/spu/spu_helpers.h +@@ -1673,6 +1673,53 @@ SPU__XE_INLINE u128 spu_cuflt(u128 a, int i8) { + const __m128i nz = _mm_xor_si128(_mm_cmpeq_epi32(v, _mm_setzero_si128()), _mm_set1_epi32(-1)); + return spu__xe_st(spu__xe_cxflt(d, _mm_setzero_si128(), nz, i8)); + } ++#elif defined(__aarch64__) && defined(__ARM_NEON) && !defined(SPU_SCALAR_HELPERS) ++#include <arm_neon.h> ++/* fi and cflts four lanes at a time on ARM64 (the others keep their references). ++ * test_spu_float_est.c checks both against the scalar references. ++ * ++ * fi: the reference's arithmetic in 32-bit lanes. (2^13 + base) * 2^19 is 2^32 plus ++ * u0 = base << 19, so with t = step * y (< 2^29) the magnitude is 2^32 + d, d = u0 - t. ++ * Without a borrow (d >= 0) the fraction is d >> 9; with one, u = d mod 2^32 lies in ++ * [2^32 - 2^29, 2^32), the value is normalised by one shift and the fraction is ++ * (u >> 8) & 0x7FFFFF, one exponent lower. */ ++static inline u128 spu_fi(u128 a, u128 b) { ++ uint32x4_t est, av; memcpy(&est, &b, 16); memcpy(&av, &a, 16); ++ const uint32x4_t exp = vandq_u32(vshrq_n_u32(est, 23), vdupq_n_u32(0xFFu)); ++ const uint32x4_t u0 = vshlq_n_u32(vandq_u32(vshrq_n_u32(est, 10), vdupq_n_u32(0x1FFFu)), 19); ++ const uint32x4_t t = vmulq_u32(vandq_u32(est, vdupq_n_u32(0x3FFu)), vandq_u32(av, vdupq_n_u32(0x7FFFFu))); ++ const uint32x4_t u = vsubq_u32(u0, t); ++ const uint32x4_t brw = vcltq_u32(u0, t); ++ const uint32x4_t frac = vbslq_u32(brw, vandq_u32(vshrq_n_u32(u, 8), vdupq_n_u32(0x7FFFFFu)), vshrq_n_u32(u, 9)); ++ const uint32x4_t e2 = vaddq_u32(exp, brw); /* a borrow lowers it by one */ ++ uint32x4_t r = vorrq_u32(vorrq_u32(vandq_u32(est, vdupq_n_u32(0x80000000u)), vshlq_n_u32(e2, 23)), frac); ++ r = vbicq_u32(r, vorrq_u32(vceqzq_u32(exp), vceqzq_u32(e2))); /* zero operand, underflow: +0 */ ++ u128 out; memcpy(&out, &r, 16); return out; ++} ++static inline u128 spu_frest(u128 a) { return spu_frest_ref(a); } ++static inline u128 spu_frsqest(u128 a) { return spu_frsqest_ref(a); } ++/* cflts, scales 0..127: scaling by 2^scale is exact or overflows (an infinity, or ++ * FLT_MAX under round-toward-zero, both of which FCVTZS saturates like the SPU), and an ++ * underflow truncates to 0 either way. FCVTZS truncates toward zero and saturates ++ * exactly as cflts does. Exponent 0 is an SPU zero and exponent 255 an ordinary huge ++ * value, so those lanes are patched to 0 and to the saturated bound of their sign. ++ * Other scales use the reference. */ ++static inline u128 spu_cflts(u128 a, int i8) { ++ const int scale = 173 - (i8 & 0xFF); ++ if (scale < 0 || scale > 127) return spu_cflts_ref(a, i8); ++ uint32x4_t x; memcpy(&x, &a, 16); ++ const float32x4_t f = vmulq_f32(vreinterpretq_f32_u32(x), ++ vreinterpretq_f32_u32(vdupq_n_u32((uint32_t)(scale + 127) << 23))); ++ uint32x4_t r = vreinterpretq_u32_s32(vcvtq_s32_f32(f)); ++ const uint32x4_t e = vandq_u32(vshrq_n_u32(x, 23), vdupq_n_u32(0xFFu)); ++ const uint32x4_t sat = vaddq_u32(vshrq_n_u32(x, 31), vdupq_n_u32(0x7FFFFFFFu)); ++ r = vbslq_u32(vceqq_u32(e, vdupq_n_u32(0xFFu)), sat, r); ++ r = vbicq_u32(r, vceqzq_u32(e)); ++ u128 out; memcpy(&out, &r, 16); return out; ++} ++static inline u128 spu_cfltu(u128 a, int i8) { return spu_cfltu_ref(a, i8); } ++static inline u128 spu_csflt(u128 a, int i8) { return spu_csflt_ref(a, i8); } ++static inline u128 spu_cuflt(u128 a, int i8) { return spu_cuflt_ref(a, i8); } + #else + static inline u128 spu_fi(u128 a, u128 b) { return spu_fi_ref(a, b); } + static inline u128 spu_frest(u128 a) { return spu_frest_ref(a); } +diff --git a/runtime/spu/tests/test_spu_fi_cflts_neon.c b/runtime/spu/tests/test_spu_fi_cflts_neon.c +new file mode 100644 +index 00000000..d7c9dda4 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_fi_cflts_neon.c +@@ -0,0 +1,73 @@ ++/* ++ * The NEON spu_fi and spu_cflts against their scalar references ++ * (spu_fi_ref, spu_cflts_ref in spu_helpers.h), lane for lane. ++ * ++ * Inputs: every exponent and sign with random fractions, the borrow edge of ++ * fi (step * y around base << 19), zero and exponent-255 lanes, and every ++ * cflts scale. Run once in the default FPCR and once with round-toward-zero ++ * plus flush-to-zero, the mode SPU_FLOAT_RZ runs lifted code in. ++ * ++ * Build: ++ * clang -std=gnu17 -O2 -I include -I runtime/spu \ ++ * -o /tmp/test_spu_fi_cflts_neon runtime/spu/tests/test_spu_fi_cflts_neon.c ++ */ ++#include "spu_helpers.h" ++#include <stdio.h> ++#include <stdlib.h> ++ ++static uint64_t s_rng = 0x9E3779B97F4A7C15ull; ++static uint32_t rnd(void) { s_rng ^= s_rng << 13; s_rng ^= s_rng >> 7; s_rng ^= s_rng << 17; return (uint32_t)s_rng; } ++ ++static unsigned long long g_n, g_bad; ++static void cmp(const char* what, u128 got, u128 want, u128 a, u128 b, int i8) ++{ ++ g_n++; ++ if (!memcmp(&got, &want, 16)) return; ++ if (g_bad++ < 10) ++ fprintf(stderr, "FAIL %s i8=%d a=%08X b=%08X got=%08X want=%08X\n", what, i8, ++ a._u32[0], b._u32[0], got._u32[0], want._u32[0]); ++} ++ ++static uint32_t edge_float(void) ++{ ++ uint32_t r = rnd(); ++ switch (r & 7) { ++ case 0: return r & 0x807FFFFFu; /* exponent 0 */ ++ case 1: return r | 0x7F800000u; /* exponent 255 */ ++ default: return r; ++ } ++} ++ ++static void run(void) ++{ ++ for (int round = 0; round < 400000; ++round) { ++ u128 a, b; ++ for (int i = 0; i < 4; ++i) { a._u32[i] = edge_float(); b._u32[i] = edge_float(); } ++ /* fi near its borrow edge: step * y close to base << 19 */ ++ if (round & 1) for (int i = 0; i < 4; ++i) { ++ uint32_t base = rnd() & 0x1FFFu, step = (rnd() & 0x3FFu) | 1u; ++ uint32_t y = (uint32_t)(((uint64_t)base << 19) / step) + (rnd() % 5) - 2; ++ b._u32[i] = (b._u32[i] & 0xFF800000u) | (base << 10) | step; ++ a._u32[i] = (a._u32[i] & ~0x7FFFFu) | (y & 0x7FFFFu); ++ } ++ cmp("fi", spu_fi(a, b), spu_fi_ref(a, b), a, b, 0); ++ const int i8 = (int)(rnd() & 0xFF); ++ cmp("cflts", spu_cflts(a, i8), spu_cflts_ref(a, i8), a, b, i8); ++ for (int s = 46; s <= 173; s += 31) cmp("cflts", spu_cflts(b, s), spu_cflts_ref(b, s), b, a, s); ++ } ++} ++ ++int main(void) ++{ ++#if defined(__aarch64__) ++ run(); ++ uint64_t fpcr; __asm__ volatile("mrs %0, fpcr" : "=r"(fpcr)); ++ __asm__ volatile("msr fpcr, %0" :: "r"(fpcr | (3ull << 22) | (1ull << 24))); /* RZ + FZ */ ++ run(); ++ __asm__ volatile("msr fpcr, %0" :: "r"(fpcr)); ++#else ++ run(); ++#endif ++ printf("spu_fi/spu_cflts NEON vs reference: %llu vectors, %llu mismatched\n", g_n, g_bad); ++ return g_bad != 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-677/solution/solve.sh b/tasks/sp00nznet__ps3recomp-677/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-677/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-677/task.toml b/tasks/sp00nznet__ps3recomp-677/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bf008250ab7de4b1b54df6372df7358d2f522bf7 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-677/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-677" +description = "perf(spu): NEON fi and cflts on ARM64" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/677" +source_access = "auto" +built_at = "2026-11-16T16:09:59.724356+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:db86350e07945f3059702b801db4abe23a46bfed62be92772f52e7d3b797f6a1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "CMakeLists.txt", + "runtime/spu/spu_helpers.h", + "runtime/spu/tests/test_spu_fi_cflts_neon.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 130 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.152574+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-677/tests/capture.py b/tasks/sp00nznet__ps3recomp-677/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-677/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-677/tests/instruction.md b/tasks/sp00nznet__ps3recomp-677/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36d75323829a3c40461a8064ab11e470fd276e5e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-677/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** perf(spu): NEON fi and cflts on ARM64 + +## Description + +On ARM64, `spu_fi` (the frest/frsqest Newton step) and `spu_cflts` fall through to per-lane scalar references. They are too large to inline, so lifted float code calls them out of line and spills vector registers. This adds NEON forms next to the AVX2 forms from #500: + +- `fi` splits the 33-bit magnitude on the low-word borrow. +- `cflts` with scales 0–127 multiplies by 2^scale and uses FCVTZS saturation, patching exponent-0 and exponent-255 lanes. Other scales keep the reference. + +All other helpers keep their references; x86 is untouched. + +Test evidence: + +- New `runtime/spu/tests/test_spu_fi_cflts_neon.c` (CTest `spu_fi_cflts_neon`): 5,600,000 vectors, 0 mismatches, under both the default FPCR and round-toward-zero + flush-to-zero (`SPU_FLOAT_RZ`), covering every exponent, fi's borrow edge and all cflts scales. A deliberately broken variant (fraction shift 8→7) produces 71,738 mismatches. +- `-DSPU_SCALAR_HELPERS` build passes; `test_spu_float_exact` passes; `ps3recomp_runtime` builds. +- Synthetic throughput (4,096 random normal-exponent vectors, fi then cflts): about 2.5× faster, 2.2 vs 5.3 ns/vector on an M-series host. When every lane is zero the scalar reference is faster, since the NEON path has no early-out. + +Based on master `4e8f3ca8` (v0.18.0); no dependency on another PR. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-677/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-677/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b7a0c143db6ebe34ba6cf7aa97a0db35edefd563 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-677/tests/oracle.patch @@ -0,0 +1,158 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..18e6aece 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -417,6 +417,16 @@ if(PS3RECOMP_BUILD_TESTS) + add_test(NAME spu_float_exact COMMAND test_spu_float_exact) + set_tests_properties(spu_float_exact PROPERTIES TIMEOUT 300) + ++ # fi and cflts (NEON on ARM64) against their scalar references, in the ++ # default FPCR and under round-toward-zero plus flush-to-zero. ++ add_executable(test_spu_fi_cflts_neon ++ runtime/spu/tests/test_spu_fi_cflts_neon.c) ++ target_include_directories(test_spu_fi_cflts_neon PRIVATE include runtime/spu) ++ target_compile_options(test_spu_fi_cflts_neon PRIVATE -UNDEBUG) ++ target_link_libraries(test_spu_fi_cflts_neon PRIVATE m) ++ add_test(NAME spu_fi_cflts_neon COMMAND test_spu_fi_cflts_neon) ++ set_tests_properties(spu_fi_cflts_neon PROPERTIES TIMEOUT 300) ++ + add_executable(test_spu_lockline_wait + runtime/spu/tests/test_spu_lockline_wait.c) + target_include_directories(test_spu_lockline_wait PRIVATE include) +diff --git a/runtime/spu/spu_helpers.h b/runtime/spu/spu_helpers.h +index f04fda63..23039b0e 100644 +--- a/runtime/spu/spu_helpers.h ++++ b/runtime/spu/spu_helpers.h +@@ -1673,6 +1673,53 @@ SPU__XE_INLINE u128 spu_cuflt(u128 a, int i8) { + const __m128i nz = _mm_xor_si128(_mm_cmpeq_epi32(v, _mm_setzero_si128()), _mm_set1_epi32(-1)); + return spu__xe_st(spu__xe_cxflt(d, _mm_setzero_si128(), nz, i8)); + } ++#elif defined(__aarch64__) && defined(__ARM_NEON) && !defined(SPU_SCALAR_HELPERS) ++#include <arm_neon.h> ++/* fi and cflts four lanes at a time on ARM64 (the others keep their references). ++ * test_spu_float_est.c checks both against the scalar references. ++ * ++ * fi: the reference's arithmetic in 32-bit lanes. (2^13 + base) * 2^19 is 2^32 plus ++ * u0 = base << 19, so with t = step * y (< 2^29) the magnitude is 2^32 + d, d = u0 - t. ++ * Without a borrow (d >= 0) the fraction is d >> 9; with one, u = d mod 2^32 lies in ++ * [2^32 - 2^29, 2^32), the value is normalised by one shift and the fraction is ++ * (u >> 8) & 0x7FFFFF, one exponent lower. */ ++static inline u128 spu_fi(u128 a, u128 b) { ++ uint32x4_t est, av; memcpy(&est, &b, 16); memcpy(&av, &a, 16); ++ const uint32x4_t exp = vandq_u32(vshrq_n_u32(est, 23), vdupq_n_u32(0xFFu)); ++ const uint32x4_t u0 = vshlq_n_u32(vandq_u32(vshrq_n_u32(est, 10), vdupq_n_u32(0x1FFFu)), 19); ++ const uint32x4_t t = vmulq_u32(vandq_u32(est, vdupq_n_u32(0x3FFu)), vandq_u32(av, vdupq_n_u32(0x7FFFFu))); ++ const uint32x4_t u = vsubq_u32(u0, t); ++ const uint32x4_t brw = vcltq_u32(u0, t); ++ const uint32x4_t frac = vbslq_u32(brw, vandq_u32(vshrq_n_u32(u, 8), vdupq_n_u32(0x7FFFFFu)), vshrq_n_u32(u, 9)); ++ const uint32x4_t e2 = vaddq_u32(exp, brw); /* a borrow lowers it by one */ ++ uint32x4_t r = vorrq_u32(vorrq_u32(vandq_u32(est, vdupq_n_u32(0x80000000u)), vshlq_n_u32(e2, 23)), frac); ++ r = vbicq_u32(r, vorrq_u32(vceqzq_u32(exp), vceqzq_u32(e2))); /* zero operand, underflow: +0 */ ++ u128 out; memcpy(&out, &r, 16); return out; ++} ++static inline u128 spu_frest(u128 a) { return spu_frest_ref(a); } ++static inline u128 spu_frsqest(u128 a) { return spu_frsqest_ref(a); } ++/* cflts, scales 0..127: scaling by 2^scale is exact or overflows (an infinity, or ++ * FLT_MAX under round-toward-zero, both of which FCVTZS saturates like the SPU), and an ++ * underflow truncates to 0 either way. FCVTZS truncates toward zero and saturates ++ * exactly as cflts does. Exponent 0 is an SPU zero and exponent 255 an ordinary huge ++ * value, so those lanes are patched to 0 and to the saturated bound of their sign. ++ * Other scales use the reference. */ ++static inline u128 spu_cflts(u128 a, int i8) { ++ const int scale = 173 - (i8 & 0xFF); ++ if (scale < 0 || scale > 127) return spu_cflts_ref(a, i8); ++ uint32x4_t x; memcpy(&x, &a, 16); ++ const float32x4_t f = vmulq_f32(vreinterpretq_f32_u32(x), ++ vreinterpretq_f32_u32(vdupq_n_u32((uint32_t)(scale + 127) << 23))); ++ uint32x4_t r = vreinterpretq_u32_s32(vcvtq_s32_f32(f)); ++ const uint32x4_t e = vandq_u32(vshrq_n_u32(x, 23), vdupq_n_u32(0xFFu)); ++ const uint32x4_t sat = vaddq_u32(vshrq_n_u32(x, 31), vdupq_n_u32(0x7FFFFFFFu)); ++ r = vbslq_u32(vceqq_u32(e, vdupq_n_u32(0xFFu)), sat, r); ++ r = vbicq_u32(r, vceqzq_u32(e)); ++ u128 out; memcpy(&out, &r, 16); return out; ++} ++static inline u128 spu_cfltu(u128 a, int i8) { return spu_cfltu_ref(a, i8); } ++static inline u128 spu_csflt(u128 a, int i8) { return spu_csflt_ref(a, i8); } ++static inline u128 spu_cuflt(u128 a, int i8) { return spu_cuflt_ref(a, i8); } + #else + static inline u128 spu_fi(u128 a, u128 b) { return spu_fi_ref(a, b); } + static inline u128 spu_frest(u128 a) { return spu_frest_ref(a); } +diff --git a/runtime/spu/tests/test_spu_fi_cflts_neon.c b/runtime/spu/tests/test_spu_fi_cflts_neon.c +new file mode 100644 +index 00000000..d7c9dda4 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_fi_cflts_neon.c +@@ -0,0 +1,73 @@ ++/* ++ * The NEON spu_fi and spu_cflts against their scalar references ++ * (spu_fi_ref, spu_cflts_ref in spu_helpers.h), lane for lane. ++ * ++ * Inputs: every exponent and sign with random fractions, the borrow edge of ++ * fi (step * y around base << 19), zero and exponent-255 lanes, and every ++ * cflts scale. Run once in the default FPCR and once with round-toward-zero ++ * plus flush-to-zero, the mode SPU_FLOAT_RZ runs lifted code in. ++ * ++ * Build: ++ * clang -std=gnu17 -O2 -I include -I runtime/spu \ ++ * -o /tmp/test_spu_fi_cflts_neon runtime/spu/tests/test_spu_fi_cflts_neon.c ++ */ ++#include "spu_helpers.h" ++#include <stdio.h> ++#include <stdlib.h> ++ ++static uint64_t s_rng = 0x9E3779B97F4A7C15ull; ++static uint32_t rnd(void) { s_rng ^= s_rng << 13; s_rng ^= s_rng >> 7; s_rng ^= s_rng << 17; return (uint32_t)s_rng; } ++ ++static unsigned long long g_n, g_bad; ++static void cmp(const char* what, u128 got, u128 want, u128 a, u128 b, int i8) ++{ ++ g_n++; ++ if (!memcmp(&got, &want, 16)) return; ++ if (g_bad++ < 10) ++ fprintf(stderr, "FAIL %s i8=%d a=%08X b=%08X got=%08X want=%08X\n", what, i8, ++ a._u32[0], b._u32[0], got._u32[0], want._u32[0]); ++} ++ ++static uint32_t edge_float(void) ++{ ++ uint32_t r = rnd(); ++ switch (r & 7) { ++ case 0: return r & 0x807FFFFFu; /* exponent 0 */ ++ case 1: return r | 0x7F800000u; /* exponent 255 */ ++ default: return r; ++ } ++} ++ ++static void run(void) ++{ ++ for (int round = 0; round < 400000; ++round) { ++ u128 a, b; ++ for (int i = 0; i < 4; ++i) { a._u32[i] = edge_float(); b._u32[i] = edge_float(); } ++ /* fi near its borrow edge: step * y close to base << 19 */ ++ if (round & 1) for (int i = 0; i < 4; ++i) { ++ uint32_t base = rnd() & 0x1FFFu, step = (rnd() & 0x3FFu) | 1u; ++ uint32_t y = (uint32_t)(((uint64_t)base << 19) / step) + (rnd() % 5) - 2; ++ b._u32[i] = (b._u32[i] & 0xFF800000u) | (base << 10) | step; ++ a._u32[i] = (a._u32[i] & ~0x7FFFFu) | (y & 0x7FFFFu); ++ } ++ cmp("fi", spu_fi(a, b), spu_fi_ref(a, b), a, b, 0); ++ const int i8 = (int)(rnd() & 0xFF); ++ cmp("cflts", spu_cflts(a, i8), spu_cflts_ref(a, i8), a, b, i8); ++ for (int s = 46; s <= 173; s += 31) cmp("cflts", spu_cflts(b, s), spu_cflts_ref(b, s), b, a, s); ++ } ++} ++ ++int main(void) ++{ ++#if defined(__aarch64__) ++ run(); ++ uint64_t fpcr; __asm__ volatile("mrs %0, fpcr" : "=r"(fpcr)); ++ __asm__ volatile("msr fpcr, %0" :: "r"(fpcr | (3ull << 22) | (1ull << 24))); /* RZ + FZ */ ++ run(); ++ __asm__ volatile("msr fpcr, %0" :: "r"(fpcr)); ++#else ++ run(); ++#endif ++ printf("spu_fi/spu_cflts NEON vs reference: %llu vectors, %llu mismatched\n", g_n, g_bad); ++ return g_bad != 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-677/tests/test.sh b/tasks/sp00nznet__ps3recomp-677/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-677/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-677/tests/verifier.py b/tasks/sp00nznet__ps3recomp-677/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-677/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-678/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-678/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-678/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-678/instruction.md b/tasks/sp00nznet__ps3recomp-678/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7b2a2bea103c85ce9e6c99453f0d80d5fe797c40 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-678/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(build): export the runtime's probed SSE4.1 requirement to consumers + +## Description + +The runtime probes `-msse4.1` and builds itself with it, but the flag is PRIVATE. Game targets that compile lifted SPU code include the same static-inline helpers without it, so on gcc/clang generic x86-64 they silently take the scalar `spu_shufb` and related paths. Making the flag PUBLIC propagates the probed ISA to consumers. Hosts where the probe fails (for example Apple clang on arm64) are unchanged. + +Test: `tools/test_spu_isa_consumer.py` configures a real CMake consumer (a C executable and a C++ object library) against the SDK, asserts `-msse4.1` is present exactly when the probe passed, checks 135,424 shuffle/selector cases, and repeats with the probe forced off. It skips when CMake or Ninja is unavailable. + +```sh +python3 tools/test_spu_isa_consumer.py +``` + +Passes on Apple Silicon (probe false). The meaningful case, gcc/clang on generic x86-64, is covered by hosted Linux CI on this PR. Based on master `4e8f3ca8` (v0.18.0); no dependency on another PR. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-678/solution/patch.diff b/tasks/sp00nznet__ps3recomp-678/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..dbeb8a1125b1ae166e2c936c5f772340d6f9d679 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-678/solution/patch.diff @@ -0,0 +1,187 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..e99d3bbe 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -336,7 +336,9 @@ if(CMAKE_C_COMPILER_ID MATCHES "Clang|GNU") + include(CheckCCompilerFlag) + check_c_compiler_flag(-msse4.1 PS3RECOMP_HAS_MSSE41) + if(PS3RECOMP_HAS_MSSE41) +- target_compile_options(ps3recomp_runtime PRIVATE -msse4.1) ++ # Lifted consumers compile the same static-inline SPU helpers. Export ++ # the runtime's existing ISA requirement so their fast path agrees. ++ target_compile_options(ps3recomp_runtime PUBLIC -msse4.1) + endif() + elseif(MSVC) + # Real cl.exe -- clang-cl reports its id as Clang and is handled above. +diff --git a/runtime/spu/tests/test_spu_isa_consumer.c b/runtime/spu/tests/test_spu_isa_consumer.c +new file mode 100644 +index 00000000..4da08bb2 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_isa_consumer.c +@@ -0,0 +1,72 @@ ++/* Synthetic C/C++ SDK consumer: architectural oracle uses word shifts only, ++ * independently of SPU_W, SIMD intrinsics, and the helper's byte loop. */ ++#ifndef _CRT_SECURE_NO_WARNINGS ++#define _CRT_SECURE_NO_WARNINGS ++#endif ++#include "../spu_helpers.h" ++#include <stdio.h> ++#include <stdlib.h> ++ ++#if defined(_MSC_VER) ++#define CONSUMER_NOINLINE __declspec(noinline) ++#else ++#define CONSUMER_NOINLINE __attribute__((noinline)) ++#endif ++#ifdef __cplusplus ++extern "C" ++#endif ++CONSUMER_NOINLINE u128 spu_consumer_shuffle(u128 a,u128 b,u128 c) { return spu_shufb(a,b,c); } ++static unsigned cases; ++static u32 random_state=0x72BC409Du; ++static u128 cleared(void) { u128 value;memset(&value,0,sizeof(value));return value; } ++static u32 next_word(void) { random_state^=random_state<<13;random_state^=random_state>>17;random_state^=random_state<<5;return random_state; } ++static unsigned byte_at(u128 value,unsigned byte) { return (value._u32[byte/4]>>(24-8*(byte%4)))&255u; } ++static void put_byte(u128* value,unsigned byte,unsigned bits) { ++ const unsigned shift=24-8*(byte%4); ++ value->_u32[byte/4]=(value->_u32[byte/4]&~(255u<<shift))|((bits&255u)<<shift); ++} ++static u128 uniform(unsigned byte) { u128 value=cleared();for(unsigned i=0;i<16;i++)put_byte(&value,i,byte);return value; } ++static void check(u128 a,u128 b,u128 control) { ++ u128 expected=cleared(); ++ for(unsigned i=0;i<16;i++) { ++ const unsigned selector=byte_at(control,i); ++ const unsigned value=selector>=224?128:selector>=192?255:selector>=128?0: ++ (selector&16)?byte_at(b,selector&15):byte_at(a,selector&15); ++ put_byte(&expected,i,value); ++ } ++ u128 got=spu_consumer_shuffle(a,b,control); ++ u128 aa=a,bb=b,cc=control; ++ aa=spu_shufb(aa,b,control);bb=spu_shufb(a,bb,control);cc=spu_shufb(a,b,cc); ++ if(memcmp(&expected,&got,16)||memcmp(&expected,&aa,16)||memcmp(&expected,&bb,16)||memcmp(&expected,&cc,16)) { ++ fprintf(stderr,"SHUFB consumer semantic/alias failure case=%u\n",cases);exit(2); ++ } ++ ++cases; ++} ++int main(void) { ++ int sse41=0,ssse3=0; ++#if defined(__SSE4_1__) ++ sse41=1; ++#endif ++#if defined(__SSSE3__) ++ ssse3=1; ++#endif ++ u128 a=cleared(),b=cleared(),c=cleared(); ++ for(unsigned i=0;i<16;i++){put_byte(&a,i,i+1);put_byte(&b,i,i+65);put_byte(&c,i,i);} ++ for(unsigned selector=0;selector<256;selector++) { ++ check(a,b,uniform(selector)); ++ for(unsigned lane=0;lane<16;lane++){u128 mixed=c;put_byte(&mixed,lane,selector);check(a,b,mixed);} ++ } ++ for(unsigned bit=0;bit<128;bit++)for(unsigned selector=0;selector<256;selector++) { ++ u128 value=cleared(),zero=cleared();value._u32[bit/32]=1u<<(bit%32); ++ check(value,zero,uniform(selector));check(zero,value,uniform(selector)); ++ } ++ for(unsigned iteration=0;iteration<16384;iteration++) { ++ for(unsigned word=0;word<4;word++){a._u32[word]=next_word();b._u32[word]=next_word();c._u32[word]=next_word();} ++ check(a,b,c);check(a,a,c);check(a,b,a);check(a,b,b); ++ } ++ printf("SPU consumer semantics PASS cases=%u SSE4.1=%d SSSE3=%d\n",cases,sse41,ssse3); ++#if defined(SPU_CONSUMER_REQUIRE_SSE41) ++ if(!sse41||!ssse3) { fputs("SDK SSE4.1 probe succeeded but linked consumer lost its ISA usage requirement\n",stderr);return 41; } ++#endif ++ return 0; ++} +diff --git a/tools/test_spu_isa_consumer.py b/tools/test_spu_isa_consumer.py +new file mode 100644 +index 00000000..4e3e46e5 +--- /dev/null ++++ b/tools/test_spu_isa_consumer.py +@@ -0,0 +1,88 @@ ++#!/usr/bin/env python3 ++"""Actual CMake C/C++ consumers inherit the SDK's probed SPU ISA contract.""" ++import argparse ++import json ++import os ++from pathlib import Path ++import re ++import shutil ++import subprocess ++import tempfile ++ ++ROOT=Path(__file__).resolve().parents[1] ++ ++def run(command,**kwargs): ++ result=subprocess.run(command,capture_output=True,text=True,timeout=120,**kwargs) ++ assert result.returncode==0,(command,result.returncode,result.stdout,result.stderr) ++ return result ++ ++def main(): ++ p=argparse.ArgumentParser(description=__doc__) ++ for name,default in [('cmake',os.environ.get('CMAKE') or shutil.which('cmake')), ++ ('ninja',os.environ.get('NINJA') or shutil.which('ninja')), ++ ('cc',os.environ.get('CC') or shutil.which('cc')), ++ ('cxx',os.environ.get('CXX') or shutil.which('c++'))]: ++ p.add_argument('--'+name,default=default) ++ a=p.parse_args() ++ if not all((a.cmake,a.ninja,a.cc,a.cxx)): ++ print('SKIP: CMake, Ninja and C/C++ compilers required');return 0 ++ msvc=Path(a.cxx).name.lower() in ('clang-cl','clang-cl.exe','cl','cl.exe') ++ with tempfile.TemporaryDirectory(prefix='spu-isa-consumer-') as directory: ++ out=Path(directory);source=ROOT/'runtime/spu/tests/test_spu_isa_consumer.c' ++ (out/'consumer.c').write_text('#include "'+source.as_posix()+'"\n') ++ (out/'consumer.cpp').write_text('#include "'+source.as_posix()+'"\n') ++ (out/'CMakeLists.txt').write_text(f'''cmake_minimum_required(VERSION 3.20) ++project(spu_isa_consumer C CXX) ++set(CMAKE_C_STANDARD 17) ++set(CMAKE_CXX_STANDARD 20) ++set(CMAKE_EXPORT_COMPILE_COMMANDS ON) ++add_subdirectory("{ROOT.as_posix()}" sdk EXCLUDE_FROM_ALL) ++# Match direct game sources plus independently compiled object-library consumers. ++add_executable(consumer_c consumer.c) ++target_link_libraries(consumer_c PRIVATE ps3recomp_runtime) ++add_library(consumer_cxx OBJECT consumer.cpp) ++target_link_libraries(consumer_cxx PRIVATE ps3recomp_runtime) ++if(PS3RECOMP_HAS_MSSE41) ++ target_compile_definitions(consumer_c PRIVATE SPU_CONSUMER_REQUIRE_SSE41=1) ++ target_compile_definitions(consumer_cxx PRIVATE SPU_CONSUMER_REQUIRE_SSE41=1) ++endif() ++''') ++ for label,extra in [('probed',[]),('probe-false',['-DPS3RECOMP_HAS_MSSE41:BOOL=OFF'])]: ++ build=out/label ++ run([a.cmake,'-S',str(out),'-B',str(build),'-G','Ninja', ++ '-DCMAKE_MAKE_PROGRAM='+a.ninja,'-DCMAKE_BUILD_TYPE=Release', ++ '-DCMAKE_C_COMPILER='+a.cc,'-DCMAKE_CXX_COMPILER='+a.cxx, ++ '-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded', ++ *extra]) ++ cache=(build/'CMakeCache.txt').read_text() ++ enabled=bool(re.search(r'^PS3RECOMP_HAS_MSSE41:(?:INTERNAL|BOOL)=(?:1|ON|TRUE)$',cache,re.M)) ++ commands=json.loads((build/'compile_commands.json').read_text()) ++ consumers=[row for row in commands if Path(row['file']).parent==out] ++ assert len(consumers)==2 ++ for row in consumers: ++ # Build only the real generated object rules. The semantic ++ # fixture is header-only and needs no SDK duplicate archive. ++ cmd=row['command'] ++ obj=row.get('output') ++ if not obj: ++ match=re.search(r'/Fo([^ ]+)|(?:^| )-o ([^ ]+)',cmd);assert match,cmd ++ obj=(match[1] or match[2]).strip('"') ++ if Path(obj).is_absolute():obj=os.path.relpath(obj,build) ++ obj=obj.replace('\\','/') ++ run([a.ninja,'-C',str(build),obj]) ++ suffix=Path(row['file']).suffix ++ exe=out/(label+('-cxx' if suffix=='.cpp' else '-c')+('.exe' if os.name=='nt' else '')) ++ if msvc:run([a.cxx,'/nologo','/MT',str(build/obj),'/Fe'+str(exe)]) ++ else:run([a.cxx,str(build/obj),'-pthread','-lm','-o',str(exe)]) ++ result=run([str(exe)]) ++ print(label,suffix,result.stdout.strip(),flush=True) ++ assert ('-msse4.1' in cmd)==enabled,cmd ++ if enabled: ++ objdump=shutil.which('llvm-objdump') or str(Path(a.cxx).with_name('llvm-objdump.exe')) ++ if Path(objdump).is_file(): ++ assembly=run([objdump,'-d','--disassemble-symbols=spu_consumer_shuffle',str(build/obj)]).stdout ++ assert re.search(r'\bv?pshufb\b',assembly),'x86 consumer wrapper lacks shuffle fast path' ++ if label=='probe-false':assert not enabled,'Forced unsupported-probe path ignored' ++ print('PASS actual CMake C/C++ ISA usage, architectural byte/selector/alias semantics, and unsupported-probe fallback') ++ ++if __name__=='__main__':main() diff --git a/tasks/sp00nznet__ps3recomp-678/solution/solve.sh b/tasks/sp00nznet__ps3recomp-678/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-678/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-678/task.toml b/tasks/sp00nznet__ps3recomp-678/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..841ec25b78ee21f2130ecc130b4d565c6477d59a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-678/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-678" +description = "fix(build): export the runtime's probed SSE4.1 requirement to consumers" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/678" +source_access = "auto" +built_at = "2026-11-16T16:09:59.722532+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5df059b0327f4f5b1019a5b91af6bb3a29694d4d5e78fd28c8b859ee6dad0bed" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "CMakeLists.txt", + "runtime/spu/tests/test_spu_isa_consumer.c", + "tools/test_spu_isa_consumer.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 164 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.153100+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-678/tests/capture.py b/tasks/sp00nznet__ps3recomp-678/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-678/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-678/tests/instruction.md b/tasks/sp00nznet__ps3recomp-678/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7b2a2bea103c85ce9e6c99453f0d80d5fe797c40 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-678/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(build): export the runtime's probed SSE4.1 requirement to consumers + +## Description + +The runtime probes `-msse4.1` and builds itself with it, but the flag is PRIVATE. Game targets that compile lifted SPU code include the same static-inline helpers without it, so on gcc/clang generic x86-64 they silently take the scalar `spu_shufb` and related paths. Making the flag PUBLIC propagates the probed ISA to consumers. Hosts where the probe fails (for example Apple clang on arm64) are unchanged. + +Test: `tools/test_spu_isa_consumer.py` configures a real CMake consumer (a C executable and a C++ object library) against the SDK, asserts `-msse4.1` is present exactly when the probe passed, checks 135,424 shuffle/selector cases, and repeats with the probe forced off. It skips when CMake or Ninja is unavailable. + +```sh +python3 tools/test_spu_isa_consumer.py +``` + +Passes on Apple Silicon (probe false). The meaningful case, gcc/clang on generic x86-64, is covered by hosted Linux CI on this PR. Based on master `4e8f3ca8` (v0.18.0); no dependency on another PR. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-678/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-678/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..dbeb8a1125b1ae166e2c936c5f772340d6f9d679 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-678/tests/oracle.patch @@ -0,0 +1,187 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..e99d3bbe 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -336,7 +336,9 @@ if(CMAKE_C_COMPILER_ID MATCHES "Clang|GNU") + include(CheckCCompilerFlag) + check_c_compiler_flag(-msse4.1 PS3RECOMP_HAS_MSSE41) + if(PS3RECOMP_HAS_MSSE41) +- target_compile_options(ps3recomp_runtime PRIVATE -msse4.1) ++ # Lifted consumers compile the same static-inline SPU helpers. Export ++ # the runtime's existing ISA requirement so their fast path agrees. ++ target_compile_options(ps3recomp_runtime PUBLIC -msse4.1) + endif() + elseif(MSVC) + # Real cl.exe -- clang-cl reports its id as Clang and is handled above. +diff --git a/runtime/spu/tests/test_spu_isa_consumer.c b/runtime/spu/tests/test_spu_isa_consumer.c +new file mode 100644 +index 00000000..4da08bb2 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_isa_consumer.c +@@ -0,0 +1,72 @@ ++/* Synthetic C/C++ SDK consumer: architectural oracle uses word shifts only, ++ * independently of SPU_W, SIMD intrinsics, and the helper's byte loop. */ ++#ifndef _CRT_SECURE_NO_WARNINGS ++#define _CRT_SECURE_NO_WARNINGS ++#endif ++#include "../spu_helpers.h" ++#include <stdio.h> ++#include <stdlib.h> ++ ++#if defined(_MSC_VER) ++#define CONSUMER_NOINLINE __declspec(noinline) ++#else ++#define CONSUMER_NOINLINE __attribute__((noinline)) ++#endif ++#ifdef __cplusplus ++extern "C" ++#endif ++CONSUMER_NOINLINE u128 spu_consumer_shuffle(u128 a,u128 b,u128 c) { return spu_shufb(a,b,c); } ++static unsigned cases; ++static u32 random_state=0x72BC409Du; ++static u128 cleared(void) { u128 value;memset(&value,0,sizeof(value));return value; } ++static u32 next_word(void) { random_state^=random_state<<13;random_state^=random_state>>17;random_state^=random_state<<5;return random_state; } ++static unsigned byte_at(u128 value,unsigned byte) { return (value._u32[byte/4]>>(24-8*(byte%4)))&255u; } ++static void put_byte(u128* value,unsigned byte,unsigned bits) { ++ const unsigned shift=24-8*(byte%4); ++ value->_u32[byte/4]=(value->_u32[byte/4]&~(255u<<shift))|((bits&255u)<<shift); ++} ++static u128 uniform(unsigned byte) { u128 value=cleared();for(unsigned i=0;i<16;i++)put_byte(&value,i,byte);return value; } ++static void check(u128 a,u128 b,u128 control) { ++ u128 expected=cleared(); ++ for(unsigned i=0;i<16;i++) { ++ const unsigned selector=byte_at(control,i); ++ const unsigned value=selector>=224?128:selector>=192?255:selector>=128?0: ++ (selector&16)?byte_at(b,selector&15):byte_at(a,selector&15); ++ put_byte(&expected,i,value); ++ } ++ u128 got=spu_consumer_shuffle(a,b,control); ++ u128 aa=a,bb=b,cc=control; ++ aa=spu_shufb(aa,b,control);bb=spu_shufb(a,bb,control);cc=spu_shufb(a,b,cc); ++ if(memcmp(&expected,&got,16)||memcmp(&expected,&aa,16)||memcmp(&expected,&bb,16)||memcmp(&expected,&cc,16)) { ++ fprintf(stderr,"SHUFB consumer semantic/alias failure case=%u\n",cases);exit(2); ++ } ++ ++cases; ++} ++int main(void) { ++ int sse41=0,ssse3=0; ++#if defined(__SSE4_1__) ++ sse41=1; ++#endif ++#if defined(__SSSE3__) ++ ssse3=1; ++#endif ++ u128 a=cleared(),b=cleared(),c=cleared(); ++ for(unsigned i=0;i<16;i++){put_byte(&a,i,i+1);put_byte(&b,i,i+65);put_byte(&c,i,i);} ++ for(unsigned selector=0;selector<256;selector++) { ++ check(a,b,uniform(selector)); ++ for(unsigned lane=0;lane<16;lane++){u128 mixed=c;put_byte(&mixed,lane,selector);check(a,b,mixed);} ++ } ++ for(unsigned bit=0;bit<128;bit++)for(unsigned selector=0;selector<256;selector++) { ++ u128 value=cleared(),zero=cleared();value._u32[bit/32]=1u<<(bit%32); ++ check(value,zero,uniform(selector));check(zero,value,uniform(selector)); ++ } ++ for(unsigned iteration=0;iteration<16384;iteration++) { ++ for(unsigned word=0;word<4;word++){a._u32[word]=next_word();b._u32[word]=next_word();c._u32[word]=next_word();} ++ check(a,b,c);check(a,a,c);check(a,b,a);check(a,b,b); ++ } ++ printf("SPU consumer semantics PASS cases=%u SSE4.1=%d SSSE3=%d\n",cases,sse41,ssse3); ++#if defined(SPU_CONSUMER_REQUIRE_SSE41) ++ if(!sse41||!ssse3) { fputs("SDK SSE4.1 probe succeeded but linked consumer lost its ISA usage requirement\n",stderr);return 41; } ++#endif ++ return 0; ++} +diff --git a/tools/test_spu_isa_consumer.py b/tools/test_spu_isa_consumer.py +new file mode 100644 +index 00000000..4e3e46e5 +--- /dev/null ++++ b/tools/test_spu_isa_consumer.py +@@ -0,0 +1,88 @@ ++#!/usr/bin/env python3 ++"""Actual CMake C/C++ consumers inherit the SDK's probed SPU ISA contract.""" ++import argparse ++import json ++import os ++from pathlib import Path ++import re ++import shutil ++import subprocess ++import tempfile ++ ++ROOT=Path(__file__).resolve().parents[1] ++ ++def run(command,**kwargs): ++ result=subprocess.run(command,capture_output=True,text=True,timeout=120,**kwargs) ++ assert result.returncode==0,(command,result.returncode,result.stdout,result.stderr) ++ return result ++ ++def main(): ++ p=argparse.ArgumentParser(description=__doc__) ++ for name,default in [('cmake',os.environ.get('CMAKE') or shutil.which('cmake')), ++ ('ninja',os.environ.get('NINJA') or shutil.which('ninja')), ++ ('cc',os.environ.get('CC') or shutil.which('cc')), ++ ('cxx',os.environ.get('CXX') or shutil.which('c++'))]: ++ p.add_argument('--'+name,default=default) ++ a=p.parse_args() ++ if not all((a.cmake,a.ninja,a.cc,a.cxx)): ++ print('SKIP: CMake, Ninja and C/C++ compilers required');return 0 ++ msvc=Path(a.cxx).name.lower() in ('clang-cl','clang-cl.exe','cl','cl.exe') ++ with tempfile.TemporaryDirectory(prefix='spu-isa-consumer-') as directory: ++ out=Path(directory);source=ROOT/'runtime/spu/tests/test_spu_isa_consumer.c' ++ (out/'consumer.c').write_text('#include "'+source.as_posix()+'"\n') ++ (out/'consumer.cpp').write_text('#include "'+source.as_posix()+'"\n') ++ (out/'CMakeLists.txt').write_text(f'''cmake_minimum_required(VERSION 3.20) ++project(spu_isa_consumer C CXX) ++set(CMAKE_C_STANDARD 17) ++set(CMAKE_CXX_STANDARD 20) ++set(CMAKE_EXPORT_COMPILE_COMMANDS ON) ++add_subdirectory("{ROOT.as_posix()}" sdk EXCLUDE_FROM_ALL) ++# Match direct game sources plus independently compiled object-library consumers. ++add_executable(consumer_c consumer.c) ++target_link_libraries(consumer_c PRIVATE ps3recomp_runtime) ++add_library(consumer_cxx OBJECT consumer.cpp) ++target_link_libraries(consumer_cxx PRIVATE ps3recomp_runtime) ++if(PS3RECOMP_HAS_MSSE41) ++ target_compile_definitions(consumer_c PRIVATE SPU_CONSUMER_REQUIRE_SSE41=1) ++ target_compile_definitions(consumer_cxx PRIVATE SPU_CONSUMER_REQUIRE_SSE41=1) ++endif() ++''') ++ for label,extra in [('probed',[]),('probe-false',['-DPS3RECOMP_HAS_MSSE41:BOOL=OFF'])]: ++ build=out/label ++ run([a.cmake,'-S',str(out),'-B',str(build),'-G','Ninja', ++ '-DCMAKE_MAKE_PROGRAM='+a.ninja,'-DCMAKE_BUILD_TYPE=Release', ++ '-DCMAKE_C_COMPILER='+a.cc,'-DCMAKE_CXX_COMPILER='+a.cxx, ++ '-DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded', ++ *extra]) ++ cache=(build/'CMakeCache.txt').read_text() ++ enabled=bool(re.search(r'^PS3RECOMP_HAS_MSSE41:(?:INTERNAL|BOOL)=(?:1|ON|TRUE)$',cache,re.M)) ++ commands=json.loads((build/'compile_commands.json').read_text()) ++ consumers=[row for row in commands if Path(row['file']).parent==out] ++ assert len(consumers)==2 ++ for row in consumers: ++ # Build only the real generated object rules. The semantic ++ # fixture is header-only and needs no SDK duplicate archive. ++ cmd=row['command'] ++ obj=row.get('output') ++ if not obj: ++ match=re.search(r'/Fo([^ ]+)|(?:^| )-o ([^ ]+)',cmd);assert match,cmd ++ obj=(match[1] or match[2]).strip('"') ++ if Path(obj).is_absolute():obj=os.path.relpath(obj,build) ++ obj=obj.replace('\\','/') ++ run([a.ninja,'-C',str(build),obj]) ++ suffix=Path(row['file']).suffix ++ exe=out/(label+('-cxx' if suffix=='.cpp' else '-c')+('.exe' if os.name=='nt' else '')) ++ if msvc:run([a.cxx,'/nologo','/MT',str(build/obj),'/Fe'+str(exe)]) ++ else:run([a.cxx,str(build/obj),'-pthread','-lm','-o',str(exe)]) ++ result=run([str(exe)]) ++ print(label,suffix,result.stdout.strip(),flush=True) ++ assert ('-msse4.1' in cmd)==enabled,cmd ++ if enabled: ++ objdump=shutil.which('llvm-objdump') or str(Path(a.cxx).with_name('llvm-objdump.exe')) ++ if Path(objdump).is_file(): ++ assembly=run([objdump,'-d','--disassemble-symbols=spu_consumer_shuffle',str(build/obj)]).stdout ++ assert re.search(r'\bv?pshufb\b',assembly),'x86 consumer wrapper lacks shuffle fast path' ++ if label=='probe-false':assert not enabled,'Forced unsupported-probe path ignored' ++ print('PASS actual CMake C/C++ ISA usage, architectural byte/selector/alias semantics, and unsupported-probe fallback') ++ ++if __name__=='__main__':main() diff --git a/tasks/sp00nznet__ps3recomp-678/tests/test.sh b/tasks/sp00nznet__ps3recomp-678/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-678/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-678/tests/verifier.py b/tasks/sp00nznet__ps3recomp-678/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-678/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-680/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-680/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-680/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-680/instruction.md b/tasks/sp00nznet__ps3recomp-680/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6e888695e5d8053e6b524a58c63684b53f2be3aa --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-680/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** ci: run macOS jobs on the macos-15 runner image + +## Description + +The macOS workflow pins `macos-14`. GitHub is retiring the arm64 macOS 14 image (); upstream's run on 2026-11-03 still received `macos-14-arm64 20260831`, so this is preventive. The arm64 matrix moves to `macos-15` with its existing architecture checks unchanged. + +A second commit makes `tools/test_ppu_prio_start.py` print the fixture's stderr when it fails under CI instead of discarding it, so a hosted failure is diagnosable from the log. + +The FIFO-walker profiler fix is already proposed in #657 and is intentionally not included here. + +Validation: + +```sh +CI=1 python3 tools/test_ppu_prio_start.py +``` + +Passes locally on Apple Silicon macOS. The runner change itself is verified by hosted CI on this PR. Based on master `4e8f3ca8` (v0.18.0); no dependency on another PR. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-680/solution/patch.diff b/tasks/sp00nznet__ps3recomp-680/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b3321f1158c8537cc97bc50cbb4de21c8fb6768b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-680/solution/patch.diff @@ -0,0 +1,31 @@ +diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml +index aeb9e948..400bfc41 100644 +--- a/.github/workflows/macos.yml ++++ b/.github/workflows/macos.yml +@@ -15,7 +15,7 @@ on: + jobs: + build: + name: macOS arm64 (${{ matrix.build_type }}) +- runs-on: macos-14 # Apple Silicon runner ++ runs-on: macos-15 # Apple Silicon runner + strategy: + fail-fast: false + matrix: +diff --git a/tools/test_ppu_prio_start.py b/tools/test_ppu_prio_start.py +index 8b2f893b..49b3f9be 100644 +--- a/tools/test_ppu_prio_start.py ++++ b/tools/test_ppu_prio_start.py +@@ -16,8 +16,11 @@ with tempfile.TemporaryDirectory(prefix='ppu-prio-start-') as tmp: + '-ffunction-sections','-fdata-sections', + '-I'+str(root/'include'),'-I'+str(root/'runtime'),'-I'+str(root/'runtime/syscalls'), + str(root/'tests/test_ppu_prio_start.c'),*linker,'-o',str(binary)],check=True) +- quiet=subprocess.DEVNULL if os.environ.get('CI') else None ++ quiet=subprocess.PIPE if os.environ.get('CI') else None + for on in (False, True): + env={k:v for k,v in os.environ.items() if k!='PS3_PRIO_START'} + if on: env['PS3_PRIO_START']='1' +- subprocess.run([str(binary)],check=True,timeout=60,env=env,stderr=quiet) ++ result=subprocess.run([str(binary)],timeout=60,env=env,stderr=quiet,text=True) ++ if result.returncode and result.stderr: ++ sys.stderr.write(result.stderr) ++ result.check_returncode() diff --git a/tasks/sp00nznet__ps3recomp-680/solution/solve.sh b/tasks/sp00nznet__ps3recomp-680/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-680/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-680/task.toml b/tasks/sp00nznet__ps3recomp-680/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..830f676c376cecb32b837001c8d63f6a897f0a3c --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-680/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-680" +description = "ci: run macOS jobs on the macos-15 runner image" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/680" +source_access = "auto" +built_at = "2026-11-16T16:09:59.720720+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:974710ead1600a96f2cb91aae781076dc5b8d0e165b1e00f39385591b53b19f3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + ".github/workflows/macos.yml", + "tools/test_ppu_prio_start.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 9 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.153707+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-680/tests/capture.py b/tasks/sp00nznet__ps3recomp-680/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-680/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-680/tests/instruction.md b/tasks/sp00nznet__ps3recomp-680/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6e888695e5d8053e6b524a58c63684b53f2be3aa --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-680/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** ci: run macOS jobs on the macos-15 runner image + +## Description + +The macOS workflow pins `macos-14`. GitHub is retiring the arm64 macOS 14 image (); upstream's run on 2026-11-03 still received `macos-14-arm64 20260831`, so this is preventive. The arm64 matrix moves to `macos-15` with its existing architecture checks unchanged. + +A second commit makes `tools/test_ppu_prio_start.py` print the fixture's stderr when it fails under CI instead of discarding it, so a hosted failure is diagnosable from the log. + +The FIFO-walker profiler fix is already proposed in #657 and is intentionally not included here. + +Validation: + +```sh +CI=1 python3 tools/test_ppu_prio_start.py +``` + +Passes locally on Apple Silicon macOS. The runner change itself is verified by hosted CI on this PR. Based on master `4e8f3ca8` (v0.18.0); no dependency on another PR. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-680/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-680/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b3321f1158c8537cc97bc50cbb4de21c8fb6768b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-680/tests/oracle.patch @@ -0,0 +1,31 @@ +diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml +index aeb9e948..400bfc41 100644 +--- a/.github/workflows/macos.yml ++++ b/.github/workflows/macos.yml +@@ -15,7 +15,7 @@ on: + jobs: + build: + name: macOS arm64 (${{ matrix.build_type }}) +- runs-on: macos-14 # Apple Silicon runner ++ runs-on: macos-15 # Apple Silicon runner + strategy: + fail-fast: false + matrix: +diff --git a/tools/test_ppu_prio_start.py b/tools/test_ppu_prio_start.py +index 8b2f893b..49b3f9be 100644 +--- a/tools/test_ppu_prio_start.py ++++ b/tools/test_ppu_prio_start.py +@@ -16,8 +16,11 @@ with tempfile.TemporaryDirectory(prefix='ppu-prio-start-') as tmp: + '-ffunction-sections','-fdata-sections', + '-I'+str(root/'include'),'-I'+str(root/'runtime'),'-I'+str(root/'runtime/syscalls'), + str(root/'tests/test_ppu_prio_start.c'),*linker,'-o',str(binary)],check=True) +- quiet=subprocess.DEVNULL if os.environ.get('CI') else None ++ quiet=subprocess.PIPE if os.environ.get('CI') else None + for on in (False, True): + env={k:v for k,v in os.environ.items() if k!='PS3_PRIO_START'} + if on: env['PS3_PRIO_START']='1' +- subprocess.run([str(binary)],check=True,timeout=60,env=env,stderr=quiet) ++ result=subprocess.run([str(binary)],timeout=60,env=env,stderr=quiet,text=True) ++ if result.returncode and result.stderr: ++ sys.stderr.write(result.stderr) ++ result.check_returncode() diff --git a/tasks/sp00nznet__ps3recomp-680/tests/test.sh b/tasks/sp00nznet__ps3recomp-680/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-680/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-680/tests/verifier.py b/tasks/sp00nznet__ps3recomp-680/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-680/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-681/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-681/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-681/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-681/instruction.md b/tasks/sp00nznet__ps3recomp-681/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4082351f89852b41cbde71d3b06d3fa52a4cb75e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-681/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** feat(video): R32F and RGBA32F colour targets in the Vulkan engine + +## Description + +The register-file engine on Vulkan created colour targets only in RGBA8 and RGBA16F (`vk_eng_rt_index`), so a surface declared with SET_SURFACE_FORMAT colour 0xC (A32B32G32R32F) or 0xD (B32F) got no target: the engine logged `colour target format 12 ... not supported yet` and the draws into it were lost. Titles render small reductions, such as a 1x1 average-luminance target, into these formats. + +**Fix:** R32F and RGBA32F join the engine's render-target formats. Both are required colour attachments in Vulkan 1.0, but blending into them is optional. On a device without `COLOR_ATTACHMENT_BLEND` for the format, those targets draw unblended and the engine logs it once. The check sits next to the existing per-target MRT blend state. + +**Test:** two new host scenes, `--float-rt` and `--float-rt-r`. Each draws the red triangle into a 64x64 RGBA32F or R32F surface with SRC_ALPHA / ONE_MINUS_SRC_ALPHA blending, then samples the surface onto the display as W32_Z32_Y32_X32_FLOAT or X32_FLOAT. The guest bytes behind the surface can't read as red, so a target that was never created fails the check. `linux-vulkan.yml` runs both under the validation layer. + +- With this change, on lavapipe (gcc and clang), every engine scene passes with no VUIDs, the new two included ([fork run](https://github.com/tekulvw/ps3recomp/actions/runs/41773153864)). +- Negative control: the same scenes without the backend change fail only `--float-rt` and `--float-rt-r` (exit 3, `colour target format 12 64x64 not supported yet`) ([fork run](https://github.com/tekulvw/ps3recomp/actions/runs/41773156809)). +- On Metal (Apple M4 Pro, headless), both scenes pass locally. They are not added to `macos.yml`. +- The Vulkan backend compiles cleanly with `-Wall -Wextra` on Apple clang against Vulkan-Headers v1.3.290. + +Based on master `4e8f3ca8`; no dependency on another PR. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-681/solution/patch.diff b/tasks/sp00nznet__ps3recomp-681/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1f82cc044ff289f01240cb1c5f9fcc4b9599a36b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-681/solution/patch.diff @@ -0,0 +1,247 @@ +diff --git a/.github/workflows/linux-vulkan.yml b/.github/workflows/linux-vulkan.yml +index e829bc3a..771047da 100644 +--- a/.github/workflows/linux-vulkan.yml ++++ b/.github/workflows/linux-vulkan.yml +@@ -88,7 +88,8 @@ jobs: + # before any backend exists (the first pass still runs it). + for m in "" "--draw" "--depth" "--quads" "--shader" \ + "--tex" "--tex-io" "--mip" "--rtt" "--depthtex" "--mrt" "--mrt-a" "--cube" \ +- "--depthbounds" "--split-present" "--feedback" "--clip" "--clip-keep"; do ++ "--depthbounds" "--split-present" "--feedback" "--clip" "--clip-keep" \ ++ "--float-rt" "--float-rt-r"; do + rc=0; ./build/ps3recomp_host $m > run.log 2>&1 || rc=$? + name=${m:-default} + echo "::group::ps3recomp_host $name -> exit $rc"; cat run.log; echo "::endgroup::" +diff --git a/libs/video/rsx_vulkan_backend.c b/libs/video/rsx_vulkan_backend.c +index db64302e..55d9a0a4 100644 +--- a/libs/video/rsx_vulkan_backend.c ++++ b/libs/video/rsx_vulkan_backend.c +@@ -2124,18 +2124,32 @@ static VkFormat vk_eng_format(rsx_be_format f, u32* bpp) + } + + /* Colour formats the E2 passes render into: RGBA8 for ordinary and display +- * targets, RGBA16F for SET_SURFACE_FORMAT 0xB HDR targets. Both are required +- * colour attachment formats with blending in Vulkan 1.0. */ +-#define VK_ENG_RT_FORMATS 2 ++ * targets, RGBA16F for SET_SURFACE_FORMAT 0xB HDR targets, and R32F / RGBA32F ++ * for the float targets a title renders small reductions into. All four are ++ * required colour attachment formats in Vulkan 1.0; blending is guaranteed only ++ * for the first two (see vk_eng_rt_blendable). */ ++#define VK_ENG_RT_FORMATS 4 + static int vk_eng_rt_index(VkFormat f) + { + switch (f) { + case VK_FORMAT_R8G8B8A8_UNORM: return 0; + case VK_FORMAT_R16G16B16A16_SFLOAT: return 1; ++ case VK_FORMAT_R32_SFLOAT: return 2; ++ case VK_FORMAT_R32G32B32A32_SFLOAT: return 3; + default: return -1; + } + } + ++/* Whether the device blends into colour format `f` (guaranteed for RGBA8 and ++ * RGBA16F, optional for 32-bit float formats). */ ++static int vk_eng_rt_blendable(VkFormat f) ++{ ++ if (f == VK_FORMAT_R8G8B8A8_UNORM || f == VK_FORMAT_R16G16B16A16_SFLOAT) return 1; ++ VkFormatProperties fp; ++ pvkGetPhysicalDeviceFormatProperties(s_vk.phys, f, &fp); ++ return (fp.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT) != 0; ++} ++ + /* The largest image side the engine creates: the device's own limit once a + * device is picked, the 4096 Vulkan guarantees before. */ + static u32 vk_max_dim(void) { return s_vk.max_dim ? s_vk.max_dim : 4096u; } +@@ -3168,6 +3182,9 @@ static VkPipeline vk_eng_variant(vk_eng_pipe* P, u32 topo_idx) + static int mrt_mode = -1; + if (mrt_mode < 0) { const char* e = getenv("PS3RECOMP_VK_MRT_MASK"); mrt_mode = e ? atoi(e) : 1; } + VkPipelineColorBlendAttachmentState cba[RSX_BE_MAX_COLOR_TARGETS]; ++ /* A device without blending on a float target draws it unblended; that is ++ * reported once, never silently. */ ++ const int blendable = vk_eng_rt_blendable(P->rt_fmt); + for (u32 r = 0; r < P->rt_count; r++) { + VkColorComponentFlags twm = wm; + int tblend = rs->blend_enable != 0; +@@ -3182,6 +3199,14 @@ static VkPipeline vk_eng_variant(vk_eng_pipe* P, u32 topo_idx) + } + tblend = (rs->blend_mrt >> r) & 1u; + } ++ if (tblend && !blendable) { ++ tblend = 0; ++ if (!(s_e2.warned & 256u)) { ++ VK_LOG("engine: blending unsupported for colour format %d on this device; drawing unblended\n", ++ (int)P->rt_fmt); ++ s_e2.warned |= 256u; ++ } ++ } + cba[r] = (VkPipelineColorBlendAttachmentState){ + .blendEnable = tblend ? VK_TRUE : VK_FALSE, + .srcColorBlendFactor = vk_gcm_blend_factor(rs->sf_rgb), +diff --git a/runtime/host/host_posix.c b/runtime/host/host_posix.c +index 447d36d2..4e20920c 100644 +--- a/runtime/host/host_posix.c ++++ b/runtime/host/host_posix.c +@@ -180,6 +180,17 @@ static const u32 CUBE_FACE_ARGB[6] = { + }; + #define CUBE_ARGB 0xFF8040E0u /* face 5, -Z: what --cube must read */ + ++/* --float-rt / --float-rt-r: an offscreen RGBA32F (SET_SURFACE_FORMAT colour ++ * 0xC) or R32F (0xD) surface, the size the guest clips it to, and the bytes ++ * per pixel of each. The backing is one float per channel in R, G, B, A ++ * order, (0, 1, 1, 1) for RGBA32F and 0 for R32F: no reading of those bytes ++ * in any channel order presents the red the surface is drawn, so a surface ++ * that was never created and was sampled from guest memory instead shows. */ ++#define FRT_OFFSET 0x001D0000u ++#define FRT_DIM 64u ++#define FRT_RGBA_BPP 16u ++#define FRT_R_BPP 4u ++ + /* Functions the RSX side exports but does not declare in a public header. */ + extern void cellGcm_rsx_process_fifo(void); + extern int cellGcm_take_flip_pending_synced(void); +@@ -296,6 +307,16 @@ static void upload_rtt_backing(void) + guest_w32(IO_ADDR + RTT_OFFSET + i * 4u, RTT_BACKING); + } + ++/* Guest memory behind the --float-rt surfaces (see FRT_OFFSET). */ ++static void upload_float_rt_backing(int one_channel) ++{ ++ static const float rgba[4] = { 0.0f, 1.0f, 1.0f, 1.0f }; ++ const uint32_t bpp = one_channel ? FRT_R_BPP : FRT_RGBA_BPP; ++ for (uint32_t i = 0; i < FRT_DIM * FRT_DIM; i++) ++ for (uint32_t c = 0; c < bpp / 4u; c++) ++ guest_f32(IO_ADDR + FRT_OFFSET + i * bpp + c * 4u, rgba[c]); ++} ++ + /* ...and the same for --depthtex's zeta: the bytes a CPU-cleared depth buffer + * would hold at the offset the second pass binds a texture unit to. */ + static void upload_depthtex_backing(void) +@@ -783,6 +804,46 @@ static void emit_feedback_draws(void) + emit_textured_draw_at(RTT_OFFSET, RTT_DIM, RTT_DIM); + } + ++/* --float-rt / --float-rt-r: the red triangle into a 32-bit float colour ++ * surface with blending on, then the display samples it, as --feedback does ++ * for an A8R8G8B8 one: the surface's pitch and format are declared so a ++ * W32_Z32_Y32_X32_FLOAT (0x9B) or X32_FLOAT (0x9C) texture over the same bytes ++ * describes one layout. A title renders small reductions (a scene's average ++ * luminance) into targets like these and blends into them. ++ * ++ * SRC_ALPHA / ONE_MINUS_SRC_ALPHA over the surface's seeded contents with the ++ * triangle's alpha of 1 leaves red, so the check is the same as --rtt's; what ++ * the mode adds is a blended pipeline and a render pass in a float format, ++ * which the Vulkan workflow runs under the validation layer. */ ++static void emit_float_rt_draws(int one_channel) ++{ ++ const u32 bpp = one_channel ? FRT_R_BPP : FRT_RGBA_BPP; ++ emit(NV4097_SET_CONTEXT_DMA_COLOR_A, CELL_GCM_CONTEXT_DMA_MEMORY_HOST_BUFFER); ++ emit(NV4097_SET_SURFACE_COLOR_AOFFSET, FRT_OFFSET); ++ emit(NV4097_SET_SURFACE_PITCH_A, FRT_DIM * bpp); ++ /* colour 0xC (A32B32G32R32F) or 0xD (B32F), Z24S8, linear. */ ++ emit(NV4097_SET_SURFACE_FORMAT, one_channel ? 0x14Du : 0x14Cu); ++ emit(NV4097_SET_SURFACE_COLOR_TARGET, CELL_GCM_SURFACE_TARGET_0); ++ emit(NV4097_SET_SURFACE_CLIP_HORIZONTAL, FRT_DIM << 16); ++ emit(NV4097_SET_SURFACE_CLIP_VERTICAL, FRT_DIM << 16); ++ emit(NV4097_SET_SHADER_PROGRAM, 0u); ++ emit(NV4097_SET_BLEND_ENABLE, 1u); ++ emit(NV4097_SET_BLEND_FUNC_SFACTOR, 0x0302u | (0x0302u << 16)); /* SRC_ALPHA */ ++ emit(NV4097_SET_BLEND_FUNC_DFACTOR, 0x0303u | (0x0303u << 16)); /* ONE_MINUS_SRC_ALPHA */ ++ emit(NV4097_SET_BLEND_EQUATION, 0x8006u | (0x8006u << 16)); /* FUNC_ADD */ ++ emit_triangle_draw(); ++ emit(NV4097_SET_BLEND_ENABLE, 0u); ++ ++ emit(NV4097_SET_CONTEXT_DMA_COLOR_A, CELL_GCM_CONTEXT_DMA_MEMORY_FRAME_BUFFER); ++ emit(NV4097_SET_SURFACE_COLOR_AOFFSET, 0u); ++ emit(NV4097_SET_SURFACE_PITCH_A, 1280u * 4u); ++ emit(NV4097_SET_SURFACE_FORMAT, 0x148u); /* A8R8G8B8 again */ ++ emit(NV4097_SET_SURFACE_CLIP_HORIZONTAL, 1280u << 16); ++ emit(NV4097_SET_SURFACE_CLIP_VERTICAL, 720u << 16); ++ emit(NV4097_SET_TEXTURE_CONTROL3 + 0, FRT_DIM * bpp); ++ emit_textured_draw_fmt(FRT_OFFSET, FRT_DIM, FRT_DIM, (one_channel ? 0x9Cu : 0x9Bu) | 0x20u); ++} ++ + /* Declare an MRT1 set, write both of its members from ONE draw, then sample + * one of them -- which is what a deferred renderer's G-buffer pass is. + * +@@ -1092,6 +1153,7 @@ static void submit_frame(int with_draw) + else if (with_draw == 8) emit_depthtex_draws(); + else if (with_draw == 7) emit_quad_draws(); + else if (with_draw == 14) emit_feedback_draws(); ++ else if (with_draw == 18 || with_draw == 19) emit_float_rt_draws(with_draw == 19); + else if (with_draw == 6) emit_rtt_draws(); + else if (with_draw == 5) emit_mip_draw(); + else if (with_draw == 4) emit_depth_draw(); +@@ -1325,7 +1387,7 @@ static int mode_needs_translator(int mode) + { + return mode == 3 || mode == 5 || mode == 6 || mode == 8 || mode == 14 || + mode == 9 || mode == 10 || mode == 11 || mode == 15 || +- mode == 16 || mode == 17; ++ mode == 16 || mode == 17 || mode == 18 || mode == 19; + } + + /* ...and which ones must, on a backend that has a translator, have run the +@@ -1349,6 +1411,8 @@ static const char* mode_flag_name(int mode) + case 15: return "--border"; + case 16: return "--clip"; + case 17: return "--clip-keep"; ++ case 18: return "--float-rt"; ++ case 19: return "--float-rt-r"; + default: return "(mode)"; + } + } +@@ -1460,6 +1524,9 @@ int main(int argc, char** argv) + /* --clip / --clip-keep: see emit_clip_draw. */ + else if (strcmp(argv[i], "--clip") == 0) do_draw = 16; + else if (strcmp(argv[i], "--clip-keep") == 0) do_draw = 17; ++ /* --float-rt / --float-rt-r: see emit_float_rt_draws. */ ++ else if (strcmp(argv[i], "--float-rt") == 0) do_draw = 18; ++ else if (strcmp(argv[i], "--float-rt-r") == 0) do_draw = 19; + } + #if !defined(__APPLE__) + if (do_draw == 15) { +@@ -1519,6 +1586,11 @@ int main(int argc, char** argv) + if (do_draw == 5) { upload_mip_texture(); upload_mip_quad(); } + /* --rtt draws both: the triangle into the surface, the quad out of it. */ + if (do_draw == 6 || do_draw == 14) { upload_triangle(); upload_textured_quad(); upload_rtt_backing(); } ++ if (do_draw == 18 || do_draw == 19) { ++ upload_triangle(); ++ upload_textured_quad(); ++ upload_float_rt_backing(do_draw == 19); ++ } + if (do_draw == 7) upload_quad_geometry(); + /* --depthtex draws both too: the flat triangle into the zeta, the quad + * out of it. */ +@@ -1621,7 +1693,9 @@ int main(int argc, char** argv) + * here, and MRT_BACKING means the guest bytes behind the surface were + * sampled instead of the surface itself. With --cube it is the -Z + * face's colour: any other face's colour means a face went missing on +- * the way up or the image was sampled as 2D. ++ * the way up or the image was sampled as 2D. With --float-rt it is ++ * red once more, out of an RGBA32F surface; --float-rt-r's R32F ++ * surface has only a red channel, so only red is compared there. + */ + u32 want = (do_draw == 15) ? BORDER_ARGB /* the border, not the texture */ + : (do_draw == 12) ? 0xFF0000FFu /* blue, inside its bounds */ +@@ -1632,6 +1706,7 @@ int main(int argc, char** argv) + : (do_draw == 7) ? 0xFFFF0000u /* the quad strip over the polygon */ + : (do_draw == 17) ? 0xFFFF0000u /* plane 1 keeps d >= 0 */ + : (do_draw == 16) ? CLEAR_ARGB /* plane 1 clipped it all */ ++ : (do_draw == 18 || do_draw == 19) ? 0xFFFF0000u /* only the surface holds red */ + : (do_draw == 14) ? 0xFFFF0000u /* the copy kept the triangle */ + : (do_draw == 6) ? 0xFFFF0000u /* only the surface holds red */ + : (do_draw == 5) ? (s_mip_aniso ? MIP_L0_ARGB : MIP_L1_ARGB) +@@ -1640,9 +1715,11 @@ int main(int argc, char** argv) + : (do_draw == 2) ? TEX_ARGB + : (do_draw == 1) ? 0xFFFF0000u + : CLEAR_ARGB; +- printf("[host] presented pixel: 0x%08X (expected 0x%08X) %s\n", +- back, want, (back & 0x00FFFFFFu) == (want & 0x00FFFFFFu) ? "OK" : "MISMATCH"); +- if ((back & 0x00FFFFFFu) != (want & 0x00FFFFFFu)) rc = 3; ++ const u32 cmp = (do_draw == 19) ? 0x00FF0000u : 0x00FFFFFFu; ++ printf("[host] presented pixel: 0x%08X (expected 0x%08X%s) %s\n", ++ back, want, (do_draw == 19) ? ", red only" : "", ++ (back & cmp) == (want & cmp) ? "OK" : "MISMATCH"); ++ if ((back & cmp) != (want & cmp)) rc = 3; + } + if (mode_runs_guest_programs(do_draw) && HOST_BACKEND_GUEST_SHADERS) { + /* The pixel alone cannot prove the programs ran: a backend that diff --git a/tasks/sp00nznet__ps3recomp-681/solution/solve.sh b/tasks/sp00nznet__ps3recomp-681/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-681/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-681/task.toml b/tasks/sp00nznet__ps3recomp-681/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..23a70656bfbc11ef258cf520a16a2046738dbc56 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-681/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-681" +description = "feat(video): R32F and RGBA32F colour targets in the Vulkan engine" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/681" +source_access = "auto" +built_at = "2026-11-16T16:09:59.718793+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8fa15944797dd0225ed1713944e136c65afdefb623311d7c4606d356ceb91418" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + ".github/workflows/linux-vulkan.yml", + "libs/video/rsx_vulkan_backend.c", + "runtime/host/host_posix.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 121 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.154241+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-681/tests/capture.py b/tasks/sp00nznet__ps3recomp-681/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-681/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-681/tests/instruction.md b/tasks/sp00nznet__ps3recomp-681/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4082351f89852b41cbde71d3b06d3fa52a4cb75e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-681/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** feat(video): R32F and RGBA32F colour targets in the Vulkan engine + +## Description + +The register-file engine on Vulkan created colour targets only in RGBA8 and RGBA16F (`vk_eng_rt_index`), so a surface declared with SET_SURFACE_FORMAT colour 0xC (A32B32G32R32F) or 0xD (B32F) got no target: the engine logged `colour target format 12 ... not supported yet` and the draws into it were lost. Titles render small reductions, such as a 1x1 average-luminance target, into these formats. + +**Fix:** R32F and RGBA32F join the engine's render-target formats. Both are required colour attachments in Vulkan 1.0, but blending into them is optional. On a device without `COLOR_ATTACHMENT_BLEND` for the format, those targets draw unblended and the engine logs it once. The check sits next to the existing per-target MRT blend state. + +**Test:** two new host scenes, `--float-rt` and `--float-rt-r`. Each draws the red triangle into a 64x64 RGBA32F or R32F surface with SRC_ALPHA / ONE_MINUS_SRC_ALPHA blending, then samples the surface onto the display as W32_Z32_Y32_X32_FLOAT or X32_FLOAT. The guest bytes behind the surface can't read as red, so a target that was never created fails the check. `linux-vulkan.yml` runs both under the validation layer. + +- With this change, on lavapipe (gcc and clang), every engine scene passes with no VUIDs, the new two included ([fork run](https://github.com/tekulvw/ps3recomp/actions/runs/41773153864)). +- Negative control: the same scenes without the backend change fail only `--float-rt` and `--float-rt-r` (exit 3, `colour target format 12 64x64 not supported yet`) ([fork run](https://github.com/tekulvw/ps3recomp/actions/runs/41773156809)). +- On Metal (Apple M4 Pro, headless), both scenes pass locally. They are not added to `macos.yml`. +- The Vulkan backend compiles cleanly with `-Wall -Wextra` on Apple clang against Vulkan-Headers v1.3.290. + +Based on master `4e8f3ca8`; no dependency on another PR. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-681/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-681/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1f82cc044ff289f01240cb1c5f9fcc4b9599a36b --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-681/tests/oracle.patch @@ -0,0 +1,247 @@ +diff --git a/.github/workflows/linux-vulkan.yml b/.github/workflows/linux-vulkan.yml +index e829bc3a..771047da 100644 +--- a/.github/workflows/linux-vulkan.yml ++++ b/.github/workflows/linux-vulkan.yml +@@ -88,7 +88,8 @@ jobs: + # before any backend exists (the first pass still runs it). + for m in "" "--draw" "--depth" "--quads" "--shader" \ + "--tex" "--tex-io" "--mip" "--rtt" "--depthtex" "--mrt" "--mrt-a" "--cube" \ +- "--depthbounds" "--split-present" "--feedback" "--clip" "--clip-keep"; do ++ "--depthbounds" "--split-present" "--feedback" "--clip" "--clip-keep" \ ++ "--float-rt" "--float-rt-r"; do + rc=0; ./build/ps3recomp_host $m > run.log 2>&1 || rc=$? + name=${m:-default} + echo "::group::ps3recomp_host $name -> exit $rc"; cat run.log; echo "::endgroup::" +diff --git a/libs/video/rsx_vulkan_backend.c b/libs/video/rsx_vulkan_backend.c +index db64302e..55d9a0a4 100644 +--- a/libs/video/rsx_vulkan_backend.c ++++ b/libs/video/rsx_vulkan_backend.c +@@ -2124,18 +2124,32 @@ static VkFormat vk_eng_format(rsx_be_format f, u32* bpp) + } + + /* Colour formats the E2 passes render into: RGBA8 for ordinary and display +- * targets, RGBA16F for SET_SURFACE_FORMAT 0xB HDR targets. Both are required +- * colour attachment formats with blending in Vulkan 1.0. */ +-#define VK_ENG_RT_FORMATS 2 ++ * targets, RGBA16F for SET_SURFACE_FORMAT 0xB HDR targets, and R32F / RGBA32F ++ * for the float targets a title renders small reductions into. All four are ++ * required colour attachment formats in Vulkan 1.0; blending is guaranteed only ++ * for the first two (see vk_eng_rt_blendable). */ ++#define VK_ENG_RT_FORMATS 4 + static int vk_eng_rt_index(VkFormat f) + { + switch (f) { + case VK_FORMAT_R8G8B8A8_UNORM: return 0; + case VK_FORMAT_R16G16B16A16_SFLOAT: return 1; ++ case VK_FORMAT_R32_SFLOAT: return 2; ++ case VK_FORMAT_R32G32B32A32_SFLOAT: return 3; + default: return -1; + } + } + ++/* Whether the device blends into colour format `f` (guaranteed for RGBA8 and ++ * RGBA16F, optional for 32-bit float formats). */ ++static int vk_eng_rt_blendable(VkFormat f) ++{ ++ if (f == VK_FORMAT_R8G8B8A8_UNORM || f == VK_FORMAT_R16G16B16A16_SFLOAT) return 1; ++ VkFormatProperties fp; ++ pvkGetPhysicalDeviceFormatProperties(s_vk.phys, f, &fp); ++ return (fp.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT) != 0; ++} ++ + /* The largest image side the engine creates: the device's own limit once a + * device is picked, the 4096 Vulkan guarantees before. */ + static u32 vk_max_dim(void) { return s_vk.max_dim ? s_vk.max_dim : 4096u; } +@@ -3168,6 +3182,9 @@ static VkPipeline vk_eng_variant(vk_eng_pipe* P, u32 topo_idx) + static int mrt_mode = -1; + if (mrt_mode < 0) { const char* e = getenv("PS3RECOMP_VK_MRT_MASK"); mrt_mode = e ? atoi(e) : 1; } + VkPipelineColorBlendAttachmentState cba[RSX_BE_MAX_COLOR_TARGETS]; ++ /* A device without blending on a float target draws it unblended; that is ++ * reported once, never silently. */ ++ const int blendable = vk_eng_rt_blendable(P->rt_fmt); + for (u32 r = 0; r < P->rt_count; r++) { + VkColorComponentFlags twm = wm; + int tblend = rs->blend_enable != 0; +@@ -3182,6 +3199,14 @@ static VkPipeline vk_eng_variant(vk_eng_pipe* P, u32 topo_idx) + } + tblend = (rs->blend_mrt >> r) & 1u; + } ++ if (tblend && !blendable) { ++ tblend = 0; ++ if (!(s_e2.warned & 256u)) { ++ VK_LOG("engine: blending unsupported for colour format %d on this device; drawing unblended\n", ++ (int)P->rt_fmt); ++ s_e2.warned |= 256u; ++ } ++ } + cba[r] = (VkPipelineColorBlendAttachmentState){ + .blendEnable = tblend ? VK_TRUE : VK_FALSE, + .srcColorBlendFactor = vk_gcm_blend_factor(rs->sf_rgb), +diff --git a/runtime/host/host_posix.c b/runtime/host/host_posix.c +index 447d36d2..4e20920c 100644 +--- a/runtime/host/host_posix.c ++++ b/runtime/host/host_posix.c +@@ -180,6 +180,17 @@ static const u32 CUBE_FACE_ARGB[6] = { + }; + #define CUBE_ARGB 0xFF8040E0u /* face 5, -Z: what --cube must read */ + ++/* --float-rt / --float-rt-r: an offscreen RGBA32F (SET_SURFACE_FORMAT colour ++ * 0xC) or R32F (0xD) surface, the size the guest clips it to, and the bytes ++ * per pixel of each. The backing is one float per channel in R, G, B, A ++ * order, (0, 1, 1, 1) for RGBA32F and 0 for R32F: no reading of those bytes ++ * in any channel order presents the red the surface is drawn, so a surface ++ * that was never created and was sampled from guest memory instead shows. */ ++#define FRT_OFFSET 0x001D0000u ++#define FRT_DIM 64u ++#define FRT_RGBA_BPP 16u ++#define FRT_R_BPP 4u ++ + /* Functions the RSX side exports but does not declare in a public header. */ + extern void cellGcm_rsx_process_fifo(void); + extern int cellGcm_take_flip_pending_synced(void); +@@ -296,6 +307,16 @@ static void upload_rtt_backing(void) + guest_w32(IO_ADDR + RTT_OFFSET + i * 4u, RTT_BACKING); + } + ++/* Guest memory behind the --float-rt surfaces (see FRT_OFFSET). */ ++static void upload_float_rt_backing(int one_channel) ++{ ++ static const float rgba[4] = { 0.0f, 1.0f, 1.0f, 1.0f }; ++ const uint32_t bpp = one_channel ? FRT_R_BPP : FRT_RGBA_BPP; ++ for (uint32_t i = 0; i < FRT_DIM * FRT_DIM; i++) ++ for (uint32_t c = 0; c < bpp / 4u; c++) ++ guest_f32(IO_ADDR + FRT_OFFSET + i * bpp + c * 4u, rgba[c]); ++} ++ + /* ...and the same for --depthtex's zeta: the bytes a CPU-cleared depth buffer + * would hold at the offset the second pass binds a texture unit to. */ + static void upload_depthtex_backing(void) +@@ -783,6 +804,46 @@ static void emit_feedback_draws(void) + emit_textured_draw_at(RTT_OFFSET, RTT_DIM, RTT_DIM); + } + ++/* --float-rt / --float-rt-r: the red triangle into a 32-bit float colour ++ * surface with blending on, then the display samples it, as --feedback does ++ * for an A8R8G8B8 one: the surface's pitch and format are declared so a ++ * W32_Z32_Y32_X32_FLOAT (0x9B) or X32_FLOAT (0x9C) texture over the same bytes ++ * describes one layout. A title renders small reductions (a scene's average ++ * luminance) into targets like these and blends into them. ++ * ++ * SRC_ALPHA / ONE_MINUS_SRC_ALPHA over the surface's seeded contents with the ++ * triangle's alpha of 1 leaves red, so the check is the same as --rtt's; what ++ * the mode adds is a blended pipeline and a render pass in a float format, ++ * which the Vulkan workflow runs under the validation layer. */ ++static void emit_float_rt_draws(int one_channel) ++{ ++ const u32 bpp = one_channel ? FRT_R_BPP : FRT_RGBA_BPP; ++ emit(NV4097_SET_CONTEXT_DMA_COLOR_A, CELL_GCM_CONTEXT_DMA_MEMORY_HOST_BUFFER); ++ emit(NV4097_SET_SURFACE_COLOR_AOFFSET, FRT_OFFSET); ++ emit(NV4097_SET_SURFACE_PITCH_A, FRT_DIM * bpp); ++ /* colour 0xC (A32B32G32R32F) or 0xD (B32F), Z24S8, linear. */ ++ emit(NV4097_SET_SURFACE_FORMAT, one_channel ? 0x14Du : 0x14Cu); ++ emit(NV4097_SET_SURFACE_COLOR_TARGET, CELL_GCM_SURFACE_TARGET_0); ++ emit(NV4097_SET_SURFACE_CLIP_HORIZONTAL, FRT_DIM << 16); ++ emit(NV4097_SET_SURFACE_CLIP_VERTICAL, FRT_DIM << 16); ++ emit(NV4097_SET_SHADER_PROGRAM, 0u); ++ emit(NV4097_SET_BLEND_ENABLE, 1u); ++ emit(NV4097_SET_BLEND_FUNC_SFACTOR, 0x0302u | (0x0302u << 16)); /* SRC_ALPHA */ ++ emit(NV4097_SET_BLEND_FUNC_DFACTOR, 0x0303u | (0x0303u << 16)); /* ONE_MINUS_SRC_ALPHA */ ++ emit(NV4097_SET_BLEND_EQUATION, 0x8006u | (0x8006u << 16)); /* FUNC_ADD */ ++ emit_triangle_draw(); ++ emit(NV4097_SET_BLEND_ENABLE, 0u); ++ ++ emit(NV4097_SET_CONTEXT_DMA_COLOR_A, CELL_GCM_CONTEXT_DMA_MEMORY_FRAME_BUFFER); ++ emit(NV4097_SET_SURFACE_COLOR_AOFFSET, 0u); ++ emit(NV4097_SET_SURFACE_PITCH_A, 1280u * 4u); ++ emit(NV4097_SET_SURFACE_FORMAT, 0x148u); /* A8R8G8B8 again */ ++ emit(NV4097_SET_SURFACE_CLIP_HORIZONTAL, 1280u << 16); ++ emit(NV4097_SET_SURFACE_CLIP_VERTICAL, 720u << 16); ++ emit(NV4097_SET_TEXTURE_CONTROL3 + 0, FRT_DIM * bpp); ++ emit_textured_draw_fmt(FRT_OFFSET, FRT_DIM, FRT_DIM, (one_channel ? 0x9Cu : 0x9Bu) | 0x20u); ++} ++ + /* Declare an MRT1 set, write both of its members from ONE draw, then sample + * one of them -- which is what a deferred renderer's G-buffer pass is. + * +@@ -1092,6 +1153,7 @@ static void submit_frame(int with_draw) + else if (with_draw == 8) emit_depthtex_draws(); + else if (with_draw == 7) emit_quad_draws(); + else if (with_draw == 14) emit_feedback_draws(); ++ else if (with_draw == 18 || with_draw == 19) emit_float_rt_draws(with_draw == 19); + else if (with_draw == 6) emit_rtt_draws(); + else if (with_draw == 5) emit_mip_draw(); + else if (with_draw == 4) emit_depth_draw(); +@@ -1325,7 +1387,7 @@ static int mode_needs_translator(int mode) + { + return mode == 3 || mode == 5 || mode == 6 || mode == 8 || mode == 14 || + mode == 9 || mode == 10 || mode == 11 || mode == 15 || +- mode == 16 || mode == 17; ++ mode == 16 || mode == 17 || mode == 18 || mode == 19; + } + + /* ...and which ones must, on a backend that has a translator, have run the +@@ -1349,6 +1411,8 @@ static const char* mode_flag_name(int mode) + case 15: return "--border"; + case 16: return "--clip"; + case 17: return "--clip-keep"; ++ case 18: return "--float-rt"; ++ case 19: return "--float-rt-r"; + default: return "(mode)"; + } + } +@@ -1460,6 +1524,9 @@ int main(int argc, char** argv) + /* --clip / --clip-keep: see emit_clip_draw. */ + else if (strcmp(argv[i], "--clip") == 0) do_draw = 16; + else if (strcmp(argv[i], "--clip-keep") == 0) do_draw = 17; ++ /* --float-rt / --float-rt-r: see emit_float_rt_draws. */ ++ else if (strcmp(argv[i], "--float-rt") == 0) do_draw = 18; ++ else if (strcmp(argv[i], "--float-rt-r") == 0) do_draw = 19; + } + #if !defined(__APPLE__) + if (do_draw == 15) { +@@ -1519,6 +1586,11 @@ int main(int argc, char** argv) + if (do_draw == 5) { upload_mip_texture(); upload_mip_quad(); } + /* --rtt draws both: the triangle into the surface, the quad out of it. */ + if (do_draw == 6 || do_draw == 14) { upload_triangle(); upload_textured_quad(); upload_rtt_backing(); } ++ if (do_draw == 18 || do_draw == 19) { ++ upload_triangle(); ++ upload_textured_quad(); ++ upload_float_rt_backing(do_draw == 19); ++ } + if (do_draw == 7) upload_quad_geometry(); + /* --depthtex draws both too: the flat triangle into the zeta, the quad + * out of it. */ +@@ -1621,7 +1693,9 @@ int main(int argc, char** argv) + * here, and MRT_BACKING means the guest bytes behind the surface were + * sampled instead of the surface itself. With --cube it is the -Z + * face's colour: any other face's colour means a face went missing on +- * the way up or the image was sampled as 2D. ++ * the way up or the image was sampled as 2D. With --float-rt it is ++ * red once more, out of an RGBA32F surface; --float-rt-r's R32F ++ * surface has only a red channel, so only red is compared there. + */ + u32 want = (do_draw == 15) ? BORDER_ARGB /* the border, not the texture */ + : (do_draw == 12) ? 0xFF0000FFu /* blue, inside its bounds */ +@@ -1632,6 +1706,7 @@ int main(int argc, char** argv) + : (do_draw == 7) ? 0xFFFF0000u /* the quad strip over the polygon */ + : (do_draw == 17) ? 0xFFFF0000u /* plane 1 keeps d >= 0 */ + : (do_draw == 16) ? CLEAR_ARGB /* plane 1 clipped it all */ ++ : (do_draw == 18 || do_draw == 19) ? 0xFFFF0000u /* only the surface holds red */ + : (do_draw == 14) ? 0xFFFF0000u /* the copy kept the triangle */ + : (do_draw == 6) ? 0xFFFF0000u /* only the surface holds red */ + : (do_draw == 5) ? (s_mip_aniso ? MIP_L0_ARGB : MIP_L1_ARGB) +@@ -1640,9 +1715,11 @@ int main(int argc, char** argv) + : (do_draw == 2) ? TEX_ARGB + : (do_draw == 1) ? 0xFFFF0000u + : CLEAR_ARGB; +- printf("[host] presented pixel: 0x%08X (expected 0x%08X) %s\n", +- back, want, (back & 0x00FFFFFFu) == (want & 0x00FFFFFFu) ? "OK" : "MISMATCH"); +- if ((back & 0x00FFFFFFu) != (want & 0x00FFFFFFu)) rc = 3; ++ const u32 cmp = (do_draw == 19) ? 0x00FF0000u : 0x00FFFFFFu; ++ printf("[host] presented pixel: 0x%08X (expected 0x%08X%s) %s\n", ++ back, want, (do_draw == 19) ? ", red only" : "", ++ (back & cmp) == (want & cmp) ? "OK" : "MISMATCH"); ++ if ((back & cmp) != (want & cmp)) rc = 3; + } + if (mode_runs_guest_programs(do_draw) && HOST_BACKEND_GUEST_SHADERS) { + /* The pixel alone cannot prove the programs ran: a backend that diff --git a/tasks/sp00nznet__ps3recomp-681/tests/test.sh b/tasks/sp00nznet__ps3recomp-681/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-681/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-681/tests/verifier.py b/tasks/sp00nznet__ps3recomp-681/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-681/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-682/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-682/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-682/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-682/instruction.md b/tasks/sp00nznet__ps3recomp-682/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a051013d25755419ef3850188cc852c743a2a7e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-682/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** fix(video): keep stale engine releases off live Vulkan objects + +## Description + +The Vulkan engine reused object handles lowest-slot-first, so a release of a handle the engine had already released freed whatever object owned that slot by then. In one title a colour target's slot ended up holding a texture; the next colour feedback draw could not snapshot its target and the frame stalled. + +**This is a defensive change.** It does not find where the stale handle comes from. It makes such a release harmless and visible: + +- `vk_eng_alloc` hands out slots round-robin, so a released handle is not reused at once. A late or duplicated release then finds a free slot, which `vk_eng_release` already ignores. +- `texture_release`, `color_target_release` and `depth_target_release` each check the kind of object they are asked to free. Colour targets go through the colour call, depth targets through the depth call, and textures, views and colour feedback copies through the texture call. A release through the wrong call can only be a stale handle. It is refused and logged (`engine: stale ... release of object N ... refused`, first 16 times), and the live object is kept. + +I checked every release call site in `rsx_draw_engine.c` against that kind mapping. One thing I noticed on the way: on a zeta resize, `eng_zdepth` releases `z->snapshot` twice (before and after `depth_target_release`). That does no harm on Vulkan, because nothing allocates between the two calls and `z->snapshot` is cleared right after. So it is not the source of the stale handle above. + +**Testing:** the Vulkan workflow on lavapipe (gcc and clang), every scene in both passes, the guest-program pass under the validation layer. All pass with no VUIDs, and the new refusal message never appears, so ordinary releases are not refused ([fork run](https://github.com/tekulvw/ps3recomp/actions/runs/41773328151)). The backend compiles cleanly with `-Wall -Wextra` on Apple clang against Vulkan-Headers v1.3.290. No synthetic fixture drives a stale release, because none of the existing upstream Vulkan tests can inject one. + +Based on master `4e8f3ca8`; independent of #681. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-682/solution/patch.diff b/tasks/sp00nznet__ps3recomp-682/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e0f83b21c225d768cf3718e1cb5b4d34420af098 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-682/solution/patch.diff @@ -0,0 +1,83 @@ +diff --git a/libs/video/rsx_vulkan_backend.c b/libs/video/rsx_vulkan_backend.c +index db64302e..594859ef 100644 +--- a/libs/video/rsx_vulkan_backend.c ++++ b/libs/video/rsx_vulkan_backend.c +@@ -2142,8 +2142,17 @@ static u32 vk_max_dim(void) { return s_vk.max_dim ? s_vk.max_dim : 4096u; } + + static u32 vk_eng_alloc(void) + { +- for (u32 i = 1; i < VK_ENG_MAX_OBJ; i++) +- if (s_eobj[i].kind == VK_ENG_FREE) return i; ++ /* Hand out slots round-robin rather than lowest-first, so a handle the ++ * engine releases is not immediately reused: a late or duplicated release ++ * of an old handle then finds a free slot instead of a live object. */ ++ static u32 cursor; ++ for (u32 step = 0; step < VK_ENG_MAX_OBJ - 1; step++) { ++ const u32 i = 1 + (cursor + step) % (VK_ENG_MAX_OBJ - 1); ++ if (s_eobj[i].kind == VK_ENG_FREE) { ++ cursor = i % (VK_ENG_MAX_OBJ - 1); ++ return i; ++ } ++ } + VK_LOG("engine: object table full (%d)\n", VK_ENG_MAX_OBJ); + return 0; + } +@@ -2293,6 +2302,42 @@ static void vk_eng_release(void* user, u32 handle) + memset(&s_eobj[handle], 0, sizeof s_eobj[handle]); + } + ++/* The engine releases each object through the call for its kind: colour ++ * targets through color_target_release, depth targets through ++ * depth_target_release, and textures, views and colour feedback copies ++ * through texture_release. Handles are slots that get reused, so a release ++ * naming an object of another kind can only be a stale handle, and freeing ++ * it would destroy the live object that now owns the slot. It is refused and ++ * reported instead. Free slots pass through: vk_eng_release ignores them. */ ++static int vk_eng_release_kind_ok(u32 handle, int want_color, int want_depth) ++{ ++ if (!handle || handle >= VK_ENG_MAX_OBJ) return 1; ++ const vk_eng_obj* o = &s_eobj[handle]; ++ if (o->kind == VK_ENG_FREE) return 1; ++ const int color = o->kind == VK_ENG_COLOR && !o->snapshot, depth = o->kind == VK_ENG_DEPTH; ++ const int ok = want_color ? color : want_depth ? depth : (!color && !depth); ++ if (!ok) { ++ static u32 logs; ++ if (logs++ < 16) ++ VK_LOG("engine: stale %s release of object %u (kind %d%s, %ux%u) refused\n", ++ want_color ? "colour target" : want_depth ? "depth target" : "texture", handle, ++ (int)o->kind, o->snapshot ? " snapshot" : "", o->w, o->h); ++ } ++ return ok; ++} ++static void vk_eng_texture_release(void* user, u32 handle) ++{ ++ if (vk_eng_release_kind_ok(handle, 0, 0)) vk_eng_release(user, handle); ++} ++static void vk_eng_color_target_release(void* user, u32 handle) ++{ ++ if (vk_eng_release_kind_ok(handle, 1, 0)) vk_eng_release(user, handle); ++} ++static void vk_eng_depth_target_release(void* user, u32 handle) ++{ ++ if (vk_eng_release_kind_ok(handle, 0, 1)) vk_eng_release(user, handle); ++} ++ + static void vk_eng_snapshot_pool_drain(void); + + static void vk_eng_shutdown(void* user) +@@ -3756,12 +3801,12 @@ static const rsx_draw_backend s_vk_engine_backend = { + .submit_and_wait = vk_eng_submit_and_wait, + .texture_create = vk_eng_texture_create, + .texture_upload = vk_eng_texture_upload, +- .texture_release = vk_eng_release, ++ .texture_release = vk_eng_texture_release, + .color_target_create = vk_eng_color_target_create, +- .color_target_release = vk_eng_release, ++ .color_target_release = vk_eng_color_target_release, + .surface_view = vk_eng_surface_view, + .depth_target_create = vk_eng_depth_target_create, +- .depth_target_release = vk_eng_release, ++ .depth_target_release = vk_eng_depth_target_release, + .depth_snapshot = vk_eng_depth_snapshot, + .color_snapshot = vk_eng_color_snapshot, + .pipeline_create = vk_eng_pipeline_create, diff --git a/tasks/sp00nznet__ps3recomp-682/solution/solve.sh b/tasks/sp00nznet__ps3recomp-682/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-682/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-682/task.toml b/tasks/sp00nznet__ps3recomp-682/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b3306bd1d9a2a7c5140347c38b9c15d93cb154f7 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-682/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-682" +description = "fix(video): keep stale engine releases off live Vulkan objects" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/682" +source_access = "auto" +built_at = "2026-11-16T16:09:59.716994+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1edd7e61b460a68e4b501860c749443e76d9b9a3c37c2ac3deeb065294addfeb" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/video/rsx_vulkan_backend.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 55 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.154782+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-682/tests/capture.py b/tasks/sp00nznet__ps3recomp-682/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-682/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-682/tests/instruction.md b/tasks/sp00nznet__ps3recomp-682/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a051013d25755419ef3850188cc852c743a2a7e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-682/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** fix(video): keep stale engine releases off live Vulkan objects + +## Description + +The Vulkan engine reused object handles lowest-slot-first, so a release of a handle the engine had already released freed whatever object owned that slot by then. In one title a colour target's slot ended up holding a texture; the next colour feedback draw could not snapshot its target and the frame stalled. + +**This is a defensive change.** It does not find where the stale handle comes from. It makes such a release harmless and visible: + +- `vk_eng_alloc` hands out slots round-robin, so a released handle is not reused at once. A late or duplicated release then finds a free slot, which `vk_eng_release` already ignores. +- `texture_release`, `color_target_release` and `depth_target_release` each check the kind of object they are asked to free. Colour targets go through the colour call, depth targets through the depth call, and textures, views and colour feedback copies through the texture call. A release through the wrong call can only be a stale handle. It is refused and logged (`engine: stale ... release of object N ... refused`, first 16 times), and the live object is kept. + +I checked every release call site in `rsx_draw_engine.c` against that kind mapping. One thing I noticed on the way: on a zeta resize, `eng_zdepth` releases `z->snapshot` twice (before and after `depth_target_release`). That does no harm on Vulkan, because nothing allocates between the two calls and `z->snapshot` is cleared right after. So it is not the source of the stale handle above. + +**Testing:** the Vulkan workflow on lavapipe (gcc and clang), every scene in both passes, the guest-program pass under the validation layer. All pass with no VUIDs, and the new refusal message never appears, so ordinary releases are not refused ([fork run](https://github.com/tekulvw/ps3recomp/actions/runs/41773328151)). The backend compiles cleanly with `-Wall -Wextra` on Apple clang against Vulkan-Headers v1.3.290. No synthetic fixture drives a stale release, because none of the existing upstream Vulkan tests can inject one. + +Based on master `4e8f3ca8`; independent of #681. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-682/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-682/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e0f83b21c225d768cf3718e1cb5b4d34420af098 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-682/tests/oracle.patch @@ -0,0 +1,83 @@ +diff --git a/libs/video/rsx_vulkan_backend.c b/libs/video/rsx_vulkan_backend.c +index db64302e..594859ef 100644 +--- a/libs/video/rsx_vulkan_backend.c ++++ b/libs/video/rsx_vulkan_backend.c +@@ -2142,8 +2142,17 @@ static u32 vk_max_dim(void) { return s_vk.max_dim ? s_vk.max_dim : 4096u; } + + static u32 vk_eng_alloc(void) + { +- for (u32 i = 1; i < VK_ENG_MAX_OBJ; i++) +- if (s_eobj[i].kind == VK_ENG_FREE) return i; ++ /* Hand out slots round-robin rather than lowest-first, so a handle the ++ * engine releases is not immediately reused: a late or duplicated release ++ * of an old handle then finds a free slot instead of a live object. */ ++ static u32 cursor; ++ for (u32 step = 0; step < VK_ENG_MAX_OBJ - 1; step++) { ++ const u32 i = 1 + (cursor + step) % (VK_ENG_MAX_OBJ - 1); ++ if (s_eobj[i].kind == VK_ENG_FREE) { ++ cursor = i % (VK_ENG_MAX_OBJ - 1); ++ return i; ++ } ++ } + VK_LOG("engine: object table full (%d)\n", VK_ENG_MAX_OBJ); + return 0; + } +@@ -2293,6 +2302,42 @@ static void vk_eng_release(void* user, u32 handle) + memset(&s_eobj[handle], 0, sizeof s_eobj[handle]); + } + ++/* The engine releases each object through the call for its kind: colour ++ * targets through color_target_release, depth targets through ++ * depth_target_release, and textures, views and colour feedback copies ++ * through texture_release. Handles are slots that get reused, so a release ++ * naming an object of another kind can only be a stale handle, and freeing ++ * it would destroy the live object that now owns the slot. It is refused and ++ * reported instead. Free slots pass through: vk_eng_release ignores them. */ ++static int vk_eng_release_kind_ok(u32 handle, int want_color, int want_depth) ++{ ++ if (!handle || handle >= VK_ENG_MAX_OBJ) return 1; ++ const vk_eng_obj* o = &s_eobj[handle]; ++ if (o->kind == VK_ENG_FREE) return 1; ++ const int color = o->kind == VK_ENG_COLOR && !o->snapshot, depth = o->kind == VK_ENG_DEPTH; ++ const int ok = want_color ? color : want_depth ? depth : (!color && !depth); ++ if (!ok) { ++ static u32 logs; ++ if (logs++ < 16) ++ VK_LOG("engine: stale %s release of object %u (kind %d%s, %ux%u) refused\n", ++ want_color ? "colour target" : want_depth ? "depth target" : "texture", handle, ++ (int)o->kind, o->snapshot ? " snapshot" : "", o->w, o->h); ++ } ++ return ok; ++} ++static void vk_eng_texture_release(void* user, u32 handle) ++{ ++ if (vk_eng_release_kind_ok(handle, 0, 0)) vk_eng_release(user, handle); ++} ++static void vk_eng_color_target_release(void* user, u32 handle) ++{ ++ if (vk_eng_release_kind_ok(handle, 1, 0)) vk_eng_release(user, handle); ++} ++static void vk_eng_depth_target_release(void* user, u32 handle) ++{ ++ if (vk_eng_release_kind_ok(handle, 0, 1)) vk_eng_release(user, handle); ++} ++ + static void vk_eng_snapshot_pool_drain(void); + + static void vk_eng_shutdown(void* user) +@@ -3756,12 +3801,12 @@ static const rsx_draw_backend s_vk_engine_backend = { + .submit_and_wait = vk_eng_submit_and_wait, + .texture_create = vk_eng_texture_create, + .texture_upload = vk_eng_texture_upload, +- .texture_release = vk_eng_release, ++ .texture_release = vk_eng_texture_release, + .color_target_create = vk_eng_color_target_create, +- .color_target_release = vk_eng_release, ++ .color_target_release = vk_eng_color_target_release, + .surface_view = vk_eng_surface_view, + .depth_target_create = vk_eng_depth_target_create, +- .depth_target_release = vk_eng_release, ++ .depth_target_release = vk_eng_depth_target_release, + .depth_snapshot = vk_eng_depth_snapshot, + .color_snapshot = vk_eng_color_snapshot, + .pipeline_create = vk_eng_pipeline_create, diff --git a/tasks/sp00nznet__ps3recomp-682/tests/test.sh b/tasks/sp00nznet__ps3recomp-682/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-682/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-682/tests/verifier.py b/tasks/sp00nznet__ps3recomp-682/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-682/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-683/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-683/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-683/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-683/instruction.md b/tasks/sp00nznet__ps3recomp-683/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e73f8025c656ff5adc9020b062069e1e17ffcb1 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-683/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** perf(spu): four-lane SSE4.1 form of the single-precision helpers + +## Description + +x86 builds without AVX2 (the default `-msse4.1` runtime) ran `spu_fa`/`fs`/`fm`/`fma`/`fms`/`fnms` one lane at a time through the scalar fast path. Those helpers topped a Linux profile of a title's SPU work. + +**Change:** a new `#elif defined(__SSE4_1__)` branch after the AVX2 form in `spu_helpers.h`. It applies the AVX2 form's lane rules word for word, with each f64x4 step done as two f64x2 halves. Each half widens exactly, operates, clears the 29 low significand bits and narrows exactly. A lane keeps the vector result only where it is provably the truncated SPU result: ordinary single or true-zero operands, the exponent gap for adds, a normal-range result, and the TwoSum boundary check for fma. Every other lane is redone by the existing per-lane path. SSE4.1 has no FMA instruction, so nothing can be contracted. 64-bit ordered compares are SSE4.2, so the exponent range checks narrow to 32-bit lanes first. The NEON and AVX2 forms and the scalar fallback are unchanged; AVX2 builds still take the AVX2 form. + +**Tests (synthetic):** +- New `test_spu_float_vector_scalar` compares the selected vector form with the scalar per-lane forms (`spu__*_s`) bit for bit. It covers every edge-word triple (+-0, biased exponent 0 with fractions, smallest normal, largest finite, biased exponent 255, Smax) and random lanes aimed at 2^-126/2^128, cancellation and wide gaps. It is registered with ctest next to `test_spu_float_exact`, and the new CI step runs both. +- On x86, both float tests build with `-msse4.1 -ffp-contract=off` when `PS3RECOMP_HAS_MSSE41`, so the SSE4.1 form is the one under test, as it is in the runtime. + +Results: +- Ryzen 7800X3D (Linux), measured by the author: 96.7M lanes against scalar and 446.8M lanes against the exact references, 0 mismatches, for both the SSE4.1 and the AVX2 forms. Time per vector: `fa` 10.9 -> 5.7 ns, `fm` 9.3 -> 2.8 ns, `fma` 11.2 -> 5.3 ns. +- Apple M4 Pro, x86_64 build with `-msse4.1 -ffp-contract=off` under Rosetta 2 (the preprocessed source confirms the SSE4.1 branch is the one selected): `test_spu_float_vector_scalar 4` gives 16.7M lanes with 0 mismatches, and `test_spu_float_exact` gives 446,840,832 lanes, bit-identical. +- Native arm64 (NEON form): both tests pass, also through `ctest`. +- Linux CI did not build either float test, so a second commit (`ci:`) adds a `linux.yml` step that builds and runs both with `-msse4.1 -ffp-contract=off`. On the fork, all four Linux jobs (gcc and clang, Debug and Release) report `16714984 lanes, 0 mismatches` and `446840832 lanes bit-identical` ([fork run](https://github.com/tekulvw/ps3recomp/actions/runs/41774752970)). + +Related: #678 makes the probed `-msse4.1` PUBLIC, so lifted code that includes these helpers also gets this form. This PR doesn't depend on it. + +Based on master `4e8f3ca8`. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-683/solution/patch.diff b/tasks/sp00nznet__ps3recomp-683/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0b10f16b49557c82786ce1c675c4f1ac5e15dd46 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-683/solution/patch.diff @@ -0,0 +1,280 @@ +diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml +index 99c0b20c..22ee81f0 100644 +--- a/.github/workflows/linux.yml ++++ b/.github/workflows/linux.yml +@@ -117,6 +117,18 @@ jobs: + echo "no AVX2 on this runner: skipped" + fi + ++ # The SSE4.1 single-precision form (the default x86-64 build) against the scalar per-lane ++ # forms and against the exact references, bit for bit, built as the runtime is. ++ - name: Run the SPU float vector tests (SSE4.1) ++ run: | ++ for t in test_spu_float_vector_scalar test_spu_float_exact; do ++ ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} \ ++ -std=gnu17 -O2 -msse4.1 -ffp-contract=off -UNDEBUG -I include -I runtime/spu \ ++ -o /tmp/${t}_sse41 runtime/spu/tests/$t.c -lm ++ done ++ /tmp/test_spu_float_vector_scalar_sse41 4 ++ /tmp/test_spu_float_exact_sse41 ++ + # runtime/spu/tests/test_spu_int_x86.c checks #512's SSE4.1 and AVX2 integer + # and quadword-shift forms against their scalar spu_X_ref references. #512 + # added the file and wired it into nothing -- no workflow step, no CMake +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..02a16013 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -416,6 +416,20 @@ if(PS3RECOMP_BUILD_TESTS) + target_link_libraries(test_spu_float_exact PRIVATE m) + add_test(NAME spu_float_exact COMMAND test_spu_float_exact) + set_tests_properties(spu_float_exact PROPERTIES TIMEOUT 300) ++ # The vector forms against the scalar per-lane forms, directly. ++ add_executable(test_spu_float_vector_scalar ++ runtime/spu/tests/test_spu_float_vector_scalar.c) ++ target_include_directories(test_spu_float_vector_scalar PRIVATE include runtime/spu) ++ target_compile_options(test_spu_float_vector_scalar PRIVATE -UNDEBUG) ++ target_link_libraries(test_spu_float_vector_scalar PRIVATE m) ++ add_test(NAME spu_float_vector_scalar COMMAND test_spu_float_vector_scalar 4) ++ set_tests_properties(spu_float_vector_scalar PROPERTIES TIMEOUT 300) ++ # On x86 both take the ISA the runtime and lifted code are built for, so the SSE4.1 ++ # vector form is the one under test; no contraction, as in the runtime. ++ if(PS3RECOMP_HAS_MSSE41) ++ target_compile_options(test_spu_float_exact PRIVATE -msse4.1 -ffp-contract=off) ++ target_compile_options(test_spu_float_vector_scalar PRIVATE -msse4.1 -ffp-contract=off) ++ endif() + + add_executable(test_spu_lockline_wait + runtime/spu/tests/test_spu_lockline_wait.c) +diff --git a/runtime/spu/spu_helpers.h b/runtime/spu/spu_helpers.h +index f04fda63..d6f1fa2c 100644 +--- a/runtime/spu/spu_helpers.h ++++ b/runtime/spu/spu_helpers.h +@@ -1129,6 +1129,122 @@ SPU__X8_INLINE u128 spu__x8_fma(u128 a, u128 b, u128 c, uint32_t negp, uint32_t + SPU__X8_INLINE u128 spu_fma(u128 a, u128 b, u128 c) { return spu__x8_fma(a, b, c, 0, 0); } /* a*b + c */ + SPU__X8_INLINE u128 spu_fms(u128 a, u128 b, u128 c) { return spu__x8_fma(a, b, c, 0, 0x80000000u); } /* a*b - c */ + SPU__X8_INLINE u128 spu_fnms(u128 a, u128 b, u128 c) { return spu__x8_fma(a, b, c, 0x80000000u, 0); } /* c - a*b */ ++#elif defined(__SSE4_1__) && !defined(SPU_SCALAR_HELPERS) ++/* The AVX2 form above with SSE4.1 only (the default x86-64 build), each f64x4 step done as two ++ * f64x2 halves: lanes 0-1 and lanes 2-3 widened exactly, the same operation, the 29 low ++ * significand bits cleared, narrowed exactly. The lane rules are the AVX2 ones word for word, so a ++ * lane takes the vector result only where that result is provably the exact truncation, and ++ * every other lane is redone by the per-lane path (spu__*_any). There is no FMA instruction here, ++ * so nothing can be contracted; the double product of two 24-bit significands is exact anyway. ++ * 64-bit compares other than equality are SSE4.2, so exponent range checks narrow the double ++ * exponents to 32-bit lanes first. */ ++#include <smmintrin.h> ++#define SPU__X4_INLINE static inline __attribute__((always_inline)) ++#define SPU__X4_SLOW static __attribute__((noinline, cold, unused)) ++SPU__X4_INLINE __m128i spu__x4_bexp(__m128i x) { return _mm_srli_epi32(_mm_slli_epi32(x, 1), 24); } ++SPU__X4_INLINE __m128i spu__x4_zero(__m128i x) { return _mm_cmpeq_epi32(_mm_slli_epi32(x, 1), _mm_setzero_si128()); } ++SPU__X4_INLINE __m128i spu__x4_plain0(__m128i x) { /* biased exponent 1..254, or +-0 */ ++ const __m128i e = spu__x4_bexp(x); ++ return _mm_or_si128(_mm_and_si128(_mm_cmpgt_epi32(e, _mm_setzero_si128()), _mm_cmpgt_epi32(_mm_set1_epi32(255), e)), ++ spu__x4_zero(x)); ++} ++/* the four singles widened to doubles: lanes 0-1 in *lo, lanes 2-3 in *hi (exact) */ ++SPU__X4_INLINE void spu__x4_wide(__m128i x, __m128d* lo, __m128d* hi) { ++ const __m128 f = _mm_castsi128_ps(x); ++ *lo = _mm_cvtps_pd(f); *hi = _mm_cvtps_pd(_mm_movehl_ps(f, f)); ++} ++/* the low 32 bits of each 64-bit lane of lo:hi, as four 32-bit lanes 0..3 */ ++SPU__X4_INLINE __m128i spu__x4_narrow(__m128i lo, __m128i hi) { ++ return _mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(lo), _mm_castsi128_ps(hi), _MM_SHUFFLE(2, 0, 2, 0))); ++} ++/* lo:hi truncated to singles. *ok: lanes whose result is a normal single or an exact zero and, ++ * when err is given, did not both round and land on a 24-bit boundary. *zm: the zero lanes. */ ++SPU__X4_INLINE __m128i spu__x4_trunc0(__m128d dlo, __m128d dhi, __m128i* ok, __m128i* zm, ++ const __m128d* elo, const __m128d* ehi) { ++ const __m128i ulo = _mm_castpd_si128(dlo), uhi = _mm_castpd_si128(dhi); ++ const __m128i az = spu__x4_narrow(_mm_cmpeq_epi64(_mm_slli_epi64(ulo, 1), _mm_setzero_si128()), ++ _mm_cmpeq_epi64(_mm_slli_epi64(uhi, 1), _mm_setzero_si128())); ++ /* biased double exponent, 0..2047, per lane; a normal single needs it in 1023-126..1023+127 */ ++ const __m128i be = _mm_and_si128(spu__x4_narrow(_mm_srli_epi64(ulo, 52), _mm_srli_epi64(uhi, 52)), _mm_set1_epi32(0x7FF)); ++ __m128i good = _mm_andnot_si128(_mm_or_si128(_mm_cmpgt_epi32(_mm_set1_epi32(1023 - 126), be), ++ _mm_cmpgt_epi32(be, _mm_set1_epi32(1023 + 127))), ++ _mm_set1_epi32(-1)); ++ if (elo) { ++ const __m128i low = _mm_set1_epi64x(0x1FFFFFFF); ++ const __m128i bnd = spu__x4_narrow(_mm_cmpeq_epi64(_mm_and_si128(ulo, low), _mm_setzero_si128()), ++ _mm_cmpeq_epi64(_mm_and_si128(uhi, low), _mm_setzero_si128())); ++ const __m128i rnd = spu__x4_narrow(_mm_castpd_si128(_mm_cmpneq_pd(*elo, _mm_setzero_pd())), ++ _mm_castpd_si128(_mm_cmpneq_pd(*ehi, _mm_setzero_pd()))); ++ good = _mm_andnot_si128(_mm_and_si128(bnd, rnd), good); ++ } ++ *ok = _mm_or_si128(good, az); ++ *zm = az; ++ const __m128i keep = _mm_set1_epi64x(~0x1FFFFFFFll); ++ const __m128 t = _mm_movelh_ps(_mm_cvtpd_ps(_mm_castsi128_pd(_mm_and_si128(ulo, keep))), ++ _mm_cvtpd_ps(_mm_castsi128_pd(_mm_and_si128(uhi, keep)))); ++ return _mm_andnot_si128(_mm_and_si128(az, _mm_set1_epi32((int)0x80000000u)), _mm_castps_si128(t)); ++} ++SPU__X4_INLINE int spu__x4_all4(__m128i m) { return _mm_movemask_ps(_mm_castsi128_ps(m)) == 0xF; } ++SPU__X4_INLINE __m128i spu__x4_ld(u128 a) { return _mm_loadu_si128((const __m128i*)a._u32); } ++SPU__X4_INLINE u128 spu__x4_st(__m128i v) { u128 r; _mm_storeu_si128((__m128i*)r._u32, v); return r; } ++SPU__X4_SLOW u128 spu__x4_fa_fix(u128 r, __m128i ok, u128 a, u128 b, uint32_t negb) { ++ const int m = _mm_movemask_ps(_mm_castsi128_ps(ok)); ++ for (int i = 0; i < 4; i++) if (!(m >> i & 1)) r._u32[i] = spu__fa_any(a._u32[i], b._u32[i] ^ negb); ++ return r; ++} ++SPU__X4_SLOW u128 spu__x4_fm_fix(u128 r, __m128i ok, u128 a, u128 b) { ++ const int m = _mm_movemask_ps(_mm_castsi128_ps(ok)); ++ for (int i = 0; i < 4; i++) if (!(m >> i & 1)) r._u32[i] = spu__fm_any(a._u32[i], b._u32[i]); ++ return r; ++} ++SPU__X4_SLOW u128 spu__x4_fma_fix(u128 r, __m128i ok, u128 a, u128 b, u128 c, uint32_t negp, uint32_t negc) { ++ const int m = _mm_movemask_ps(_mm_castsi128_ps(ok)); ++ for (int i = 0; i < 4; i++) if (!(m >> i & 1)) r._u32[i] = spu__fma_any(a._u32[i], b._u32[i], c._u32[i], negp, negc); ++ return r; ++} ++SPU__X4_INLINE u128 spu__x4_fa(u128 a, u128 b, uint32_t negb) { ++ const __m128i x = spu__x4_ld(a), y = _mm_xor_si128(spu__x4_ld(b), _mm_set1_epi32((int)negb)); ++ /* the exponent-gap limit applies only between two nonzero terms */ ++ const __m128i gap = _mm_cmpgt_epi32(_mm_set1_epi32(30), _mm_abs_epi32(_mm_sub_epi32(spu__x4_bexp(x), spu__x4_bexp(y)))); ++ const __m128i pre = _mm_and_si128(_mm_and_si128(spu__x4_plain0(x), spu__x4_plain0(y)), ++ _mm_or_si128(gap, _mm_or_si128(spu__x4_zero(x), spu__x4_zero(y)))); ++ __m128d xl, xh, yl, yh; spu__x4_wide(x, &xl, &xh); spu__x4_wide(y, &yl, &yh); ++ __m128i ok, zm; ++ const __m128i r = spu__x4_trunc0(_mm_add_pd(xl, yl), _mm_add_pd(xh, yh), &ok, &zm, NULL, NULL); ++ ok = _mm_and_si128(ok, pre); ++ return spu__x4_all4(ok) ? spu__x4_st(r) : spu__x4_fa_fix(spu__x4_st(r), ok, a, b, negb); ++} ++SPU__X4_INLINE u128 spu_fa(u128 a, u128 b) { return spu__x4_fa(a, b, 0); } ++SPU__X4_INLINE u128 spu_fs(u128 a, u128 b) { return spu__x4_fa(a, b, 0x80000000u); } ++SPU__X4_INLINE u128 spu_fm(u128 a, u128 b) { ++ const __m128i x = spu__x4_ld(a), y = spu__x4_ld(b); ++ __m128d xl, xh, yl, yh; spu__x4_wide(x, &xl, &xh); spu__x4_wide(y, &yl, &yh); ++ __m128i ok, zm; ++ const __m128i r = spu__x4_trunc0(_mm_mul_pd(xl, yl), _mm_mul_pd(xh, yh), &ok, &zm, NULL, NULL); ++ ok = _mm_and_si128(ok, _mm_and_si128(spu__x4_plain0(x), spu__x4_plain0(y))); ++ return spu__x4_all4(ok) ? spu__x4_st(r) : spu__x4_fm_fix(spu__x4_st(r), ok, a, b); ++} ++/* (+-a*b) + (+-c): the product is exact in double; TwoSum gives the add's exact rounding error. */ ++SPU__X4_INLINE void spu__x4_twosum(__m128d p, __m128d zz, __m128d* sum, __m128d* err) { ++ const __m128d s = _mm_add_pd(p, zz), bb = _mm_sub_pd(s, p); ++ *sum = s; ++ *err = _mm_add_pd(_mm_sub_pd(p, _mm_sub_pd(s, bb)), _mm_sub_pd(zz, bb)); ++} ++SPU__X4_INLINE u128 spu__x4_fma(u128 a, u128 b, u128 c, uint32_t negp, uint32_t negc) { ++ const __m128i x = _mm_xor_si128(spu__x4_ld(a), _mm_set1_epi32((int)negp)), y = spu__x4_ld(b); ++ const __m128i z = _mm_xor_si128(spu__x4_ld(c), _mm_set1_epi32((int)negc)); ++ __m128d xl, xh, yl, yh, zl, zh; spu__x4_wide(x, &xl, &xh); spu__x4_wide(y, &yl, &yh); spu__x4_wide(z, &zl, &zh); ++ __m128d sl, sh, el, eh; ++ spu__x4_twosum(_mm_mul_pd(xl, yl), zl, &sl, &el); ++ spu__x4_twosum(_mm_mul_pd(xh, yh), zh, &sh, &eh); ++ __m128i ok, zm; ++ const __m128i r = spu__x4_trunc0(sl, sh, &ok, &zm, &el, &eh); ++ ok = _mm_and_si128(ok, _mm_and_si128(_mm_and_si128(spu__x4_plain0(x), spu__x4_plain0(y)), spu__x4_plain0(z))); ++ return spu__x4_all4(ok) ? spu__x4_st(r) : spu__x4_fma_fix(spu__x4_st(r), ok, a, b, c, negp, negc); ++} ++SPU__X4_INLINE u128 spu_fma(u128 a, u128 b, u128 c) { return spu__x4_fma(a, b, c, 0, 0); } /* a*b + c */ ++SPU__X4_INLINE u128 spu_fms(u128 a, u128 b, u128 c) { return spu__x4_fma(a, b, c, 0, 0x80000000u); } /* a*b - c */ ++SPU__X4_INLINE u128 spu_fnms(u128 a, u128 b, u128 c) { return spu__x4_fma(a, b, c, 0x80000000u, 0); } /* c - a*b */ + #else + static inline u128 spu_fa(u128 a, u128 b) { return spu__fa_s(a, b); } + static inline u128 spu_fs(u128 a, u128 b) { return spu__fs_s(a, b); } +diff --git a/runtime/spu/tests/test_spu_float_exact.c b/runtime/spu/tests/test_spu_float_exact.c +index a3d19d70..d9719439 100644 +--- a/runtime/spu/tests/test_spu_float_exact.c ++++ b/runtime/spu/tests/test_spu_float_exact.c +@@ -9,7 +9,7 @@ + * 3. random vectors from a mix of generators aimed at the hard spots: results near 2^-126 and + * 2^128, cancellation in fa/fs and fma (z close to -x*y), fma sums rounded onto a 24-bit + * boundary, wide exponent gaps, zeros of every kind, extended-range words, raw words. +- * Build (arm64, or x86 with -mavx2 -mfma): ++ * Build (arm64; x86 with -msse4.1 for the SSE4.1 form, or -mavx2 -mfma for the AVX2 form): + * cc -O2 -I runtime/spu -I include runtime/spu/tests/test_spu_float_exact.c -lm -o t && ./t [scale] + * scale (default 1) multiplies the pass-3 size: 1 = 64M vectors (256M lanes). */ + #include "spu_helpers.h" +diff --git a/runtime/spu/tests/test_spu_float_vector_scalar.c b/runtime/spu/tests/test_spu_float_vector_scalar.c +new file mode 100644 +index 00000000..547d5616 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_float_vector_scalar.c +@@ -0,0 +1,86 @@ ++/* The vector single-precision ops this build selects (spu_fa/fs/fm/fma/fms/fnms: the SSE4.1, AVX2 ++ * or NEON form) against the scalar per-lane forms (spu__*_s: scalar fast path, else exact), lane ++ * by lane and bit for bit. test_spu_float_exact compares both against the exact references; this ++ * one is the direct differential check between the two code paths a build can take. ++ * Lanes are drawn from SPU edge words (+-0, words with biased exponent 0 and a fraction, the ++ * smallest normal, the largest IEEE-finite word, extended-range words of biased exponent 255, ++ * Smax), random normal values in a narrow and a wide exponent window, values whose product or ++ * sum lands near 2^-126 or 2^128, fma addends close to -x*y, and raw random words; each vector ++ * mixes generators per lane so that a vector with one odd lane still takes the fix-up path. ++ * Build: cc -O2 -msse4.1 -ffp-contract=off -I runtime/spu -I include THIS -lm -o t && ./t [millions] */ ++#include "spu_helpers.h" ++#include <stdio.h> ++#include <stdlib.h> ++ ++static uint64_t s_rng = 0x9E3779B97F4A7C15ull; ++static inline uint32_t rnd32(void) ++{ ++ s_rng ^= s_rng << 13; s_rng ^= s_rng >> 7; s_rng ^= s_rng << 17; ++ return (uint32_t)(s_rng >> 16); ++} ++static const uint32_t k_edge[] = { ++ 0x00000000u, 0x80000000u, 0x00000001u, 0x807FFFFFu, 0x00400000u, 0x00800000u, 0x80800000u, ++ 0x00800001u, 0x3F800000u, 0xBF800000u, 0x3F7FFFFFu, 0x3F800001u, 0x7F7FFFFFu, 0xFF7FFFFFu, ++ 0x7F000000u, 0x7F800000u, 0xFF800000u, 0x7FC00000u, 0x7F800001u, 0x7FFFFFFFu, 0xFFFFFFFFu, ++ 0x01000000u, 0x00FFFFFFu, 0x4B000000u, 0x4B7FFFFFu, 0x33800000u, 0x34000000u, 0x5F800000u, ++ 0x1F800000u, 0x20000000u, 0x60000000u, ++}; ++#define NEDGE (sizeof k_edge / sizeof k_edge[0]) ++static uint32_t word(uint32_t z) ++{ ++ const uint32_t sign = rnd32() & 0x80000000u; ++ switch (rnd32() % 9) { ++ case 0: return k_edge[rnd32() % NEDGE] ^ (rnd32() & 0x80000000u); ++ case 1: return sign | ((100u + rnd32() % 56u) << 23) | (rnd32() & 0x7FFFFFu); /* narrow window */ ++ case 2: return sign | ((1u + rnd32() % 254u) << 23) | (rnd32() & 0x7FFFFFu); /* any normal */ ++ case 3: return sign | ((rnd32() % 2u ? 255u : 0u) << 23) | (rnd32() & 0x7FFFFFu); /* exp 0 / 255 */ ++ case 4: return sign | ((1u + rnd32() % 4u) << 23) | (rnd32() & 0x7FFFFFu); /* near 2^-126 */ ++ case 5: return sign | ((250u + rnd32() % 6u) << 23) | (rnd32() & 0x7FFFFFu); /* near 2^128 */ ++ case 6: return z ? (z ^ 0x80000000u) + (rnd32() % 5u) - 2u : rnd32(); /* cancellation */ ++ case 7: return sign | ((63u + rnd32() % 2u) << 23) | (rnd32() & 0x7FFFFFu); /* products near 2^-126 */ ++ default: return rnd32(); ++ } ++} ++static long s_bad, s_lanes; ++static const char* const k_ops[6] = { "fa", "fs", "fm", "fma", "fms", "fnms" }; ++static void check(int op, u128 a, u128 b, u128 c) ++{ ++ u128 got, ref; ++ switch (op) { ++ case 0: got = spu_fa(a, b); ref = spu__fa_s(a, b); break; ++ case 1: got = spu_fs(a, b); ref = spu__fs_s(a, b); break; ++ case 2: got = spu_fm(a, b); ref = spu__fm_s(a, b); break; ++ case 3: got = spu_fma(a, b, c); ref = spu__fma_s(a, b, c); break; ++ case 4: got = spu_fms(a, b, c); ref = spu__fms_s(a, b, c); break; ++ default: got = spu_fnms(a, b, c); ref = spu__fnms_s(a, b, c); break; ++ } ++ s_lanes += 4; ++ for (int i = 0; i < 4; i++) ++ if (got._u32[i] != ref._u32[i] && s_bad++ < 20) ++ printf("MISMATCH %s a=%08X b=%08X c=%08X vector=%08X scalar=%08X\n", k_ops[op], ++ a._u32[i], b._u32[i], c._u32[i], got._u32[i], ref._u32[i]); ++} ++int main(int argc, char** argv) ++{ ++ const long millions = argc > 1 ? atol(argv[1]) : 16; ++ /* every pair of edge words in every lane position */ ++ for (unsigned i = 0; i < NEDGE; i++) for (unsigned j = 0; j < NEDGE; j++) for (unsigned k = 0; k < NEDGE; k++) { ++ u128 a, b, c; ++ for (int l = 0; l < 4; l++) { ++ a._u32[l] = k_edge[(i + l) % NEDGE]; b._u32[l] = k_edge[(j + 3 * l) % NEDGE]; c._u32[l] = k_edge[(k + 5 * l) % NEDGE]; ++ } ++ for (int op = 0; op < 6; op++) check(op, a, b, c); ++ } ++ for (long n = 0; n < millions * 1000000L; n++) { ++ u128 a, b, c; ++ for (int l = 0; l < 4; l++) { ++ a._u32[l] = word(0); b._u32[l] = word(0); ++ /* for fma, an addend close to -a*b in the cancellation generator */ ++ const u128 one = { ._u32 = { a._u32[l], 0, 0, 0 } }, two = { ._u32 = { b._u32[l], 0, 0, 0 } }; ++ c._u32[l] = word(spu__fm_s(one, two)._u32[0]); ++ } ++ check((int)(n % 6), a, b, c); ++ } ++ printf("test_spu_float_vector_scalar: %ld lanes, %ld mismatches\n", s_lanes, s_bad); ++ return s_bad != 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-683/solution/solve.sh b/tasks/sp00nznet__ps3recomp-683/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-683/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-683/task.toml b/tasks/sp00nznet__ps3recomp-683/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4ce65a9772fd440b61102dda02dac0e01a62e39e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-683/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-683" +description = "perf(spu): four-lane SSE4.1 form of the single-precision helpers" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/683" +source_access = "auto" +built_at = "2026-11-16T16:09:59.715061+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ea60d38b40ff954c74b63df332946a201612580689e3c080239cb73ad35dfa48" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + ".github/workflows/linux.yml", + "CMakeLists.txt", + "runtime/spu/spu_helpers.h", + "runtime/spu/tests/test_spu_float_exact.c", + "runtime/spu/tests/test_spu_float_vector_scalar.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 230 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.155340+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-683/tests/capture.py b/tasks/sp00nznet__ps3recomp-683/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-683/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-683/tests/instruction.md b/tasks/sp00nznet__ps3recomp-683/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e73f8025c656ff5adc9020b062069e1e17ffcb1 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-683/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** perf(spu): four-lane SSE4.1 form of the single-precision helpers + +## Description + +x86 builds without AVX2 (the default `-msse4.1` runtime) ran `spu_fa`/`fs`/`fm`/`fma`/`fms`/`fnms` one lane at a time through the scalar fast path. Those helpers topped a Linux profile of a title's SPU work. + +**Change:** a new `#elif defined(__SSE4_1__)` branch after the AVX2 form in `spu_helpers.h`. It applies the AVX2 form's lane rules word for word, with each f64x4 step done as two f64x2 halves. Each half widens exactly, operates, clears the 29 low significand bits and narrows exactly. A lane keeps the vector result only where it is provably the truncated SPU result: ordinary single or true-zero operands, the exponent gap for adds, a normal-range result, and the TwoSum boundary check for fma. Every other lane is redone by the existing per-lane path. SSE4.1 has no FMA instruction, so nothing can be contracted. 64-bit ordered compares are SSE4.2, so the exponent range checks narrow to 32-bit lanes first. The NEON and AVX2 forms and the scalar fallback are unchanged; AVX2 builds still take the AVX2 form. + +**Tests (synthetic):** +- New `test_spu_float_vector_scalar` compares the selected vector form with the scalar per-lane forms (`spu__*_s`) bit for bit. It covers every edge-word triple (+-0, biased exponent 0 with fractions, smallest normal, largest finite, biased exponent 255, Smax) and random lanes aimed at 2^-126/2^128, cancellation and wide gaps. It is registered with ctest next to `test_spu_float_exact`, and the new CI step runs both. +- On x86, both float tests build with `-msse4.1 -ffp-contract=off` when `PS3RECOMP_HAS_MSSE41`, so the SSE4.1 form is the one under test, as it is in the runtime. + +Results: +- Ryzen 7800X3D (Linux), measured by the author: 96.7M lanes against scalar and 446.8M lanes against the exact references, 0 mismatches, for both the SSE4.1 and the AVX2 forms. Time per vector: `fa` 10.9 -> 5.7 ns, `fm` 9.3 -> 2.8 ns, `fma` 11.2 -> 5.3 ns. +- Apple M4 Pro, x86_64 build with `-msse4.1 -ffp-contract=off` under Rosetta 2 (the preprocessed source confirms the SSE4.1 branch is the one selected): `test_spu_float_vector_scalar 4` gives 16.7M lanes with 0 mismatches, and `test_spu_float_exact` gives 446,840,832 lanes, bit-identical. +- Native arm64 (NEON form): both tests pass, also through `ctest`. +- Linux CI did not build either float test, so a second commit (`ci:`) adds a `linux.yml` step that builds and runs both with `-msse4.1 -ffp-contract=off`. On the fork, all four Linux jobs (gcc and clang, Debug and Release) report `16714984 lanes, 0 mismatches` and `446840832 lanes bit-identical` ([fork run](https://github.com/tekulvw/ps3recomp/actions/runs/41774752970)). + +Related: #678 makes the probed `-msse4.1` PUBLIC, so lifted code that includes these helpers also gets this form. This PR doesn't depend on it. + +Based on master `4e8f3ca8`. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-683/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-683/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0b10f16b49557c82786ce1c675c4f1ac5e15dd46 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-683/tests/oracle.patch @@ -0,0 +1,280 @@ +diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml +index 99c0b20c..22ee81f0 100644 +--- a/.github/workflows/linux.yml ++++ b/.github/workflows/linux.yml +@@ -117,6 +117,18 @@ jobs: + echo "no AVX2 on this runner: skipped" + fi + ++ # The SSE4.1 single-precision form (the default x86-64 build) against the scalar per-lane ++ # forms and against the exact references, bit for bit, built as the runtime is. ++ - name: Run the SPU float vector tests (SSE4.1) ++ run: | ++ for t in test_spu_float_vector_scalar test_spu_float_exact; do ++ ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} \ ++ -std=gnu17 -O2 -msse4.1 -ffp-contract=off -UNDEBUG -I include -I runtime/spu \ ++ -o /tmp/${t}_sse41 runtime/spu/tests/$t.c -lm ++ done ++ /tmp/test_spu_float_vector_scalar_sse41 4 ++ /tmp/test_spu_float_exact_sse41 ++ + # runtime/spu/tests/test_spu_int_x86.c checks #512's SSE4.1 and AVX2 integer + # and quadword-shift forms against their scalar spu_X_ref references. #512 + # added the file and wired it into nothing -- no workflow step, no CMake +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..02a16013 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -416,6 +416,20 @@ if(PS3RECOMP_BUILD_TESTS) + target_link_libraries(test_spu_float_exact PRIVATE m) + add_test(NAME spu_float_exact COMMAND test_spu_float_exact) + set_tests_properties(spu_float_exact PROPERTIES TIMEOUT 300) ++ # The vector forms against the scalar per-lane forms, directly. ++ add_executable(test_spu_float_vector_scalar ++ runtime/spu/tests/test_spu_float_vector_scalar.c) ++ target_include_directories(test_spu_float_vector_scalar PRIVATE include runtime/spu) ++ target_compile_options(test_spu_float_vector_scalar PRIVATE -UNDEBUG) ++ target_link_libraries(test_spu_float_vector_scalar PRIVATE m) ++ add_test(NAME spu_float_vector_scalar COMMAND test_spu_float_vector_scalar 4) ++ set_tests_properties(spu_float_vector_scalar PROPERTIES TIMEOUT 300) ++ # On x86 both take the ISA the runtime and lifted code are built for, so the SSE4.1 ++ # vector form is the one under test; no contraction, as in the runtime. ++ if(PS3RECOMP_HAS_MSSE41) ++ target_compile_options(test_spu_float_exact PRIVATE -msse4.1 -ffp-contract=off) ++ target_compile_options(test_spu_float_vector_scalar PRIVATE -msse4.1 -ffp-contract=off) ++ endif() + + add_executable(test_spu_lockline_wait + runtime/spu/tests/test_spu_lockline_wait.c) +diff --git a/runtime/spu/spu_helpers.h b/runtime/spu/spu_helpers.h +index f04fda63..d6f1fa2c 100644 +--- a/runtime/spu/spu_helpers.h ++++ b/runtime/spu/spu_helpers.h +@@ -1129,6 +1129,122 @@ SPU__X8_INLINE u128 spu__x8_fma(u128 a, u128 b, u128 c, uint32_t negp, uint32_t + SPU__X8_INLINE u128 spu_fma(u128 a, u128 b, u128 c) { return spu__x8_fma(a, b, c, 0, 0); } /* a*b + c */ + SPU__X8_INLINE u128 spu_fms(u128 a, u128 b, u128 c) { return spu__x8_fma(a, b, c, 0, 0x80000000u); } /* a*b - c */ + SPU__X8_INLINE u128 spu_fnms(u128 a, u128 b, u128 c) { return spu__x8_fma(a, b, c, 0x80000000u, 0); } /* c - a*b */ ++#elif defined(__SSE4_1__) && !defined(SPU_SCALAR_HELPERS) ++/* The AVX2 form above with SSE4.1 only (the default x86-64 build), each f64x4 step done as two ++ * f64x2 halves: lanes 0-1 and lanes 2-3 widened exactly, the same operation, the 29 low ++ * significand bits cleared, narrowed exactly. The lane rules are the AVX2 ones word for word, so a ++ * lane takes the vector result only where that result is provably the exact truncation, and ++ * every other lane is redone by the per-lane path (spu__*_any). There is no FMA instruction here, ++ * so nothing can be contracted; the double product of two 24-bit significands is exact anyway. ++ * 64-bit compares other than equality are SSE4.2, so exponent range checks narrow the double ++ * exponents to 32-bit lanes first. */ ++#include <smmintrin.h> ++#define SPU__X4_INLINE static inline __attribute__((always_inline)) ++#define SPU__X4_SLOW static __attribute__((noinline, cold, unused)) ++SPU__X4_INLINE __m128i spu__x4_bexp(__m128i x) { return _mm_srli_epi32(_mm_slli_epi32(x, 1), 24); } ++SPU__X4_INLINE __m128i spu__x4_zero(__m128i x) { return _mm_cmpeq_epi32(_mm_slli_epi32(x, 1), _mm_setzero_si128()); } ++SPU__X4_INLINE __m128i spu__x4_plain0(__m128i x) { /* biased exponent 1..254, or +-0 */ ++ const __m128i e = spu__x4_bexp(x); ++ return _mm_or_si128(_mm_and_si128(_mm_cmpgt_epi32(e, _mm_setzero_si128()), _mm_cmpgt_epi32(_mm_set1_epi32(255), e)), ++ spu__x4_zero(x)); ++} ++/* the four singles widened to doubles: lanes 0-1 in *lo, lanes 2-3 in *hi (exact) */ ++SPU__X4_INLINE void spu__x4_wide(__m128i x, __m128d* lo, __m128d* hi) { ++ const __m128 f = _mm_castsi128_ps(x); ++ *lo = _mm_cvtps_pd(f); *hi = _mm_cvtps_pd(_mm_movehl_ps(f, f)); ++} ++/* the low 32 bits of each 64-bit lane of lo:hi, as four 32-bit lanes 0..3 */ ++SPU__X4_INLINE __m128i spu__x4_narrow(__m128i lo, __m128i hi) { ++ return _mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(lo), _mm_castsi128_ps(hi), _MM_SHUFFLE(2, 0, 2, 0))); ++} ++/* lo:hi truncated to singles. *ok: lanes whose result is a normal single or an exact zero and, ++ * when err is given, did not both round and land on a 24-bit boundary. *zm: the zero lanes. */ ++SPU__X4_INLINE __m128i spu__x4_trunc0(__m128d dlo, __m128d dhi, __m128i* ok, __m128i* zm, ++ const __m128d* elo, const __m128d* ehi) { ++ const __m128i ulo = _mm_castpd_si128(dlo), uhi = _mm_castpd_si128(dhi); ++ const __m128i az = spu__x4_narrow(_mm_cmpeq_epi64(_mm_slli_epi64(ulo, 1), _mm_setzero_si128()), ++ _mm_cmpeq_epi64(_mm_slli_epi64(uhi, 1), _mm_setzero_si128())); ++ /* biased double exponent, 0..2047, per lane; a normal single needs it in 1023-126..1023+127 */ ++ const __m128i be = _mm_and_si128(spu__x4_narrow(_mm_srli_epi64(ulo, 52), _mm_srli_epi64(uhi, 52)), _mm_set1_epi32(0x7FF)); ++ __m128i good = _mm_andnot_si128(_mm_or_si128(_mm_cmpgt_epi32(_mm_set1_epi32(1023 - 126), be), ++ _mm_cmpgt_epi32(be, _mm_set1_epi32(1023 + 127))), ++ _mm_set1_epi32(-1)); ++ if (elo) { ++ const __m128i low = _mm_set1_epi64x(0x1FFFFFFF); ++ const __m128i bnd = spu__x4_narrow(_mm_cmpeq_epi64(_mm_and_si128(ulo, low), _mm_setzero_si128()), ++ _mm_cmpeq_epi64(_mm_and_si128(uhi, low), _mm_setzero_si128())); ++ const __m128i rnd = spu__x4_narrow(_mm_castpd_si128(_mm_cmpneq_pd(*elo, _mm_setzero_pd())), ++ _mm_castpd_si128(_mm_cmpneq_pd(*ehi, _mm_setzero_pd()))); ++ good = _mm_andnot_si128(_mm_and_si128(bnd, rnd), good); ++ } ++ *ok = _mm_or_si128(good, az); ++ *zm = az; ++ const __m128i keep = _mm_set1_epi64x(~0x1FFFFFFFll); ++ const __m128 t = _mm_movelh_ps(_mm_cvtpd_ps(_mm_castsi128_pd(_mm_and_si128(ulo, keep))), ++ _mm_cvtpd_ps(_mm_castsi128_pd(_mm_and_si128(uhi, keep)))); ++ return _mm_andnot_si128(_mm_and_si128(az, _mm_set1_epi32((int)0x80000000u)), _mm_castps_si128(t)); ++} ++SPU__X4_INLINE int spu__x4_all4(__m128i m) { return _mm_movemask_ps(_mm_castsi128_ps(m)) == 0xF; } ++SPU__X4_INLINE __m128i spu__x4_ld(u128 a) { return _mm_loadu_si128((const __m128i*)a._u32); } ++SPU__X4_INLINE u128 spu__x4_st(__m128i v) { u128 r; _mm_storeu_si128((__m128i*)r._u32, v); return r; } ++SPU__X4_SLOW u128 spu__x4_fa_fix(u128 r, __m128i ok, u128 a, u128 b, uint32_t negb) { ++ const int m = _mm_movemask_ps(_mm_castsi128_ps(ok)); ++ for (int i = 0; i < 4; i++) if (!(m >> i & 1)) r._u32[i] = spu__fa_any(a._u32[i], b._u32[i] ^ negb); ++ return r; ++} ++SPU__X4_SLOW u128 spu__x4_fm_fix(u128 r, __m128i ok, u128 a, u128 b) { ++ const int m = _mm_movemask_ps(_mm_castsi128_ps(ok)); ++ for (int i = 0; i < 4; i++) if (!(m >> i & 1)) r._u32[i] = spu__fm_any(a._u32[i], b._u32[i]); ++ return r; ++} ++SPU__X4_SLOW u128 spu__x4_fma_fix(u128 r, __m128i ok, u128 a, u128 b, u128 c, uint32_t negp, uint32_t negc) { ++ const int m = _mm_movemask_ps(_mm_castsi128_ps(ok)); ++ for (int i = 0; i < 4; i++) if (!(m >> i & 1)) r._u32[i] = spu__fma_any(a._u32[i], b._u32[i], c._u32[i], negp, negc); ++ return r; ++} ++SPU__X4_INLINE u128 spu__x4_fa(u128 a, u128 b, uint32_t negb) { ++ const __m128i x = spu__x4_ld(a), y = _mm_xor_si128(spu__x4_ld(b), _mm_set1_epi32((int)negb)); ++ /* the exponent-gap limit applies only between two nonzero terms */ ++ const __m128i gap = _mm_cmpgt_epi32(_mm_set1_epi32(30), _mm_abs_epi32(_mm_sub_epi32(spu__x4_bexp(x), spu__x4_bexp(y)))); ++ const __m128i pre = _mm_and_si128(_mm_and_si128(spu__x4_plain0(x), spu__x4_plain0(y)), ++ _mm_or_si128(gap, _mm_or_si128(spu__x4_zero(x), spu__x4_zero(y)))); ++ __m128d xl, xh, yl, yh; spu__x4_wide(x, &xl, &xh); spu__x4_wide(y, &yl, &yh); ++ __m128i ok, zm; ++ const __m128i r = spu__x4_trunc0(_mm_add_pd(xl, yl), _mm_add_pd(xh, yh), &ok, &zm, NULL, NULL); ++ ok = _mm_and_si128(ok, pre); ++ return spu__x4_all4(ok) ? spu__x4_st(r) : spu__x4_fa_fix(spu__x4_st(r), ok, a, b, negb); ++} ++SPU__X4_INLINE u128 spu_fa(u128 a, u128 b) { return spu__x4_fa(a, b, 0); } ++SPU__X4_INLINE u128 spu_fs(u128 a, u128 b) { return spu__x4_fa(a, b, 0x80000000u); } ++SPU__X4_INLINE u128 spu_fm(u128 a, u128 b) { ++ const __m128i x = spu__x4_ld(a), y = spu__x4_ld(b); ++ __m128d xl, xh, yl, yh; spu__x4_wide(x, &xl, &xh); spu__x4_wide(y, &yl, &yh); ++ __m128i ok, zm; ++ const __m128i r = spu__x4_trunc0(_mm_mul_pd(xl, yl), _mm_mul_pd(xh, yh), &ok, &zm, NULL, NULL); ++ ok = _mm_and_si128(ok, _mm_and_si128(spu__x4_plain0(x), spu__x4_plain0(y))); ++ return spu__x4_all4(ok) ? spu__x4_st(r) : spu__x4_fm_fix(spu__x4_st(r), ok, a, b); ++} ++/* (+-a*b) + (+-c): the product is exact in double; TwoSum gives the add's exact rounding error. */ ++SPU__X4_INLINE void spu__x4_twosum(__m128d p, __m128d zz, __m128d* sum, __m128d* err) { ++ const __m128d s = _mm_add_pd(p, zz), bb = _mm_sub_pd(s, p); ++ *sum = s; ++ *err = _mm_add_pd(_mm_sub_pd(p, _mm_sub_pd(s, bb)), _mm_sub_pd(zz, bb)); ++} ++SPU__X4_INLINE u128 spu__x4_fma(u128 a, u128 b, u128 c, uint32_t negp, uint32_t negc) { ++ const __m128i x = _mm_xor_si128(spu__x4_ld(a), _mm_set1_epi32((int)negp)), y = spu__x4_ld(b); ++ const __m128i z = _mm_xor_si128(spu__x4_ld(c), _mm_set1_epi32((int)negc)); ++ __m128d xl, xh, yl, yh, zl, zh; spu__x4_wide(x, &xl, &xh); spu__x4_wide(y, &yl, &yh); spu__x4_wide(z, &zl, &zh); ++ __m128d sl, sh, el, eh; ++ spu__x4_twosum(_mm_mul_pd(xl, yl), zl, &sl, &el); ++ spu__x4_twosum(_mm_mul_pd(xh, yh), zh, &sh, &eh); ++ __m128i ok, zm; ++ const __m128i r = spu__x4_trunc0(sl, sh, &ok, &zm, &el, &eh); ++ ok = _mm_and_si128(ok, _mm_and_si128(_mm_and_si128(spu__x4_plain0(x), spu__x4_plain0(y)), spu__x4_plain0(z))); ++ return spu__x4_all4(ok) ? spu__x4_st(r) : spu__x4_fma_fix(spu__x4_st(r), ok, a, b, c, negp, negc); ++} ++SPU__X4_INLINE u128 spu_fma(u128 a, u128 b, u128 c) { return spu__x4_fma(a, b, c, 0, 0); } /* a*b + c */ ++SPU__X4_INLINE u128 spu_fms(u128 a, u128 b, u128 c) { return spu__x4_fma(a, b, c, 0, 0x80000000u); } /* a*b - c */ ++SPU__X4_INLINE u128 spu_fnms(u128 a, u128 b, u128 c) { return spu__x4_fma(a, b, c, 0x80000000u, 0); } /* c - a*b */ + #else + static inline u128 spu_fa(u128 a, u128 b) { return spu__fa_s(a, b); } + static inline u128 spu_fs(u128 a, u128 b) { return spu__fs_s(a, b); } +diff --git a/runtime/spu/tests/test_spu_float_exact.c b/runtime/spu/tests/test_spu_float_exact.c +index a3d19d70..d9719439 100644 +--- a/runtime/spu/tests/test_spu_float_exact.c ++++ b/runtime/spu/tests/test_spu_float_exact.c +@@ -9,7 +9,7 @@ + * 3. random vectors from a mix of generators aimed at the hard spots: results near 2^-126 and + * 2^128, cancellation in fa/fs and fma (z close to -x*y), fma sums rounded onto a 24-bit + * boundary, wide exponent gaps, zeros of every kind, extended-range words, raw words. +- * Build (arm64, or x86 with -mavx2 -mfma): ++ * Build (arm64; x86 with -msse4.1 for the SSE4.1 form, or -mavx2 -mfma for the AVX2 form): + * cc -O2 -I runtime/spu -I include runtime/spu/tests/test_spu_float_exact.c -lm -o t && ./t [scale] + * scale (default 1) multiplies the pass-3 size: 1 = 64M vectors (256M lanes). */ + #include "spu_helpers.h" +diff --git a/runtime/spu/tests/test_spu_float_vector_scalar.c b/runtime/spu/tests/test_spu_float_vector_scalar.c +new file mode 100644 +index 00000000..547d5616 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_float_vector_scalar.c +@@ -0,0 +1,86 @@ ++/* The vector single-precision ops this build selects (spu_fa/fs/fm/fma/fms/fnms: the SSE4.1, AVX2 ++ * or NEON form) against the scalar per-lane forms (spu__*_s: scalar fast path, else exact), lane ++ * by lane and bit for bit. test_spu_float_exact compares both against the exact references; this ++ * one is the direct differential check between the two code paths a build can take. ++ * Lanes are drawn from SPU edge words (+-0, words with biased exponent 0 and a fraction, the ++ * smallest normal, the largest IEEE-finite word, extended-range words of biased exponent 255, ++ * Smax), random normal values in a narrow and a wide exponent window, values whose product or ++ * sum lands near 2^-126 or 2^128, fma addends close to -x*y, and raw random words; each vector ++ * mixes generators per lane so that a vector with one odd lane still takes the fix-up path. ++ * Build: cc -O2 -msse4.1 -ffp-contract=off -I runtime/spu -I include THIS -lm -o t && ./t [millions] */ ++#include "spu_helpers.h" ++#include <stdio.h> ++#include <stdlib.h> ++ ++static uint64_t s_rng = 0x9E3779B97F4A7C15ull; ++static inline uint32_t rnd32(void) ++{ ++ s_rng ^= s_rng << 13; s_rng ^= s_rng >> 7; s_rng ^= s_rng << 17; ++ return (uint32_t)(s_rng >> 16); ++} ++static const uint32_t k_edge[] = { ++ 0x00000000u, 0x80000000u, 0x00000001u, 0x807FFFFFu, 0x00400000u, 0x00800000u, 0x80800000u, ++ 0x00800001u, 0x3F800000u, 0xBF800000u, 0x3F7FFFFFu, 0x3F800001u, 0x7F7FFFFFu, 0xFF7FFFFFu, ++ 0x7F000000u, 0x7F800000u, 0xFF800000u, 0x7FC00000u, 0x7F800001u, 0x7FFFFFFFu, 0xFFFFFFFFu, ++ 0x01000000u, 0x00FFFFFFu, 0x4B000000u, 0x4B7FFFFFu, 0x33800000u, 0x34000000u, 0x5F800000u, ++ 0x1F800000u, 0x20000000u, 0x60000000u, ++}; ++#define NEDGE (sizeof k_edge / sizeof k_edge[0]) ++static uint32_t word(uint32_t z) ++{ ++ const uint32_t sign = rnd32() & 0x80000000u; ++ switch (rnd32() % 9) { ++ case 0: return k_edge[rnd32() % NEDGE] ^ (rnd32() & 0x80000000u); ++ case 1: return sign | ((100u + rnd32() % 56u) << 23) | (rnd32() & 0x7FFFFFu); /* narrow window */ ++ case 2: return sign | ((1u + rnd32() % 254u) << 23) | (rnd32() & 0x7FFFFFu); /* any normal */ ++ case 3: return sign | ((rnd32() % 2u ? 255u : 0u) << 23) | (rnd32() & 0x7FFFFFu); /* exp 0 / 255 */ ++ case 4: return sign | ((1u + rnd32() % 4u) << 23) | (rnd32() & 0x7FFFFFu); /* near 2^-126 */ ++ case 5: return sign | ((250u + rnd32() % 6u) << 23) | (rnd32() & 0x7FFFFFu); /* near 2^128 */ ++ case 6: return z ? (z ^ 0x80000000u) + (rnd32() % 5u) - 2u : rnd32(); /* cancellation */ ++ case 7: return sign | ((63u + rnd32() % 2u) << 23) | (rnd32() & 0x7FFFFFu); /* products near 2^-126 */ ++ default: return rnd32(); ++ } ++} ++static long s_bad, s_lanes; ++static const char* const k_ops[6] = { "fa", "fs", "fm", "fma", "fms", "fnms" }; ++static void check(int op, u128 a, u128 b, u128 c) ++{ ++ u128 got, ref; ++ switch (op) { ++ case 0: got = spu_fa(a, b); ref = spu__fa_s(a, b); break; ++ case 1: got = spu_fs(a, b); ref = spu__fs_s(a, b); break; ++ case 2: got = spu_fm(a, b); ref = spu__fm_s(a, b); break; ++ case 3: got = spu_fma(a, b, c); ref = spu__fma_s(a, b, c); break; ++ case 4: got = spu_fms(a, b, c); ref = spu__fms_s(a, b, c); break; ++ default: got = spu_fnms(a, b, c); ref = spu__fnms_s(a, b, c); break; ++ } ++ s_lanes += 4; ++ for (int i = 0; i < 4; i++) ++ if (got._u32[i] != ref._u32[i] && s_bad++ < 20) ++ printf("MISMATCH %s a=%08X b=%08X c=%08X vector=%08X scalar=%08X\n", k_ops[op], ++ a._u32[i], b._u32[i], c._u32[i], got._u32[i], ref._u32[i]); ++} ++int main(int argc, char** argv) ++{ ++ const long millions = argc > 1 ? atol(argv[1]) : 16; ++ /* every pair of edge words in every lane position */ ++ for (unsigned i = 0; i < NEDGE; i++) for (unsigned j = 0; j < NEDGE; j++) for (unsigned k = 0; k < NEDGE; k++) { ++ u128 a, b, c; ++ for (int l = 0; l < 4; l++) { ++ a._u32[l] = k_edge[(i + l) % NEDGE]; b._u32[l] = k_edge[(j + 3 * l) % NEDGE]; c._u32[l] = k_edge[(k + 5 * l) % NEDGE]; ++ } ++ for (int op = 0; op < 6; op++) check(op, a, b, c); ++ } ++ for (long n = 0; n < millions * 1000000L; n++) { ++ u128 a, b, c; ++ for (int l = 0; l < 4; l++) { ++ a._u32[l] = word(0); b._u32[l] = word(0); ++ /* for fma, an addend close to -a*b in the cancellation generator */ ++ const u128 one = { ._u32 = { a._u32[l], 0, 0, 0 } }, two = { ._u32 = { b._u32[l], 0, 0, 0 } }; ++ c._u32[l] = word(spu__fm_s(one, two)._u32[0]); ++ } ++ check((int)(n % 6), a, b, c); ++ } ++ printf("test_spu_float_vector_scalar: %ld lanes, %ld mismatches\n", s_lanes, s_bad); ++ return s_bad != 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-683/tests/test.sh b/tasks/sp00nznet__ps3recomp-683/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-683/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-683/tests/verifier.py b/tasks/sp00nznet__ps3recomp-683/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-683/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-684/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-684/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-684/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-684/instruction.md b/tasks/sp00nznet__ps3recomp-684/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6691fb2c3b995b14affd6740da66573f3bb7fdc6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-684/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** ppu_sysprx: contended sys_lwmutex_trylock returns CELL_EBUSY + +## Description + +<!-- claude-projects-attribution: {"github_login":"ohkora"} --> +_Requested by **Lord Ohkora** · [project thread](https://claude.ai/code/project/chan_01YNDsm4WrszcKxHit3d9xbn?thread=cmsg_01YNDsm4WrszcKxHit3d9xbnD2a41kJSws2uhdfYuMM6sN)_ + +## Why + +`sys_lwmutex_trylock` in `runtime/ppu/ppu_sysprx.cpp` answers a contended trylock with `0x8001000B` (`CELL_ETIMEDOUT`), even though the comment beside it says `// EBUSY`. lv2 returns `CELL_EBUSY` (`0x8001000A`) when another thread holds the mutex. `ETIMEDOUT` is for a lock whose timeout expired, which `sys_lwmutex_lock` already returns correctly. + +Titles that poll with trylock and check for EBUSY treat the wrong code as a hard failure. PlayStation All-Stars Battle Royale (BCUS98472) is one. Its FIOS layer logs this on every contended poll of the mutex its disc reads share: + +``` +sys_lwmutex_trylock failed on mutex 'dearchiver_opticalFunnel': -2147418101 (operation timed out) +``` + +With this change the message is gone. + +## What changed + +- Contended `sys_lwmutex_trylock` returns `CELL_EBUSY`. The uncontended and recursive paths are unchanged. +- New `tools/test_lwmutex_trylock_busy.py`, in the style of `test_lwcond_layout.py`. It pulls the real handler and its `LWM_*` definitions out of `ppu_sysprx.cpp`, builds them over stub guest memory, and checks that: + - a free mutex is acquired; + - a second thread's trylock gets `CELL_EBUSY`; + - the holder's owner and recursion count are left alone. + +## Test evidence + +- New test on master: fails with `thread B gets CELL_EBUSY (ret 0x8001000B) -- that is CELL_ETIMEDOUT`. +- New test with this change: passes. +- The full `tools/test_*.py` suite passes on Linux (gcc 13.3.0). +- In a BCUS98472 port built with clang-cl on Windows, on the older 39e4f49 base, the FIOS trylock failures stop with this change. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +https://claude.ai/code/session_01B1FjNpGqw84TCo218ynPKH + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-684/solution/patch.diff b/tasks/sp00nznet__ps3recomp-684/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4377b1185e70048f1e4ed60998b86617334b95e8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-684/solution/patch.diff @@ -0,0 +1,145 @@ +diff --git a/runtime/ppu/ppu_sysprx.cpp b/runtime/ppu/ppu_sysprx.cpp +index 9cb50400..d4375ab4 100644 +--- a/runtime/ppu/ppu_sysprx.cpp ++++ b/runtime/ppu/ppu_sysprx.cpp +@@ -338,7 +338,10 @@ static void sys_lwmutex_trylock(ppu_context* ctx) + ctx->gpr[3] = 0; + return; + } +- if (!lwm_try(sl0)) { ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x8001000Bu; return; } // EBUSY ++ /* Held by another thread: lv2 answers CELL_EBUSY (0x8001000A). 0x8001000B ++ * is ETIMEDOUT, which only a lock with an expired timeout returns; titles ++ * that poll with trylock and check for EBUSY treat it as a hard failure. */ ++ if (!lwm_try(sl0)) { ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x8001000Au; return; } + } + if (lwm_trace()) { struct LwmSlot* sl = lwm_find(lwm); if (sl) { sl->holder = (long)self; sl->acq_us = lwm_now_us(); sl->acq_fences = g_gcm_ref_pub_count; sl->acq_cpu_us = ppu_thread_cpu_us(self); } } + vm_write32(lwm + LWM_OWNER, self); +diff --git a/tools/test_lwmutex_trylock_busy.py b/tools/test_lwmutex_trylock_busy.py +new file mode 100644 +index 00000000..0af9ef61 +--- /dev/null ++++ b/tools/test_lwmutex_trylock_busy.py +@@ -0,0 +1,123 @@ ++#!/usr/bin/env python3 ++"""sys_lwmutex_trylock on a mutex another thread holds returns CELL_EBUSY. ++ ++lv2 answers a contended trylock with CELL_EBUSY (0x8001000A). The context-style ++HLE in runtime/ppu/ppu_sysprx.cpp returned 0x8001000B, CELL_ETIMEDOUT, which a ++real kernel only gives a lock whose timeout expired. Titles that poll with ++trylock and test for EBUSY then treat the busy case as a hard failure; FIOS in ++PlayStation All-Stars Battle Royale (BCUS98472) logs ++"sys_lwmutex_trylock failed on mutex 'dearchiver_opticalFunnel'" on every ++contended poll. ++ ++Builds the real sys_lwmutex_trylock (pulled verbatim out of ppu_sysprx.cpp, ++along with its LWM_OWNER / LWM_RECUR / LWM_SELF definitions) into a small host ++program over stubbed guest memory and a single stub semaphore, and checks: ++ - a trylock on a free mutex succeeds and stamps owner/recursion; ++ - a trylock by a second thread while it is held returns CELL_EBUSY, not ++ CELL_ETIMEDOUT, and leaves the holder's owner/recursion untouched. ++""" ++import os ++import re ++import shutil ++import subprocess ++import tempfile ++from pathlib import Path ++ ++ROOT = Path(__file__).resolve().parents[1] ++ ++ ++def extract(src, name): ++ m = re.search(r'static void %s\(ppu_context\* ctx\)\s*\{' % name, src) ++ assert m, name + ' not found' ++ i, depth = m.end(), 1 ++ while depth: ++ depth += {'{': 1, '}': -1}.get(src[i], 0) ++ i += 1 ++ return src[m.start():i] ++ ++ ++def define(src, name): ++ m = re.search(r'^#define %s\b.*$' % name, src, re.M) ++ assert m, name + ' not found' ++ return m.group(0) ++ ++ ++HARNESS = r''' ++#include <cstdint> ++#include <cstdio> ++#include <cstring> ++static uint8_t mem[0x10000]; ++static void vm_write32(uint32_t a, uint32_t v) { for (int i = 0; i < 4; i++) mem[a + i] = (uint8_t)(v >> (24 - 8 * i)); } ++static uint32_t vm_read32(uint32_t a) { return (uint32_t)mem[a] << 24 | mem[a + 1] << 16 | mem[a + 2] << 8 | mem[a + 3]; } ++struct ppu_context { uint64_t gpr[32]; uint64_t thread_id; }; ++%s ++%s ++%s ++/* One host-side slot standing in for the semaphore table: lwm_try takes it ++ * if free. Hold tracking (lwm_trace) stays off. */ ++struct LwmSlot { long holder; long long acq_us; long long acq_fences; unsigned long long acq_cpu_us; int held; }; ++static LwmSlot s_slot; ++static struct LwmSlot* lwm_slot(uint32_t) { return &s_slot; } ++static struct LwmSlot* lwm_find(uint32_t) { return &s_slot; } ++static int lwm_try(struct LwmSlot* sl) { if (sl->held) return 0; sl->held = 1; return 1; } ++static int lwm_trace(void) { return 0; } ++static long long lwm_now_us(void) { return 0; } ++static volatile long long g_gcm_ref_pub_count = 0; ++static unsigned long long ppu_thread_cpu_us(unsigned) { return 0; } ++%s ++static int32_t ret(const ppu_context& c) { return (int32_t)(uint32_t)c.gpr[3]; } ++int main() { ++ const uint32_t LWM = 0x1000, A = 0x101, B = 0x102; ++ int fails = 0, ok; ++ memset(mem, 0, sizeof mem); ++ ++ ppu_context c = {}; ++ c.gpr[3] = LWM; c.thread_id = A; ++ sys_lwmutex_trylock(&c); ++ ok = ret(c) == 0 && vm_read32(LWM + LWM_OWNER) == A && vm_read32(LWM + LWM_RECUR) == 1; ++ printf("[%%s] free mutex: thread A acquires (ret 0x%%08X, owner 0x%%X, recur %%u)\n", ++ ok ? "PASS" : "FAIL", (uint32_t)ret(c), vm_read32(LWM + LWM_OWNER), vm_read32(LWM + LWM_RECUR)); ++ fails += !ok; ++ ++ c = ppu_context{}; ++ c.gpr[3] = LWM; c.thread_id = B; ++ sys_lwmutex_trylock(&c); ++ ok = (uint32_t)ret(c) == 0x8001000Au && c.gpr[3] == 0xFFFFFFFF8001000Aull; ++ printf("[%%s] held by A: thread B gets CELL_EBUSY (ret 0x%%08X)%%s\n", ++ ok ? "PASS" : "FAIL", (uint32_t)ret(c), ++ (uint32_t)ret(c) == 0x8001000Bu ? " -- that is CELL_ETIMEDOUT" : ""); ++ fails += !ok; ++ ok = vm_read32(LWM + LWM_OWNER) == A && vm_read32(LWM + LWM_RECUR) == 1; ++ printf("[%%s] held by A: owner and recursion unchanged (owner 0x%%X, recur %%u)\n", ++ ok ? "PASS" : "FAIL", vm_read32(LWM + LWM_OWNER), vm_read32(LWM + LWM_RECUR)); ++ fails += !ok; ++ return fails ? 1 : 0; ++} ++''' ++ ++ ++def main(): ++ cxx = os.environ.get('CXX') or shutil.which('c++') or shutil.which('g++') or shutil.which('clang++') ++ if not cxx: ++ print('SKIP: no C++ compiler') ++ return ++ src = (ROOT / 'runtime/ppu/ppu_sysprx.cpp').read_text() ++ code = HARNESS % (define(src, 'LWM_OWNER'), define(src, 'LWM_RECUR'), define(src, 'LWM_SELF'), ++ extract(src, 'sys_lwmutex_trylock')) ++ with tempfile.TemporaryDirectory() as tmp: ++ c = Path(tmp) / 't.cpp' ++ exe = Path(tmp) / 't' ++ c.write_text(code) ++ r = subprocess.run([cxx, '-std=c++17', '-O1', '-w', str(c), '-o', str(exe)], capture_output=True, text=True) ++ if r.returncode: ++ print(r.stderr[-2000:]) ++ raise SystemExit('FAIL: harness did not compile') ++ r = subprocess.run([str(exe)], capture_output=True, text=True) ++ print(r.stdout, end='') ++ if r.returncode: ++ raise SystemExit('FAIL: contended sys_lwmutex_trylock') ++ print('PASS: contended sys_lwmutex_trylock returns CELL_EBUSY') ++ ++ ++if __name__ == '__main__': ++ main() diff --git a/tasks/sp00nznet__ps3recomp-684/solution/solve.sh b/tasks/sp00nznet__ps3recomp-684/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-684/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-684/task.toml b/tasks/sp00nznet__ps3recomp-684/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6e6afd0c1b984c5e4e5cca4dbbbf9d4694b26b1f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-684/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-684" +description = "ppu_sysprx: contended sys_lwmutex_trylock returns CELL_EBUSY" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/684" +source_access = "auto" +built_at = "2026-11-16T16:09:59.713203+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3cb7edfb7feea90a939e38688015c1d10a9ab69c31b74be65ed215c120dac908" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "runtime/ppu/ppu_sysprx.cpp", + "tools/test_lwmutex_trylock_busy.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 128 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.155876+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-684/tests/capture.py b/tasks/sp00nznet__ps3recomp-684/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-684/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-684/tests/instruction.md b/tasks/sp00nznet__ps3recomp-684/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6691fb2c3b995b14affd6740da66573f3bb7fdc6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-684/tests/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** ppu_sysprx: contended sys_lwmutex_trylock returns CELL_EBUSY + +## Description + +<!-- claude-projects-attribution: {"github_login":"ohkora"} --> +_Requested by **Lord Ohkora** · [project thread](https://claude.ai/code/project/chan_01YNDsm4WrszcKxHit3d9xbn?thread=cmsg_01YNDsm4WrszcKxHit3d9xbnD2a41kJSws2uhdfYuMM6sN)_ + +## Why + +`sys_lwmutex_trylock` in `runtime/ppu/ppu_sysprx.cpp` answers a contended trylock with `0x8001000B` (`CELL_ETIMEDOUT`), even though the comment beside it says `// EBUSY`. lv2 returns `CELL_EBUSY` (`0x8001000A`) when another thread holds the mutex. `ETIMEDOUT` is for a lock whose timeout expired, which `sys_lwmutex_lock` already returns correctly. + +Titles that poll with trylock and check for EBUSY treat the wrong code as a hard failure. PlayStation All-Stars Battle Royale (BCUS98472) is one. Its FIOS layer logs this on every contended poll of the mutex its disc reads share: + +``` +sys_lwmutex_trylock failed on mutex 'dearchiver_opticalFunnel': -2147418101 (operation timed out) +``` + +With this change the message is gone. + +## What changed + +- Contended `sys_lwmutex_trylock` returns `CELL_EBUSY`. The uncontended and recursive paths are unchanged. +- New `tools/test_lwmutex_trylock_busy.py`, in the style of `test_lwcond_layout.py`. It pulls the real handler and its `LWM_*` definitions out of `ppu_sysprx.cpp`, builds them over stub guest memory, and checks that: + - a free mutex is acquired; + - a second thread's trylock gets `CELL_EBUSY`; + - the holder's owner and recursion count are left alone. + +## Test evidence + +- New test on master: fails with `thread B gets CELL_EBUSY (ret 0x8001000B) -- that is CELL_ETIMEDOUT`. +- New test with this change: passes. +- The full `tools/test_*.py` suite passes on Linux (gcc 13.3.0). +- In a BCUS98472 port built with clang-cl on Windows, on the older 39e4f49 base, the FIOS trylock failures stop with this change. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +https://claude.ai/code/session_01B1FjNpGqw84TCo218ynPKH + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-684/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-684/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4377b1185e70048f1e4ed60998b86617334b95e8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-684/tests/oracle.patch @@ -0,0 +1,145 @@ +diff --git a/runtime/ppu/ppu_sysprx.cpp b/runtime/ppu/ppu_sysprx.cpp +index 9cb50400..d4375ab4 100644 +--- a/runtime/ppu/ppu_sysprx.cpp ++++ b/runtime/ppu/ppu_sysprx.cpp +@@ -338,7 +338,10 @@ static void sys_lwmutex_trylock(ppu_context* ctx) + ctx->gpr[3] = 0; + return; + } +- if (!lwm_try(sl0)) { ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x8001000Bu; return; } // EBUSY ++ /* Held by another thread: lv2 answers CELL_EBUSY (0x8001000A). 0x8001000B ++ * is ETIMEDOUT, which only a lock with an expired timeout returns; titles ++ * that poll with trylock and check for EBUSY treat it as a hard failure. */ ++ if (!lwm_try(sl0)) { ctx->gpr[3] = (uint64_t)(int64_t)(int32_t)0x8001000Au; return; } + } + if (lwm_trace()) { struct LwmSlot* sl = lwm_find(lwm); if (sl) { sl->holder = (long)self; sl->acq_us = lwm_now_us(); sl->acq_fences = g_gcm_ref_pub_count; sl->acq_cpu_us = ppu_thread_cpu_us(self); } } + vm_write32(lwm + LWM_OWNER, self); +diff --git a/tools/test_lwmutex_trylock_busy.py b/tools/test_lwmutex_trylock_busy.py +new file mode 100644 +index 00000000..0af9ef61 +--- /dev/null ++++ b/tools/test_lwmutex_trylock_busy.py +@@ -0,0 +1,123 @@ ++#!/usr/bin/env python3 ++"""sys_lwmutex_trylock on a mutex another thread holds returns CELL_EBUSY. ++ ++lv2 answers a contended trylock with CELL_EBUSY (0x8001000A). The context-style ++HLE in runtime/ppu/ppu_sysprx.cpp returned 0x8001000B, CELL_ETIMEDOUT, which a ++real kernel only gives a lock whose timeout expired. Titles that poll with ++trylock and test for EBUSY then treat the busy case as a hard failure; FIOS in ++PlayStation All-Stars Battle Royale (BCUS98472) logs ++"sys_lwmutex_trylock failed on mutex 'dearchiver_opticalFunnel'" on every ++contended poll. ++ ++Builds the real sys_lwmutex_trylock (pulled verbatim out of ppu_sysprx.cpp, ++along with its LWM_OWNER / LWM_RECUR / LWM_SELF definitions) into a small host ++program over stubbed guest memory and a single stub semaphore, and checks: ++ - a trylock on a free mutex succeeds and stamps owner/recursion; ++ - a trylock by a second thread while it is held returns CELL_EBUSY, not ++ CELL_ETIMEDOUT, and leaves the holder's owner/recursion untouched. ++""" ++import os ++import re ++import shutil ++import subprocess ++import tempfile ++from pathlib import Path ++ ++ROOT = Path(__file__).resolve().parents[1] ++ ++ ++def extract(src, name): ++ m = re.search(r'static void %s\(ppu_context\* ctx\)\s*\{' % name, src) ++ assert m, name + ' not found' ++ i, depth = m.end(), 1 ++ while depth: ++ depth += {'{': 1, '}': -1}.get(src[i], 0) ++ i += 1 ++ return src[m.start():i] ++ ++ ++def define(src, name): ++ m = re.search(r'^#define %s\b.*$' % name, src, re.M) ++ assert m, name + ' not found' ++ return m.group(0) ++ ++ ++HARNESS = r''' ++#include <cstdint> ++#include <cstdio> ++#include <cstring> ++static uint8_t mem[0x10000]; ++static void vm_write32(uint32_t a, uint32_t v) { for (int i = 0; i < 4; i++) mem[a + i] = (uint8_t)(v >> (24 - 8 * i)); } ++static uint32_t vm_read32(uint32_t a) { return (uint32_t)mem[a] << 24 | mem[a + 1] << 16 | mem[a + 2] << 8 | mem[a + 3]; } ++struct ppu_context { uint64_t gpr[32]; uint64_t thread_id; }; ++%s ++%s ++%s ++/* One host-side slot standing in for the semaphore table: lwm_try takes it ++ * if free. Hold tracking (lwm_trace) stays off. */ ++struct LwmSlot { long holder; long long acq_us; long long acq_fences; unsigned long long acq_cpu_us; int held; }; ++static LwmSlot s_slot; ++static struct LwmSlot* lwm_slot(uint32_t) { return &s_slot; } ++static struct LwmSlot* lwm_find(uint32_t) { return &s_slot; } ++static int lwm_try(struct LwmSlot* sl) { if (sl->held) return 0; sl->held = 1; return 1; } ++static int lwm_trace(void) { return 0; } ++static long long lwm_now_us(void) { return 0; } ++static volatile long long g_gcm_ref_pub_count = 0; ++static unsigned long long ppu_thread_cpu_us(unsigned) { return 0; } ++%s ++static int32_t ret(const ppu_context& c) { return (int32_t)(uint32_t)c.gpr[3]; } ++int main() { ++ const uint32_t LWM = 0x1000, A = 0x101, B = 0x102; ++ int fails = 0, ok; ++ memset(mem, 0, sizeof mem); ++ ++ ppu_context c = {}; ++ c.gpr[3] = LWM; c.thread_id = A; ++ sys_lwmutex_trylock(&c); ++ ok = ret(c) == 0 && vm_read32(LWM + LWM_OWNER) == A && vm_read32(LWM + LWM_RECUR) == 1; ++ printf("[%%s] free mutex: thread A acquires (ret 0x%%08X, owner 0x%%X, recur %%u)\n", ++ ok ? "PASS" : "FAIL", (uint32_t)ret(c), vm_read32(LWM + LWM_OWNER), vm_read32(LWM + LWM_RECUR)); ++ fails += !ok; ++ ++ c = ppu_context{}; ++ c.gpr[3] = LWM; c.thread_id = B; ++ sys_lwmutex_trylock(&c); ++ ok = (uint32_t)ret(c) == 0x8001000Au && c.gpr[3] == 0xFFFFFFFF8001000Aull; ++ printf("[%%s] held by A: thread B gets CELL_EBUSY (ret 0x%%08X)%%s\n", ++ ok ? "PASS" : "FAIL", (uint32_t)ret(c), ++ (uint32_t)ret(c) == 0x8001000Bu ? " -- that is CELL_ETIMEDOUT" : ""); ++ fails += !ok; ++ ok = vm_read32(LWM + LWM_OWNER) == A && vm_read32(LWM + LWM_RECUR) == 1; ++ printf("[%%s] held by A: owner and recursion unchanged (owner 0x%%X, recur %%u)\n", ++ ok ? "PASS" : "FAIL", vm_read32(LWM + LWM_OWNER), vm_read32(LWM + LWM_RECUR)); ++ fails += !ok; ++ return fails ? 1 : 0; ++} ++''' ++ ++ ++def main(): ++ cxx = os.environ.get('CXX') or shutil.which('c++') or shutil.which('g++') or shutil.which('clang++') ++ if not cxx: ++ print('SKIP: no C++ compiler') ++ return ++ src = (ROOT / 'runtime/ppu/ppu_sysprx.cpp').read_text() ++ code = HARNESS % (define(src, 'LWM_OWNER'), define(src, 'LWM_RECUR'), define(src, 'LWM_SELF'), ++ extract(src, 'sys_lwmutex_trylock')) ++ with tempfile.TemporaryDirectory() as tmp: ++ c = Path(tmp) / 't.cpp' ++ exe = Path(tmp) / 't' ++ c.write_text(code) ++ r = subprocess.run([cxx, '-std=c++17', '-O1', '-w', str(c), '-o', str(exe)], capture_output=True, text=True) ++ if r.returncode: ++ print(r.stderr[-2000:]) ++ raise SystemExit('FAIL: harness did not compile') ++ r = subprocess.run([str(exe)], capture_output=True, text=True) ++ print(r.stdout, end='') ++ if r.returncode: ++ raise SystemExit('FAIL: contended sys_lwmutex_trylock') ++ print('PASS: contended sys_lwmutex_trylock returns CELL_EBUSY') ++ ++ ++if __name__ == '__main__': ++ main() diff --git a/tasks/sp00nznet__ps3recomp-684/tests/test.sh b/tasks/sp00nznet__ps3recomp-684/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-684/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-684/tests/verifier.py b/tasks/sp00nznet__ps3recomp-684/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-684/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-685/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-685/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-685/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-685/instruction.md b/tasks/sp00nznet__ps3recomp-685/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aba348bfe22d9cff34821aad324482bfe5c0f27d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-685/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** cellPamf: reader calls on an uninitialised reader return INVALID_ARG + +## Description + +<!-- claude-projects-attribution: {"github_login":"ohkora"} --> +_Requested by **Lord Ohkora** · [project thread](https://claude.ai/code/project/chan_01YNDsm4WrszcKxHit3d9xbn?thread=cmsg_01YNDsm4WrszcKxHit3d9xbnD2a41kJSws2uhdfYuMM6sN)_ + +## Why + +`pamf_host()` in `libs/codec/cellPamf.c` hands out a fresh, zeroed slot for any reader EA it hasn't seen. That's right for `cellPamfReaderInitialize`, but every other reader call uses it too. So a getter called on a reader the title never initialised gets a slot whose `pamfAddr` is NULL, and then reads the PAMF header through that NULL pointer. + +PlayStation All-Stars Battle Royale (BCUS98472) does this when its attract movie never opens. It calls `cellSailPlayer` `CreateDescriptor` for `movies/attract.pam`, then `cellPamfReaderGetPresentationStartTime` on a reader that was never initialised. That faults with an access violation reading NULL+0x18 (`PAMF_OFF_PRESENT_START`), and the title crashes during boot. + +## What changed + +- New `pamf_get()`. It returns the reader that a successful `Initialize` set up at that EA, and NULL for an unknown EA or a failed `Initialize`. +- Every reader call except `Initialize` now uses `pamf_get()`. Their existing `!reader` checks then return `CELL_PAMF_ERROR_INVALID_ARG`. `GetMuxRateBound`, which returns a `u32`, returns 0. +- `Initialize` keeps using `pamf_host()`, so its behaviour is unchanged. +- New `libs/codec/tests/test_pamf_uninit_reader.c`, driven by `tools/test_pamf_uninit_reader.py` the same way `test_http_response_getters` is. It includes the real `cellPamf.c` and runs every reader call against: + - a reader that was never initialised; + - a reader whose `Initialize` failed with bad magic; + - a reader initialised from a well-formed header, which must still parse: start and end time, mux rate, stream count, entry points. + +## Test evidence + +- New test on master: the fixture crashes with SIGSEGV in the first getter. +- New test with this change: all 44 checks pass. +- The full `tools/test_*.py` suite passes on Linux (gcc 13.3.0). +- In a BCUS98472 port built with clang-cl on Windows, on the older 39e4f49 base, 8 of 8 boots got past the crash and kept running for 60 s. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +https://claude.ai/code/session_01B1FjNpGqw84TCo218ynPKH + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-685/solution/patch.diff b/tasks/sp00nznet__ps3recomp-685/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e923933c2fd55aedd2f8ad7ef73a1adcee974b28 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-685/solution/patch.diff @@ -0,0 +1,361 @@ +diff --git a/libs/codec/cellPamf.c b/libs/codec/cellPamf.c +index 1b6275d3..edc79cb4 100644 +--- a/libs/codec/cellPamf.c ++++ b/libs/codec/cellPamf.c +@@ -129,6 +129,24 @@ static CellPamfReader* pamf_host(CellPamfReader* guest_ea) + return NULL; + } + ++/* The reader a successful cellPamfReaderInitialize set up at this EA, or NULL. ++ * Every call except Initialize goes through this. pamf_host hands out a fresh, ++ * zeroed slot for an EA it hasn't seen, which only Initialize should do: a ++ * getter called on a reader the title never initialised (its movie never ++ * opened, say) got a slot with pamfAddr NULL and read the header through it. ++ * An Initialize that failed leaves its slot with pamfAddr NULL, so that reader ++ * stays invalid too. */ ++static CellPamfReader* pamf_get(CellPamfReader* guest_ea) ++{ ++ u32 ea = (u32)(uintptr_t)guest_ea; ++ if (!ea) ++ return NULL; ++ for (int i = 0; i < PAMF_MAX_READERS; i++) ++ if (s_readers[i].in_use && s_readers[i].ea == ea) ++ return s_readers[i].r.pamfAddr ? &s_readers[i].r : NULL; ++ return NULL; ++} ++ + /* --------------------------------------------------------------------------- + * Reader lifecycle + * -----------------------------------------------------------------------*/ +@@ -186,7 +204,7 @@ s32 cellPamfReaderInitialize(CellPamfReader* reader, void* pamfAddr, + + s32 cellPamfReaderGetPresentationStartTime(CellPamfReader* reader, u64* startTime) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader || !startTime) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -197,7 +215,7 @@ s32 cellPamfReaderGetPresentationStartTime(CellPamfReader* reader, u64* startTim + + s32 cellPamfReaderGetPresentationEndTime(CellPamfReader* reader, u64* endTime) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader || !endTime) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -208,7 +226,7 @@ s32 cellPamfReaderGetPresentationEndTime(CellPamfReader* reader, u64* endTime) + + u32 cellPamfReaderGetMuxRateBound(CellPamfReader* reader) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader) + return 0; + +@@ -222,7 +240,7 @@ u32 cellPamfReaderGetMuxRateBound(CellPamfReader* reader) + + s32 cellPamfReaderGetNumberOfStreams(CellPamfReader* reader) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -249,7 +267,7 @@ static s32 get_stream_sdk_type(CellPamfReader* reader, u32 index) + + s32 cellPamfReaderGetNumberOfSpecificStreams(CellPamfReader* reader, u8 streamType) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -263,7 +281,7 @@ s32 cellPamfReaderGetNumberOfSpecificStreams(CellPamfReader* reader, u8 streamTy + + s32 cellPamfReaderSetStreamWithType(CellPamfReader* reader, u8 streamType, u32 streamIndex) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -283,14 +301,14 @@ s32 cellPamfReaderSetStreamWithType(CellPamfReader* reader, u8 streamType, u32 s + s32 cellPamfReaderSetStreamWithTypeAndChannel(CellPamfReader* reader, u8 streamType, u32 channel) + { + /* Forward the GUEST pointer untouched: cellPamfReaderSetStreamWithType +- * resolves it itself, and pamf_host keys on the guest EA -- handing it an ++ * resolves it itself, and pamf_get keys on the guest EA -- handing it an + * already-resolved host pointer would key a second, empty slot. */ + return cellPamfReaderSetStreamWithType(reader, streamType, channel); + } + + s32 cellPamfReaderSetStreamWithIndex(CellPamfReader* reader, u32 streamIndex) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -361,7 +379,7 @@ static u8 lpcm_bits(u8 code) + + s32 cellPamfReaderGetStreamInfo(CellPamfReader* reader, void* info, u32 infoSize) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader || !info) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -450,7 +468,7 @@ s32 cellPamfReaderGetStreamInfo(CellPamfReader* reader, void* info, u32 infoSize + + s32 cellPamfReaderGetStreamIndex(CellPamfReader* reader) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -477,7 +495,7 @@ s32 cellPamfStreamTypeToEsFilterId(u8 streamType, u8 streamIndex, + + s32 cellPamfReaderGetNumberOfEp(CellPamfReader* reader, s32* numEp) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader || !numEp) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -488,7 +506,7 @@ s32 cellPamfReaderGetNumberOfEp(CellPamfReader* reader, s32* numEp) + + s32 cellPamfReaderGetEp(CellPamfReader* reader, u32 epIndex, CellPamfEp* ep) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader || !ep) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +diff --git a/libs/codec/tests/test_pamf_uninit_reader.c b/libs/codec/tests/test_pamf_uninit_reader.c +new file mode 100644 +index 00000000..77d6e9e9 +--- /dev/null ++++ b/libs/codec/tests/test_pamf_uninit_reader.c +@@ -0,0 +1,152 @@ ++/* ++ * test_pamf_uninit_reader - cellPamf calls on a reader that was never ++ * successfully initialised. ++ * ++ * A title can ask a PAMF reader for its presentation start time before ++ * cellPamfReaderInitialize has run on it, for example when its movie never ++ * opened. The reader table handed such an EA a fresh, zeroed slot, and the ++ * getter then read the header through its NULL pamfAddr (an access violation ++ * at NULL+0x18 for GetPresentationStartTime). Every call except Initialize ++ * now looks the reader up instead, and an unknown or failed reader is ++ * CELL_PAMF_ERROR_INVALID_ARG. ++ * ++ * Checks, all through guest EAs: ++ * - each reader call on an EA Initialize never saw fails cleanly and ++ * leaves its output untouched; ++ * - a reader whose Initialize failed (bad magic) stays invalid; ++ * - a reader initialised from a well-formed header still answers. ++ * ++ * cc -std=gnu17 -I include -o test_pamf_uninit_reader libs/codec/tests/test_pamf_uninit_reader.c ++ * Driven by tools/test_pamf_uninit_reader.py. ++ */ ++#include "../cellPamf.c" ++#include <stdlib.h> ++ ++uint8_t* vm_base; ++uint32_t ppu_vm_size; ++int g_resv_store_active; ++uint32_t g_ww_lo, g_ww_hi; ++void ppu_resv_break_store(uint64_t ea) { (void)ea; } ++void ps3_ww_report_inline(uint32_t a, uint64_t v, int w) { (void)a; (void)v; (void)w; } ++int spu_coh_is_reserved(uint32_t a) { (void)a; return 0; } ++void spu_coh_notify_write(uint32_t a) { (void)a; } ++void spu_lockline_lock(void) {} ++void spu_lockline_unlock(void) {} ++ ++static int fails = 0; ++#define CHECK(c, ...) do { printf((c) ? "[PASS] " : "[FAIL] "); printf(__VA_ARGS__); printf("\n"); \ ++ fflush(stdout); if (!(c)) fails++; } while (0) ++ ++#define INVALID ((s32)CELL_PAMF_ERROR_INVALID_ARG) ++#define EA(x) ((CellPamfReader*)(uintptr_t)(x)) ++#define OUT(x) ((void*)(uintptr_t)(x)) ++ ++static const u32 READER_NEW = 0x1000; /* never initialised */ ++static const u32 READER_BAD = 0x1080; /* Initialize failed */ ++static const u32 READER_GOOD = 0x1100; /* initialised */ ++static const u32 OUT_EA = 0x2000; /* output scratch */ ++static const u32 HDR_EA = 0x10000; /* PAMF header */ ++static const u32 BAD_EA = 0x20000; /* header with the wrong magic */ ++ ++static void put32(u32 ea, u32 v) { vm_write32(ea, v); } ++static void put16(u32 ea, u16 v) { vm_base[ea] = (u8)(v >> 8); vm_base[ea + 1] = (u8)v; } ++ ++/* A header in the layout cellPamf.c parses: one AVC stream, one entry point. */ ++static void build_header(void) ++{ ++ put32(HDR_EA + PAMF_OFF_MAGIC, CELL_PAMF_MAGIC); ++ put32(HDR_EA + PAMF_OFF_VERSION, 0x00040100); ++ put32(HDR_EA + PAMF_OFF_DATA_OFFSET, 0x800); ++ put32(HDR_EA + PAMF_OFF_DATA_SIZE, 0); ++ put32(HDR_EA + PAMF_OFF_STREAM_TABLE, 0x30); ++ put16(HDR_EA + PAMF_OFF_NUM_STREAMS, 1); ++ put32(HDR_EA + PAMF_OFF_PRESENT_START, 0x1234); ++ put32(HDR_EA + PAMF_OFF_PRESENT_END, 0x5678); ++ put32(HDR_EA + PAMF_OFF_MUX_RATE, 0x9ABC); ++ put32(HDR_EA + PAMF_OFF_EP_OFFSET, 0x60); ++ put32(HDR_EA + PAMF_OFF_EP_COUNT, 1); ++ vm_base[HDR_EA + 0x30] = PAMF_RAW_TYPE_AVC; ++ put32(HDR_EA + 0x60, 0x11); ++ put32(HDR_EA + 0x64, 0x22); ++ memcpy(vm_base + BAD_EA, vm_base + HDR_EA, 0x80); ++ put32(BAD_EA + PAMF_OFF_MAGIC, 0x4E4F5045); /* "NOPE" */ ++} ++ ++static void poison_out(void) { memset(vm_base + OUT_EA, 0xAA, 0x100); } ++static int out_untouched(void) ++{ ++ for (int i = 0; i < 0x100; i++) ++ if (vm_base[OUT_EA + i] != 0xAA) return 0; ++ return 1; ++} ++ ++static void expect_invalid(u32 reader, const char* what) ++{ ++ s32 r; ++ poison_out(); ++ r = cellPamfReaderGetPresentationStartTime(EA(reader), OUT(OUT_EA)); ++ CHECK(r == INVALID && out_untouched(), "%s: GetPresentationStartTime -> 0x%08X", what, (u32)r); ++ poison_out(); ++ r = cellPamfReaderGetPresentationEndTime(EA(reader), OUT(OUT_EA)); ++ CHECK(r == INVALID && out_untouched(), "%s: GetPresentationEndTime -> 0x%08X", what, (u32)r); ++ u32 mux = cellPamfReaderGetMuxRateBound(EA(reader)); ++ CHECK(mux == 0, "%s: GetMuxRateBound -> %u", what, mux); ++ r = cellPamfReaderGetNumberOfStreams(EA(reader)); ++ CHECK(r == INVALID, "%s: GetNumberOfStreams -> 0x%08X", what, (u32)r); ++ r = cellPamfReaderGetNumberOfSpecificStreams(EA(reader), CELL_PAMF_STREAM_TYPE_AVC); ++ CHECK(r == INVALID, "%s: GetNumberOfSpecificStreams -> 0x%08X", what, (u32)r); ++ r = cellPamfReaderSetStreamWithType(EA(reader), CELL_PAMF_STREAM_TYPE_AVC, 0); ++ CHECK(r == INVALID, "%s: SetStreamWithType -> 0x%08X", what, (u32)r); ++ r = cellPamfReaderSetStreamWithTypeAndChannel(EA(reader), CELL_PAMF_STREAM_TYPE_AVC, 0); ++ CHECK(r == INVALID, "%s: SetStreamWithTypeAndChannel -> 0x%08X", what, (u32)r); ++ r = cellPamfReaderSetStreamWithIndex(EA(reader), 0); ++ CHECK(r == INVALID, "%s: SetStreamWithIndex -> 0x%08X", what, (u32)r); ++ r = cellPamfReaderGetStreamIndex(EA(reader)); ++ CHECK(r == INVALID, "%s: GetStreamIndex -> 0x%08X", what, (u32)r); ++ poison_out(); ++ r = cellPamfReaderGetStreamInfo(EA(reader), OUT(OUT_EA), 0x40); ++ CHECK(r == INVALID && out_untouched(), "%s: GetStreamInfo -> 0x%08X", what, (u32)r); ++ poison_out(); ++ r = cellPamfReaderGetNumberOfEp(EA(reader), OUT(OUT_EA)); ++ CHECK(r == INVALID && out_untouched(), "%s: GetNumberOfEp -> 0x%08X", what, (u32)r); ++ poison_out(); ++ r = cellPamfReaderGetEp(EA(reader), 0, OUT(OUT_EA)); ++ CHECK(r == INVALID && out_untouched(), "%s: GetEp -> 0x%08X", what, (u32)r); ++} ++ ++int main(void) ++{ ++ ppu_vm_size = 0x40000; ++ vm_base = calloc(1, ppu_vm_size); ++ if (!vm_base) return 2; ++ build_header(); ++ ++ /* Before any Initialize at all. */ ++ expect_invalid(READER_NEW, "never initialised"); ++ ++ /* A failed Initialize leaves that reader invalid. */ ++ s32 r = cellPamfReaderInitialize(EA(READER_BAD), OUT(BAD_EA), 0x800, 0); ++ CHECK(r == (s32)CELL_PAMF_ERROR_INVALID_HEADER, "bad magic: Initialize -> 0x%08X", (u32)r); ++ expect_invalid(READER_BAD, "failed Initialize"); ++ ++ /* A good reader still works, and the others stay invalid beside it. */ ++ r = cellPamfReaderInitialize(EA(READER_GOOD), OUT(HDR_EA), 0x800, 0); ++ CHECK(r == CELL_OK, "good header: Initialize -> 0x%08X", (u32)r); ++ r = cellPamfReaderGetPresentationStartTime(EA(READER_GOOD), OUT(OUT_EA)); ++ CHECK(r == CELL_OK && vm_read64(OUT_EA) == 0x1234, "initialised: start time 0x%llX", ++ (unsigned long long)vm_read64(OUT_EA)); ++ r = cellPamfReaderGetPresentationEndTime(EA(READER_GOOD), OUT(OUT_EA)); ++ CHECK(r == CELL_OK && vm_read64(OUT_EA) == 0x5678, "initialised: end time 0x%llX", ++ (unsigned long long)vm_read64(OUT_EA)); ++ CHECK(cellPamfReaderGetMuxRateBound(EA(READER_GOOD)) == 0x9ABC, "initialised: mux rate"); ++ CHECK(cellPamfReaderGetNumberOfStreams(EA(READER_GOOD)) == 1, "initialised: one stream"); ++ r = cellPamfReaderGetNumberOfEp(EA(READER_GOOD), OUT(OUT_EA)); ++ CHECK(r == CELL_OK && vm_read32(OUT_EA) == 1, "initialised: one entry point"); ++ r = cellPamfReaderGetEp(EA(READER_GOOD), 0, OUT(OUT_EA)); ++ CHECK(r == CELL_OK && vm_read32(OUT_EA) == 0x11 && vm_read32(OUT_EA + 4) == 0x22, ++ "initialised: entry point 0 is (0x%X, 0x%X)", vm_read32(OUT_EA), vm_read32(OUT_EA + 4)); ++ expect_invalid(READER_NEW, "never initialised, beside a good reader"); ++ ++ printf(fails ? "FAIL: %d check(s)\n" : "PASS: cellPamf reader calls on uninitialised readers\n", fails); ++ return fails ? 1 : 0; ++} +diff --git a/tools/test_pamf_uninit_reader.py b/tools/test_pamf_uninit_reader.py +new file mode 100644 +index 00000000..a537b0c3 +--- /dev/null ++++ b/tools/test_pamf_uninit_reader.py +@@ -0,0 +1,61 @@ ++#!/usr/bin/env python3 ++"""cellPamf reader calls on a reader that was never initialised. ++ ++A getter called on a PAMF reader before (or after a failed) ++cellPamfReaderInitialize was handed a fresh, zeroed slot and read the PAMF ++header through its NULL pamfAddr: PlayStation All-Stars Battle Royale ++(BCUS98472) crashed in cellPamfReaderGetPresentationStartTime at NULL+0x18 when ++its attract movie never opened. This builds ++libs/codec/tests/test_pamf_uninit_reader.c, which includes the real ++cellPamf.c, and runs it. ++ ++It needs a host C compiler (under CI=1 a missing one fails instead of ++skipping). ++ ++Usage: ++ python3 tools/test_pamf_uninit_reader.py ++""" ++ ++import os ++import shutil ++import subprocess ++import sys ++import tempfile ++ ++TOOLS = os.path.dirname(os.path.abspath(__file__)) ++ROOT = os.path.dirname(TOOLS) ++SOURCES = [os.path.join(ROOT, "libs", "codec", "tests", "test_pamf_uninit_reader.c")] ++ ++ ++def _cc(): ++ return (shutil.which(os.environ.get("CC", "cc")) or shutil.which("clang") ++ or shutil.which("gcc")) ++ ++ ++def main(): ++ cc = _cc() ++ if cc is None: ++ if os.environ.get("CI"): ++ print("FAIL: no C compiler found") ++ return 1 ++ print("skip test_pamf_uninit_reader: no C compiler") ++ return 0 ++ with tempfile.TemporaryDirectory() as td: ++ exe = os.path.join(td, "test_pamf_uninit_reader") ++ cmd = [cc, "-std=gnu17", "-w", "-I" + os.path.join(ROOT, "include"), ++ "-o", exe] + SOURCES ++ r = subprocess.run(cmd, capture_output=True, text=True) ++ if r.returncode != 0: ++ print("FAIL: fixture did not build") ++ print((r.stdout + r.stderr)[-4000:]) ++ return 1 ++ r = subprocess.run([exe], capture_output=True, text=True) ++ sys.stdout.write(r.stdout) ++ if r.returncode < 0: ++ print("FAIL: fixture crashed (signal %d)" % -r.returncode) ++ return 1 ++ return r.returncode ++ ++ ++if __name__ == "__main__": ++ sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-685/solution/solve.sh b/tasks/sp00nznet__ps3recomp-685/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-685/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-685/task.toml b/tasks/sp00nznet__ps3recomp-685/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5064758d3c4fc95734b70a1f960f950690f73e77 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-685/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-685" +description = "cellPamf: reader calls on an uninitialised reader return INVALID_ARG" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/685" +source_access = "auto" +built_at = "2026-11-16T16:09:59.711341+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:11c7a80c743a26624d2627e3be838a461a446f12d8adc2a8cad24e70003a284d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "libs/codec/cellPamf.c", + "libs/codec/tests/test_pamf_uninit_reader.c", + "tools/test_pamf_uninit_reader.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 255 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.156390+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-685/tests/capture.py b/tasks/sp00nznet__ps3recomp-685/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-685/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-685/tests/instruction.md b/tasks/sp00nznet__ps3recomp-685/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aba348bfe22d9cff34821aad324482bfe5c0f27d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-685/tests/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** cellPamf: reader calls on an uninitialised reader return INVALID_ARG + +## Description + +<!-- claude-projects-attribution: {"github_login":"ohkora"} --> +_Requested by **Lord Ohkora** · [project thread](https://claude.ai/code/project/chan_01YNDsm4WrszcKxHit3d9xbn?thread=cmsg_01YNDsm4WrszcKxHit3d9xbnD2a41kJSws2uhdfYuMM6sN)_ + +## Why + +`pamf_host()` in `libs/codec/cellPamf.c` hands out a fresh, zeroed slot for any reader EA it hasn't seen. That's right for `cellPamfReaderInitialize`, but every other reader call uses it too. So a getter called on a reader the title never initialised gets a slot whose `pamfAddr` is NULL, and then reads the PAMF header through that NULL pointer. + +PlayStation All-Stars Battle Royale (BCUS98472) does this when its attract movie never opens. It calls `cellSailPlayer` `CreateDescriptor` for `movies/attract.pam`, then `cellPamfReaderGetPresentationStartTime` on a reader that was never initialised. That faults with an access violation reading NULL+0x18 (`PAMF_OFF_PRESENT_START`), and the title crashes during boot. + +## What changed + +- New `pamf_get()`. It returns the reader that a successful `Initialize` set up at that EA, and NULL for an unknown EA or a failed `Initialize`. +- Every reader call except `Initialize` now uses `pamf_get()`. Their existing `!reader` checks then return `CELL_PAMF_ERROR_INVALID_ARG`. `GetMuxRateBound`, which returns a `u32`, returns 0. +- `Initialize` keeps using `pamf_host()`, so its behaviour is unchanged. +- New `libs/codec/tests/test_pamf_uninit_reader.c`, driven by `tools/test_pamf_uninit_reader.py` the same way `test_http_response_getters` is. It includes the real `cellPamf.c` and runs every reader call against: + - a reader that was never initialised; + - a reader whose `Initialize` failed with bad magic; + - a reader initialised from a well-formed header, which must still parse: start and end time, mux rate, stream count, entry points. + +## Test evidence + +- New test on master: the fixture crashes with SIGSEGV in the first getter. +- New test with this change: all 44 checks pass. +- The full `tools/test_*.py` suite passes on Linux (gcc 13.3.0). +- In a BCUS98472 port built with clang-cl on Windows, on the older 39e4f49 base, 8 of 8 boots got past the crash and kept running for 60 s. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +https://claude.ai/code/session_01B1FjNpGqw84TCo218ynPKH + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-685/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-685/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e923933c2fd55aedd2f8ad7ef73a1adcee974b28 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-685/tests/oracle.patch @@ -0,0 +1,361 @@ +diff --git a/libs/codec/cellPamf.c b/libs/codec/cellPamf.c +index 1b6275d3..edc79cb4 100644 +--- a/libs/codec/cellPamf.c ++++ b/libs/codec/cellPamf.c +@@ -129,6 +129,24 @@ static CellPamfReader* pamf_host(CellPamfReader* guest_ea) + return NULL; + } + ++/* The reader a successful cellPamfReaderInitialize set up at this EA, or NULL. ++ * Every call except Initialize goes through this. pamf_host hands out a fresh, ++ * zeroed slot for an EA it hasn't seen, which only Initialize should do: a ++ * getter called on a reader the title never initialised (its movie never ++ * opened, say) got a slot with pamfAddr NULL and read the header through it. ++ * An Initialize that failed leaves its slot with pamfAddr NULL, so that reader ++ * stays invalid too. */ ++static CellPamfReader* pamf_get(CellPamfReader* guest_ea) ++{ ++ u32 ea = (u32)(uintptr_t)guest_ea; ++ if (!ea) ++ return NULL; ++ for (int i = 0; i < PAMF_MAX_READERS; i++) ++ if (s_readers[i].in_use && s_readers[i].ea == ea) ++ return s_readers[i].r.pamfAddr ? &s_readers[i].r : NULL; ++ return NULL; ++} ++ + /* --------------------------------------------------------------------------- + * Reader lifecycle + * -----------------------------------------------------------------------*/ +@@ -186,7 +204,7 @@ s32 cellPamfReaderInitialize(CellPamfReader* reader, void* pamfAddr, + + s32 cellPamfReaderGetPresentationStartTime(CellPamfReader* reader, u64* startTime) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader || !startTime) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -197,7 +215,7 @@ s32 cellPamfReaderGetPresentationStartTime(CellPamfReader* reader, u64* startTim + + s32 cellPamfReaderGetPresentationEndTime(CellPamfReader* reader, u64* endTime) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader || !endTime) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -208,7 +226,7 @@ s32 cellPamfReaderGetPresentationEndTime(CellPamfReader* reader, u64* endTime) + + u32 cellPamfReaderGetMuxRateBound(CellPamfReader* reader) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader) + return 0; + +@@ -222,7 +240,7 @@ u32 cellPamfReaderGetMuxRateBound(CellPamfReader* reader) + + s32 cellPamfReaderGetNumberOfStreams(CellPamfReader* reader) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -249,7 +267,7 @@ static s32 get_stream_sdk_type(CellPamfReader* reader, u32 index) + + s32 cellPamfReaderGetNumberOfSpecificStreams(CellPamfReader* reader, u8 streamType) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -263,7 +281,7 @@ s32 cellPamfReaderGetNumberOfSpecificStreams(CellPamfReader* reader, u8 streamTy + + s32 cellPamfReaderSetStreamWithType(CellPamfReader* reader, u8 streamType, u32 streamIndex) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -283,14 +301,14 @@ s32 cellPamfReaderSetStreamWithType(CellPamfReader* reader, u8 streamType, u32 s + s32 cellPamfReaderSetStreamWithTypeAndChannel(CellPamfReader* reader, u8 streamType, u32 channel) + { + /* Forward the GUEST pointer untouched: cellPamfReaderSetStreamWithType +- * resolves it itself, and pamf_host keys on the guest EA -- handing it an ++ * resolves it itself, and pamf_get keys on the guest EA -- handing it an + * already-resolved host pointer would key a second, empty slot. */ + return cellPamfReaderSetStreamWithType(reader, streamType, channel); + } + + s32 cellPamfReaderSetStreamWithIndex(CellPamfReader* reader, u32 streamIndex) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -361,7 +379,7 @@ static u8 lpcm_bits(u8 code) + + s32 cellPamfReaderGetStreamInfo(CellPamfReader* reader, void* info, u32 infoSize) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader || !info) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -450,7 +468,7 @@ s32 cellPamfReaderGetStreamInfo(CellPamfReader* reader, void* info, u32 infoSize + + s32 cellPamfReaderGetStreamIndex(CellPamfReader* reader) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -477,7 +495,7 @@ s32 cellPamfStreamTypeToEsFilterId(u8 streamType, u8 streamIndex, + + s32 cellPamfReaderGetNumberOfEp(CellPamfReader* reader, s32* numEp) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader || !numEp) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +@@ -488,7 +506,7 @@ s32 cellPamfReaderGetNumberOfEp(CellPamfReader* reader, s32* numEp) + + s32 cellPamfReaderGetEp(CellPamfReader* reader, u32 epIndex, CellPamfEp* ep) + { +- reader = pamf_host(reader); ++ reader = pamf_get(reader); + if (!reader || !ep) + return (s32)CELL_PAMF_ERROR_INVALID_ARG; + +diff --git a/libs/codec/tests/test_pamf_uninit_reader.c b/libs/codec/tests/test_pamf_uninit_reader.c +new file mode 100644 +index 00000000..77d6e9e9 +--- /dev/null ++++ b/libs/codec/tests/test_pamf_uninit_reader.c +@@ -0,0 +1,152 @@ ++/* ++ * test_pamf_uninit_reader - cellPamf calls on a reader that was never ++ * successfully initialised. ++ * ++ * A title can ask a PAMF reader for its presentation start time before ++ * cellPamfReaderInitialize has run on it, for example when its movie never ++ * opened. The reader table handed such an EA a fresh, zeroed slot, and the ++ * getter then read the header through its NULL pamfAddr (an access violation ++ * at NULL+0x18 for GetPresentationStartTime). Every call except Initialize ++ * now looks the reader up instead, and an unknown or failed reader is ++ * CELL_PAMF_ERROR_INVALID_ARG. ++ * ++ * Checks, all through guest EAs: ++ * - each reader call on an EA Initialize never saw fails cleanly and ++ * leaves its output untouched; ++ * - a reader whose Initialize failed (bad magic) stays invalid; ++ * - a reader initialised from a well-formed header still answers. ++ * ++ * cc -std=gnu17 -I include -o test_pamf_uninit_reader libs/codec/tests/test_pamf_uninit_reader.c ++ * Driven by tools/test_pamf_uninit_reader.py. ++ */ ++#include "../cellPamf.c" ++#include <stdlib.h> ++ ++uint8_t* vm_base; ++uint32_t ppu_vm_size; ++int g_resv_store_active; ++uint32_t g_ww_lo, g_ww_hi; ++void ppu_resv_break_store(uint64_t ea) { (void)ea; } ++void ps3_ww_report_inline(uint32_t a, uint64_t v, int w) { (void)a; (void)v; (void)w; } ++int spu_coh_is_reserved(uint32_t a) { (void)a; return 0; } ++void spu_coh_notify_write(uint32_t a) { (void)a; } ++void spu_lockline_lock(void) {} ++void spu_lockline_unlock(void) {} ++ ++static int fails = 0; ++#define CHECK(c, ...) do { printf((c) ? "[PASS] " : "[FAIL] "); printf(__VA_ARGS__); printf("\n"); \ ++ fflush(stdout); if (!(c)) fails++; } while (0) ++ ++#define INVALID ((s32)CELL_PAMF_ERROR_INVALID_ARG) ++#define EA(x) ((CellPamfReader*)(uintptr_t)(x)) ++#define OUT(x) ((void*)(uintptr_t)(x)) ++ ++static const u32 READER_NEW = 0x1000; /* never initialised */ ++static const u32 READER_BAD = 0x1080; /* Initialize failed */ ++static const u32 READER_GOOD = 0x1100; /* initialised */ ++static const u32 OUT_EA = 0x2000; /* output scratch */ ++static const u32 HDR_EA = 0x10000; /* PAMF header */ ++static const u32 BAD_EA = 0x20000; /* header with the wrong magic */ ++ ++static void put32(u32 ea, u32 v) { vm_write32(ea, v); } ++static void put16(u32 ea, u16 v) { vm_base[ea] = (u8)(v >> 8); vm_base[ea + 1] = (u8)v; } ++ ++/* A header in the layout cellPamf.c parses: one AVC stream, one entry point. */ ++static void build_header(void) ++{ ++ put32(HDR_EA + PAMF_OFF_MAGIC, CELL_PAMF_MAGIC); ++ put32(HDR_EA + PAMF_OFF_VERSION, 0x00040100); ++ put32(HDR_EA + PAMF_OFF_DATA_OFFSET, 0x800); ++ put32(HDR_EA + PAMF_OFF_DATA_SIZE, 0); ++ put32(HDR_EA + PAMF_OFF_STREAM_TABLE, 0x30); ++ put16(HDR_EA + PAMF_OFF_NUM_STREAMS, 1); ++ put32(HDR_EA + PAMF_OFF_PRESENT_START, 0x1234); ++ put32(HDR_EA + PAMF_OFF_PRESENT_END, 0x5678); ++ put32(HDR_EA + PAMF_OFF_MUX_RATE, 0x9ABC); ++ put32(HDR_EA + PAMF_OFF_EP_OFFSET, 0x60); ++ put32(HDR_EA + PAMF_OFF_EP_COUNT, 1); ++ vm_base[HDR_EA + 0x30] = PAMF_RAW_TYPE_AVC; ++ put32(HDR_EA + 0x60, 0x11); ++ put32(HDR_EA + 0x64, 0x22); ++ memcpy(vm_base + BAD_EA, vm_base + HDR_EA, 0x80); ++ put32(BAD_EA + PAMF_OFF_MAGIC, 0x4E4F5045); /* "NOPE" */ ++} ++ ++static void poison_out(void) { memset(vm_base + OUT_EA, 0xAA, 0x100); } ++static int out_untouched(void) ++{ ++ for (int i = 0; i < 0x100; i++) ++ if (vm_base[OUT_EA + i] != 0xAA) return 0; ++ return 1; ++} ++ ++static void expect_invalid(u32 reader, const char* what) ++{ ++ s32 r; ++ poison_out(); ++ r = cellPamfReaderGetPresentationStartTime(EA(reader), OUT(OUT_EA)); ++ CHECK(r == INVALID && out_untouched(), "%s: GetPresentationStartTime -> 0x%08X", what, (u32)r); ++ poison_out(); ++ r = cellPamfReaderGetPresentationEndTime(EA(reader), OUT(OUT_EA)); ++ CHECK(r == INVALID && out_untouched(), "%s: GetPresentationEndTime -> 0x%08X", what, (u32)r); ++ u32 mux = cellPamfReaderGetMuxRateBound(EA(reader)); ++ CHECK(mux == 0, "%s: GetMuxRateBound -> %u", what, mux); ++ r = cellPamfReaderGetNumberOfStreams(EA(reader)); ++ CHECK(r == INVALID, "%s: GetNumberOfStreams -> 0x%08X", what, (u32)r); ++ r = cellPamfReaderGetNumberOfSpecificStreams(EA(reader), CELL_PAMF_STREAM_TYPE_AVC); ++ CHECK(r == INVALID, "%s: GetNumberOfSpecificStreams -> 0x%08X", what, (u32)r); ++ r = cellPamfReaderSetStreamWithType(EA(reader), CELL_PAMF_STREAM_TYPE_AVC, 0); ++ CHECK(r == INVALID, "%s: SetStreamWithType -> 0x%08X", what, (u32)r); ++ r = cellPamfReaderSetStreamWithTypeAndChannel(EA(reader), CELL_PAMF_STREAM_TYPE_AVC, 0); ++ CHECK(r == INVALID, "%s: SetStreamWithTypeAndChannel -> 0x%08X", what, (u32)r); ++ r = cellPamfReaderSetStreamWithIndex(EA(reader), 0); ++ CHECK(r == INVALID, "%s: SetStreamWithIndex -> 0x%08X", what, (u32)r); ++ r = cellPamfReaderGetStreamIndex(EA(reader)); ++ CHECK(r == INVALID, "%s: GetStreamIndex -> 0x%08X", what, (u32)r); ++ poison_out(); ++ r = cellPamfReaderGetStreamInfo(EA(reader), OUT(OUT_EA), 0x40); ++ CHECK(r == INVALID && out_untouched(), "%s: GetStreamInfo -> 0x%08X", what, (u32)r); ++ poison_out(); ++ r = cellPamfReaderGetNumberOfEp(EA(reader), OUT(OUT_EA)); ++ CHECK(r == INVALID && out_untouched(), "%s: GetNumberOfEp -> 0x%08X", what, (u32)r); ++ poison_out(); ++ r = cellPamfReaderGetEp(EA(reader), 0, OUT(OUT_EA)); ++ CHECK(r == INVALID && out_untouched(), "%s: GetEp -> 0x%08X", what, (u32)r); ++} ++ ++int main(void) ++{ ++ ppu_vm_size = 0x40000; ++ vm_base = calloc(1, ppu_vm_size); ++ if (!vm_base) return 2; ++ build_header(); ++ ++ /* Before any Initialize at all. */ ++ expect_invalid(READER_NEW, "never initialised"); ++ ++ /* A failed Initialize leaves that reader invalid. */ ++ s32 r = cellPamfReaderInitialize(EA(READER_BAD), OUT(BAD_EA), 0x800, 0); ++ CHECK(r == (s32)CELL_PAMF_ERROR_INVALID_HEADER, "bad magic: Initialize -> 0x%08X", (u32)r); ++ expect_invalid(READER_BAD, "failed Initialize"); ++ ++ /* A good reader still works, and the others stay invalid beside it. */ ++ r = cellPamfReaderInitialize(EA(READER_GOOD), OUT(HDR_EA), 0x800, 0); ++ CHECK(r == CELL_OK, "good header: Initialize -> 0x%08X", (u32)r); ++ r = cellPamfReaderGetPresentationStartTime(EA(READER_GOOD), OUT(OUT_EA)); ++ CHECK(r == CELL_OK && vm_read64(OUT_EA) == 0x1234, "initialised: start time 0x%llX", ++ (unsigned long long)vm_read64(OUT_EA)); ++ r = cellPamfReaderGetPresentationEndTime(EA(READER_GOOD), OUT(OUT_EA)); ++ CHECK(r == CELL_OK && vm_read64(OUT_EA) == 0x5678, "initialised: end time 0x%llX", ++ (unsigned long long)vm_read64(OUT_EA)); ++ CHECK(cellPamfReaderGetMuxRateBound(EA(READER_GOOD)) == 0x9ABC, "initialised: mux rate"); ++ CHECK(cellPamfReaderGetNumberOfStreams(EA(READER_GOOD)) == 1, "initialised: one stream"); ++ r = cellPamfReaderGetNumberOfEp(EA(READER_GOOD), OUT(OUT_EA)); ++ CHECK(r == CELL_OK && vm_read32(OUT_EA) == 1, "initialised: one entry point"); ++ r = cellPamfReaderGetEp(EA(READER_GOOD), 0, OUT(OUT_EA)); ++ CHECK(r == CELL_OK && vm_read32(OUT_EA) == 0x11 && vm_read32(OUT_EA + 4) == 0x22, ++ "initialised: entry point 0 is (0x%X, 0x%X)", vm_read32(OUT_EA), vm_read32(OUT_EA + 4)); ++ expect_invalid(READER_NEW, "never initialised, beside a good reader"); ++ ++ printf(fails ? "FAIL: %d check(s)\n" : "PASS: cellPamf reader calls on uninitialised readers\n", fails); ++ return fails ? 1 : 0; ++} +diff --git a/tools/test_pamf_uninit_reader.py b/tools/test_pamf_uninit_reader.py +new file mode 100644 +index 00000000..a537b0c3 +--- /dev/null ++++ b/tools/test_pamf_uninit_reader.py +@@ -0,0 +1,61 @@ ++#!/usr/bin/env python3 ++"""cellPamf reader calls on a reader that was never initialised. ++ ++A getter called on a PAMF reader before (or after a failed) ++cellPamfReaderInitialize was handed a fresh, zeroed slot and read the PAMF ++header through its NULL pamfAddr: PlayStation All-Stars Battle Royale ++(BCUS98472) crashed in cellPamfReaderGetPresentationStartTime at NULL+0x18 when ++its attract movie never opened. This builds ++libs/codec/tests/test_pamf_uninit_reader.c, which includes the real ++cellPamf.c, and runs it. ++ ++It needs a host C compiler (under CI=1 a missing one fails instead of ++skipping). ++ ++Usage: ++ python3 tools/test_pamf_uninit_reader.py ++""" ++ ++import os ++import shutil ++import subprocess ++import sys ++import tempfile ++ ++TOOLS = os.path.dirname(os.path.abspath(__file__)) ++ROOT = os.path.dirname(TOOLS) ++SOURCES = [os.path.join(ROOT, "libs", "codec", "tests", "test_pamf_uninit_reader.c")] ++ ++ ++def _cc(): ++ return (shutil.which(os.environ.get("CC", "cc")) or shutil.which("clang") ++ or shutil.which("gcc")) ++ ++ ++def main(): ++ cc = _cc() ++ if cc is None: ++ if os.environ.get("CI"): ++ print("FAIL: no C compiler found") ++ return 1 ++ print("skip test_pamf_uninit_reader: no C compiler") ++ return 0 ++ with tempfile.TemporaryDirectory() as td: ++ exe = os.path.join(td, "test_pamf_uninit_reader") ++ cmd = [cc, "-std=gnu17", "-w", "-I" + os.path.join(ROOT, "include"), ++ "-o", exe] + SOURCES ++ r = subprocess.run(cmd, capture_output=True, text=True) ++ if r.returncode != 0: ++ print("FAIL: fixture did not build") ++ print((r.stdout + r.stderr)[-4000:]) ++ return 1 ++ r = subprocess.run([exe], capture_output=True, text=True) ++ sys.stdout.write(r.stdout) ++ if r.returncode < 0: ++ print("FAIL: fixture crashed (signal %d)" % -r.returncode) ++ return 1 ++ return r.returncode ++ ++ ++if __name__ == "__main__": ++ sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-685/tests/test.sh b/tasks/sp00nznet__ps3recomp-685/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-685/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-685/tests/verifier.py b/tasks/sp00nznet__ps3recomp-685/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-685/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-688/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-688/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-688/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-688/instruction.md b/tasks/sp00nznet__ps3recomp-688/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..103c80e674098dae414d525560686935cefefa3c --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-688/instruction.md @@ -0,0 +1,109 @@ +# Issue + +**Title:** spu_interp: decode by one 2048-entry table indexed by insn >> 21 + +## Description + +## Summary +Replaces the SPU interpreter's decode cascade in `spu_decode1` with a single 2048-entry table lookup indexed by `insn >> 21`. + +This change is **decode-only**: `spu_ins`, instruction execution semantics, and the execute `switch` are unchanged. `tools/gen_spu_interp.py` generates the C decode table from the imported opcode tables plus the RI7/RI8/LSX/channel definitions it already mirrored; the generated file is checked for freshness. + +## Motivation +In interpreted SPU workloads, instruction decode takes a large share of SPU worker CPU. A Time Profiler of one title put 37 % of its audio job queue's worker CPU and 29 % of its frame job queue's inside `spu_decode1`. + +### The cascade +Previously, `spu_decode1` evaluated every instruction by walking a sequential cascade of generated `switch` helper functions and channel comparisons: +1. RRR (4 bits) via `spu_dec_rrr` +2. RI18 (7 bits) via `spu_dec_ri18` +3. RI16 (9 bits) via `spu_dec_ri16` +4. Channel ops (11 bits) via direct compares for `rdch`, `wrch`, `rchcnt` +5. RI10 (8 bits) via `spu_dec_ri10` +6. RI8 (10 bits) via `spu_dec_ri8` +7. RR (11 bits) via `spu_dec_rr` +8. RI7 (11 bits) via `spu_dec_ri7` +9. LSX (11 bits) via `spu_dec_lsx` +10. Fallback to `SPU_word` + +In addition to this chain of calls and branches per instruction, `spu_decode1` eagerly computed 10-bit, 16-bit, and 18-bit sign- and zero-extended immediate fields up front regardless of which instruction form matched. + +## Why a table is exact +Every SPU opcode field in the ISA is between 4 and 11 bits wide: +- RRR: 4 bits (`insn[31:28]`) +- RI18: 7 bits (`insn[31:25]`) +- RI10: 8 bits (`insn[31:24]`) +- RI16: 9 bits (`insn[31:23]`) +- RI8: 10 bits (`insn[31:22]`) +- RR / RI7 / LSX / Channel: 11 bits (`insn[31:21]`) + +Because every opcode field is a prefix of bits 31..21, the decoded mnemonic and its precedence in the cascade are a pure function of `insn >> 21`. + +`tools/gen_spu_interp.py` now resolves all 2048 possible 11-bit prefixes against the exact precedence order of the old cascade and emits a static 2048-entry table (`spu_decode_tab`) of compact entries (`spu_decode_ent` with 1-byte `op` and 1-byte immediate `form`). + +`spu_decode1` indexes this table with a single load (`insn >> 21`) and evaluates only the specific immediate or target field required by that form. + +## Changes +- `tools/gen_spu_interp.py`: + - Evaluates all 2048 11-bit prefixes using the existing cascade precedence order (RRR -> RI18 -> RI16 -> Channel -> RI10 -> RI8 -> RR -> RI7 -> LSX -> .word). + - Emits `spu_decode_tab[2048]` with `op` and `form`. + - Removes unused `spu_dec_*` functions and `spu_ri7_unsigned`. +- `runtime/spu/spu_interp_tables.inc`: + - Generated lookup table and `spu_decode_form` enum. +- `runtime/spu/spu_interp.c`: + - `spu_decode1` replaced with single table load + form switch. As a side effect this removes undefined behaviour: the old `lqd`/`stqd` path shifted a negative `int` left (`i10 << 4`); UBSan reports `left shift of negative value -512` there. The new path shifts in `uint32_t`. +- `runtime/spu/tests/test_spu_decode.c`: + - New test verifying opcode and field decodes for all 15 immediate forms: signed/unsigned boundaries, LS target wrapping, channel-field width, RRR field order, hints, all four float conversions, and invalid words. Conflicting-prefix precedence was checked separately with an off-tree injected collision. +- `CMakeLists.txt`: + - Registers `test_spu_decode` under unit tests. + +## Validation + +### 1. Exhaustive 2^32 Parity Verification Harness +An off-tree verification harness compared every field of `spu_ins` (`op`, `rt`, `ra`, `rb`, `rc`, `ch`, `imm`, `tgt`) produced by the old cascade against the new table-driven decoder: +- Checked across all $2^{32}$ (4,294,967,296) instruction words at `pc = 0x00000`: **0 mismatches** (3.30 s). +- Checked across all $2^{32}$ (4,294,967,296) instruction words at `pc = 0x3FFFC`: **0 mismatches** (3.24 s). +- Repeated independently (separate harness, separate reviewer): both full sweeps plus 131,072 samples at random aligned pcs covering all 2048 prefixes, **0 mismatches**. A UBSan build over a 1-in-4097 sample is clean for the new decoder. + +### 2. Decode Throughput Microbenchmark +A local off-tree microbenchmark on macOS Apple Silicon timed a synthetic mix of 10,000,000 instructions across opcode formats (no title code), 5 repetitions per arm (`powermode 1`, Low Power mode on battery). The harness is not part of this PR, so treat these numbers as local supporting evidence, not a reproducible upstream benchmark: +- **Old cascade**: + - Runs: 0.1182 s, 0.1181 s, 0.1186 s, 0.1183 s, 0.1181 s + - Mean: **0.1183 s** (spread 0.1181..0.1186 s) — **84.56 M insn/s** +- **New table**: + - Runs: 0.0622 s, 0.0623 s, 0.0624 s, 0.0625 s, 0.0624 s + - Mean: **0.0624 s** (spread 0.0622..0.0625 s) — **160.35 M insn/s** +- **Speedup**: **1.90x** (47.3% decode time reduction). + +### 3. Effect in a commercial title +In one commercial title's replay (same input, 3 runs per arm), its audio middleware's three SPU job images ran 1.4-1.8x faster per job (mean 2.00 -> 1.09 ms, 0.70 -> 0.46 ms, 0.54 -> 0.38 ms), stale audio blocks fell from 1868 to 78 per run, and frame rate rose from 108 to 119 fps. In a Time Profiler, the decode share of worker CPU fell from 37 % to 14 % in the audio queue and from 29 % to 11 % in the frame queue. These are private, workload-local observations, not a general performance guarantee. + +### 4. Test Suites and Toolchain Parity +- Untouched upstream base (`4e8f3ca8`): 22/22 ctest tests pass. +- Patched upstream tree: 23/23 ctest tests pass (`spu_decode` passes in 0.00 s). +- `test_spu_decode` builds and passes with `CC=gcc-16 CXX=g++-16`; GCC's only warnings there are the existing `static inline` + `noinline` attributes in `spu_helpers.h`, not the new decoder. +- `python3 tools/gen_spu_interp.py` regenerates `spu_interp_tables.inc` byte-identically; `tools/test_spu_disasm_ri10.py`, which CI runs, fails if the committed table is stale. That checks freshness against the generator, not decoder equivalence. +- Not run: the Windows clang-cl workflow. The new decoder compiles warning-free for `x86_64-pc-windows-msvc` with clang, and `test_spu_decode` sits inside the existing `if(NOT WIN32)` test block. + +## Test plan +1. Run `python3 tools/test_spu_disasm_ri10.py`: it checks the RI10 expectations and that the committed table matches the generator, without rewriting the checkout. +2. Configure with `-DPS3RECOMP_BUILD_TESTS=ON` and build `test_spu_decode`. +3. Run `ctest -R spu_decode --output-on-failure`. +4. Run full ctest suite to ensure zero regressions across runtime and tools tests. + +Note: CI builds without `PS3RECOMP_BUILD_TESTS`, so `spu_decode`, like the other root CTests, runs only locally. CI still catches a stale table through the tools tests. Running the root CTests in CI would be a separate change; I can send it if wanted. + +## Notes +This PR is intentionally scoped to decode only. Caching decoded instructions across executions (a predecode cache) would need its own invalidation contract for DMA and self-modifying code, so it is left out. No CHANGELOG entry, following the repository's release-time changelog. + +## Checklist +- [x] Builds locally (AppleClang and GCC 16) +- [x] Full test suite passes (23/23) +- [x] Exhaustive parity verified over all 2^32 words (0 mismatches) +- [x] Generator output matches the committed table (freshness check, not an equivalence proof) +- [x] No behavior changes to execution semantics or lifted paths +- [x] No title names, addresses, or game/firmware assets added +- [x] "Allow edits by maintainers" enabled + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-688/solution/patch.diff b/tasks/sp00nznet__ps3recomp-688/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bb1541ed8b279fe8b36c48c78629c3c1cd5e1cbf --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-688/solution/patch.diff @@ -0,0 +1,1310 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..3704fda4 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -417,6 +417,16 @@ if(PS3RECOMP_BUILD_TESTS) + add_test(NAME spu_float_exact COMMAND test_spu_float_exact) + set_tests_properties(spu_float_exact PROPERTIES TIMEOUT 300) + ++ # The interpreter's op/immediate decode at the opcode-width and ++ # immediate-form boundaries, against ISA-layout encodings. ++ add_executable(test_spu_decode ++ runtime/spu/tests/test_spu_decode.c) ++ target_include_directories(test_spu_decode PRIVATE include runtime/spu) ++ target_compile_options(test_spu_decode PRIVATE -UNDEBUG) ++ target_link_libraries(test_spu_decode PRIVATE m) ++ add_test(NAME spu_decode COMMAND test_spu_decode) ++ set_tests_properties(spu_decode PROPERTIES TIMEOUT 30) ++ + add_executable(test_spu_lockline_wait + runtime/spu/tests/test_spu_lockline_wait.c) + target_include_directories(test_spu_lockline_wait PRIVATE include) +diff --git a/runtime/spu/spu_interp.c b/runtime/spu/spu_interp.c +index e9b8f613..ea85a8a3 100644 +--- a/runtime/spu/spu_interp.c ++++ b/runtime/spu/spu_interp.c +@@ -17,7 +17,7 @@ u128 spu_rdch(spu_context* ctx, uint32_t channel); + void spu_wrch(spu_context* ctx, uint32_t channel, u128 value); + uint32_t spu_rchcnt(spu_context* ctx, uint32_t channel); + +-#include "spu_interp_tables.inc" /* spu_op enum, spu_op_name[], spu_dec_* */ ++#include "spu_interp_tables.inc" /* spu_op enum, spu_op_name[], spu_decode_tab[] */ + + /* Work descriptor for the next SYS_SPU_THREAD_STOP_RECEIVE_EVENT service, set + * by the event-port send that wakes a sim SPU. Single-slot: dispatch is +@@ -25,7 +25,7 @@ uint32_t spu_rchcnt(spu_context* ctx, uint32_t channel); + uint32_t g_spu_pending_evt[3]; + int g_spu_pending_evt_valid; + +-/* ---- decode: 32-bit insn -> fields (mirrors spu_disasm.spu_decode order) ---- */ ++/* ---- decode: 32-bit insn -> fields (one lookup in spu_decode_tab) ---- */ + typedef struct { + spu_op op; + uint8_t rt, ra, rb, rc, ch; +@@ -38,61 +38,38 @@ static int32_t sx(uint32_t v, int bits) { + return (int32_t)((v ^ m) - m); + } + ++/* Every opcode field is a prefix of bits 31..21, so the op and the immediate ++ * form come from one table load; the cascade precedence is baked into the ++ * table by tools/gen_spu_interp.py. Only the fields the form needs are ++ * computed. */ + static void spu_decode1(uint32_t insn, uint32_t pc, spu_ins* d) { +- uint32_t op4 = (insn >> 28) & 0xF, op7 = (insn >> 25) & 0x7F; +- uint32_t op8 = (insn >> 24) & 0xFF, op9 = (insn >> 23) & 0x1FF; +- uint32_t op10 = (insn >> 22) & 0x3FF, op11 = (insn >> 21) & 0x7FF; ++ const spu_decode_ent e = spu_decode_tab[insn >> 21]; ++ d->op = (spu_op)e.op; + d->rt = insn & 0x7F; d->ra = (insn >> 7) & 0x7F; + d->rb = (insn >> 14) & 0x7F; d->rc = (insn >> 21) & 0x7F; + d->ch = (insn >> 7) & 0x7F; d->imm = 0; d->tgt = 0; +- int32_t i10 = sx((insn >> 14) & 0x3FF, 10); +- int32_t i16 = sx((insn >> 7) & 0xFFFF, 16); +- uint32_t i18 = (insn >> 7) & 0x3FFFF; + +- /* RRR (4) */ +- if ((d->op = spu_dec_rrr(op4)) != SPU_word) return; +- /* RI18 (7) */ +- if ((d->op = spu_dec_ri18(op7)) != SPU_word) { +- d->imm = (d->op == SPU_ila) ? (int32_t)i18 : (int32_t)(i18 & 0xFFFF); +- return; ++ switch ((spu_decode_form)e.form) { ++ case SPU_F_NONE: break; ++ case SPU_F_I18: d->imm = (int32_t)((insn >> 7) & 0x3FFFF); break; ++ case SPU_F_I18LO: d->imm = (int32_t)((insn >> 7) & 0xFFFF); break; ++ case SPU_F_LQA: ++ d->tgt = ((((insn >> 7) & 0xFFFF) << 2)) & 0x3FFF0; break; ++ case SPU_F_LQR: ++ d->tgt = ((uint32_t)(sx((insn >> 7) & 0xFFFF, 16) * 4) + pc) & 0x3FFF0; break; ++ case SPU_F_BREL: ++ d->tgt = ((uint32_t)(sx((insn >> 7) & 0xFFFF, 16) * 4) + pc) & 0x3FFFF; break; ++ case SPU_F_BABS: ++ d->tgt = ((uint32_t)(sx((insn >> 7) & 0xFFFF, 16) * 4)) & 0x3FFFF; break; ++ case SPU_F_I16S: d->imm = sx((insn >> 7) & 0xFFFF, 16); break; ++ case SPU_F_I16U: d->imm = (int32_t)((insn >> 7) & 0xFFFF); break; ++ case SPU_F_I10: d->imm = sx((insn >> 14) & 0x3FF, 10); break; ++ case SPU_F_I10Q: d->imm = (int32_t)((uint32_t)sx((insn >> 14) & 0x3FF, 10) << 4); break; ++ case SPU_F_I8: d->imm = (insn >> 14) & 0xFF; break; ++ case SPU_F_STOP: d->imm = insn & 0x3FFF; break; ++ case SPU_F_I7S: d->imm = sx(d->rb, 7); break; ++ case SPU_F_I7U: d->imm = d->rb; break; + } +- /* RI16 (9) — before RI10 (shared top-8-bit opcodes) */ +- if ((d->op = spu_dec_ri16(op9)) != SPU_word) { +- switch (d->op) { +- case SPU_lqa: case SPU_stqa: d->tgt = ((uint32_t)(i16 & 0xFFFF) << 2) & 0x3FFF0; break; +- case SPU_lqr: case SPU_stqr: d->tgt = ((uint32_t)(i16 * 4) + pc) & 0x3FFF0; break; +- case SPU_br: case SPU_brsl: case SPU_brz: case SPU_brnz: +- case SPU_brhz: case SPU_brhnz: d->tgt = ((uint32_t)(i16 * 4) + pc) & 0x3FFFF; break; +- case SPU_bra: case SPU_brasl: d->tgt = ((uint32_t)(i16 * 4)) & 0x3FFFF; break; +- case SPU_il: d->imm = i16; break; +- default: d->imm = (int32_t)(i16 & 0xFFFF); break; /* ilh/ilhu/iohl */ +- } +- return; +- } +- /* channel ops (op11) — before RI10 (wrch/shli op8 clash) */ +- if (op11 == 0x00D) { d->op = SPU_rdch; return; } +- if (op11 == 0x10D) { d->op = SPU_wrch; return; } +- if (op11 == 0x00F) { d->op = SPU_rchcnt; return; } +- /* RI10 (8) */ +- if ((d->op = spu_dec_ri10(op8)) != SPU_word) { +- d->imm = (d->op == SPU_lqd || d->op == SPU_stqd) ? (i10 << 4) : i10; +- return; +- } +- /* RI8 (10) float<->int conversions */ +- if ((d->op = spu_dec_ri8(op10)) != SPU_word) { d->imm = (insn >> 14) & 0xFF; return; } +- /* RR (11) */ +- if ((d->op = spu_dec_rr(op11)) != SPU_word) { +- if (d->op == SPU_stop) d->imm = insn & 0x3FFF; +- return; +- } +- /* RI7 (11) rotate/shift/gen-control immediates */ +- if ((d->op = spu_dec_ri7(op11)) != SPU_word) { +- d->imm = spu_ri7_unsigned(d->op) ? d->rb : sx(d->rb, 7); +- return; +- } +- /* LSX (redundant with RR's lqx/stqx, kept for order-parity) */ +- if ((d->op = spu_dec_lsx(op11)) != SPU_word) return; +- d->op = SPU_word; + } + + /* spu_lifted_lookup() is defined by spu_fn_registry.c (the single owner of the +diff --git a/runtime/spu/spu_interp_tables.inc b/runtime/spu/spu_interp_tables.inc +index 90f9dd8c..ee32cf28 100644 +--- a/runtime/spu/spu_interp_tables.inc ++++ b/runtime/spu/spu_interp_tables.inc +@@ -1,6 +1,7 @@ + /* GENERATED by tools/gen_spu_interp.py -- do not edit. */ +-/* Opcode->mnemonic tables for the SPU interpreter, from the validated +- * spu_disasm.py decoder. Regenerate after any decoder table change. */ ++/* Opcode->mnemonic enum and the insn>>21 decode table for the SPU ++ * interpreter, from the validated spu_disasm.py decoder. Regenerate after ++ * any decoder table change. */ + + typedef enum { + SPU_word, +@@ -409,256 +410,540 @@ static const char* const spu_op_name[SPU_OP_COUNT] = { + [SPU_xswd] = "xswd", + }; + +-static spu_op spu_dec_rrr(uint32_t op4) { +- switch (op4) { +- case 0x8: return SPU_selb; +- case 0xB: return SPU_shufb; +- case 0xC: return SPU_mpya; +- case 0xD: return SPU_fnms; +- case 0xE: return SPU_fma; +- case 0xF: return SPU_fms; +- default: return SPU_word; +- } +-} +- +-static spu_op spu_dec_ri18(uint32_t op7) { +- switch (op7) { +- case 0x8: return SPU_hbra; +- case 0x9: return SPU_hbrr; +- case 0x21: return SPU_ila; +- default: return SPU_word; +- } +-} +- +-static spu_op spu_dec_ri16(uint32_t op9) { +- switch (op9) { +- case 0x40: return SPU_brz; +- case 0x41: return SPU_stqa; +- case 0x42: return SPU_brnz; +- case 0x44: return SPU_brhz; +- case 0x46: return SPU_brhnz; +- case 0x47: return SPU_stqr; +- case 0x60: return SPU_bra; +- case 0x61: return SPU_lqa; +- case 0x62: return SPU_brasl; +- case 0x64: return SPU_br; +- case 0x65: return SPU_fsmbi; +- case 0x66: return SPU_brsl; +- case 0x67: return SPU_lqr; +- case 0x81: return SPU_il; +- case 0x82: return SPU_ilhu; +- case 0x83: return SPU_ilh; +- case 0xC1: return SPU_iohl; +- default: return SPU_word; +- } +-} +- +-static spu_op spu_dec_ri10(uint32_t op8) { +- switch (op8) { +- case 0x4: return SPU_ori; +- case 0x5: return SPU_orhi; +- case 0x6: return SPU_orbi; +- case 0xC: return SPU_sfi; +- case 0xD: return SPU_sfhi; +- case 0x14: return SPU_andi; +- case 0x15: return SPU_andhi; +- case 0x16: return SPU_andbi; +- case 0x1C: return SPU_ai; +- case 0x1D: return SPU_ahi; +- case 0x24: return SPU_stqd; +- case 0x34: return SPU_lqd; +- case 0x44: return SPU_xori; +- case 0x45: return SPU_xorhi; +- case 0x46: return SPU_xorbi; +- case 0x4C: return SPU_cgti; +- case 0x4D: return SPU_cgthi; +- case 0x4E: return SPU_cgtbi; +- case 0x4F: return SPU_hgti; +- case 0x5C: return SPU_clgti; +- case 0x5D: return SPU_clgthi; +- case 0x5E: return SPU_clgtbi; +- case 0x5F: return SPU_hlgti; +- case 0x74: return SPU_mpyi; +- case 0x75: return SPU_mpyui; +- case 0x7C: return SPU_ceqi; +- case 0x7D: return SPU_ceqhi; +- case 0x7E: return SPU_ceqbi; +- case 0x7F: return SPU_heqi; +- default: return SPU_word; +- } +-} +- +-static spu_op spu_dec_ri8(uint32_t op10) { +- switch (op10) { +- case 0x1D8: return SPU_cflts; +- case 0x1D9: return SPU_cfltu; +- case 0x1DA: return SPU_csflt; +- case 0x1DB: return SPU_cuflt; +- default: return SPU_word; +- } +-} +- +-static spu_op spu_dec_rr(uint32_t op11) { +- switch (op11) { +- case 0x0: return SPU_stop; +- case 0x1: return SPU_lnop; +- case 0x2: return SPU_sync; +- case 0x3: return SPU_dsync; +- case 0xC: return SPU_mfspr; +- case 0xD: return SPU_rdch; +- case 0xF: return SPU_rchcnt; +- case 0x40: return SPU_sf; +- case 0x41: return SPU_or; +- case 0x42: return SPU_bg; +- case 0x48: return SPU_sfh; +- case 0x49: return SPU_nor; +- case 0x53: return SPU_absdb; +- case 0x58: return SPU_rot; +- case 0x59: return SPU_rotm; +- case 0x5A: return SPU_rotma; +- case 0x5B: return SPU_shl; +- case 0x5C: return SPU_roth; +- case 0x5D: return SPU_rothm; +- case 0x5E: return SPU_rotmah; +- case 0x5F: return SPU_shlh; +- case 0xC0: return SPU_a; +- case 0xC1: return SPU_and; +- case 0xC2: return SPU_cg; +- case 0xC8: return SPU_ah; +- case 0xC9: return SPU_nand; +- case 0xD3: return SPU_avgb; +- case 0x10C: return SPU_mtspr; +- case 0x10D: return SPU_wrch; +- case 0x128: return SPU_biz; +- case 0x129: return SPU_binz; +- case 0x12A: return SPU_bihz; +- case 0x12B: return SPU_bihnz; +- case 0x140: return SPU_stopd; +- case 0x144: return SPU_stqx; +- case 0x1A8: return SPU_bi; +- case 0x1A9: return SPU_bisl; +- case 0x1AA: return SPU_iret; +- case 0x1AB: return SPU_bisled; +- case 0x1AC: return SPU_hbr; +- case 0x1B0: return SPU_gb; +- case 0x1B1: return SPU_gbh; +- case 0x1B2: return SPU_gbb; +- case 0x1B4: return SPU_fsm; +- case 0x1B5: return SPU_fsmh; +- case 0x1B6: return SPU_fsmb; +- case 0x1B8: return SPU_frest; +- case 0x1B9: return SPU_frsqest; +- case 0x1C4: return SPU_lqx; +- case 0x1CC: return SPU_rotqbybi; +- case 0x1CD: return SPU_rotqmbybi; +- case 0x1CF: return SPU_shlqbybi; +- case 0x1D4: return SPU_cbx; +- case 0x1D5: return SPU_chx; +- case 0x1D6: return SPU_cwx; +- case 0x1D7: return SPU_cdx; +- case 0x1D8: return SPU_rotqbi; +- case 0x1D9: return SPU_rotqmbi; +- case 0x1DB: return SPU_shlqbi; +- case 0x1DC: return SPU_rotqby; +- case 0x1DD: return SPU_rotqmby; +- case 0x1DF: return SPU_shlqby; +- case 0x1F0: return SPU_orx; +- case 0x201: return SPU_nop; +- case 0x240: return SPU_cgt; +- case 0x241: return SPU_xor; +- case 0x248: return SPU_cgth; +- case 0x249: return SPU_eqv; +- case 0x250: return SPU_cgtb; +- case 0x253: return SPU_sumb; +- case 0x258: return SPU_hgt; +- case 0x2A5: return SPU_clz; +- case 0x2A6: return SPU_xswd; +- case 0x2AE: return SPU_xshw; +- case 0x2B4: return SPU_cntb; +- case 0x2B6: return SPU_xsbh; +- case 0x2C0: return SPU_clgt; +- case 0x2C1: return SPU_andc; +- case 0x2C2: return SPU_fcgt; +- case 0x2C3: return SPU_dfcgt; +- case 0x2C4: return SPU_fa; +- case 0x2C5: return SPU_fs; +- case 0x2C6: return SPU_fm; +- case 0x2C8: return SPU_clgth; +- case 0x2C9: return SPU_orc; +- case 0x2CA: return SPU_fcmgt; +- case 0x2CB: return SPU_dfcmgt; +- case 0x2CC: return SPU_dfa; +- case 0x2CD: return SPU_dfs; +- case 0x2CE: return SPU_dfm; +- case 0x2D0: return SPU_clgtb; +- case 0x2D8: return SPU_hlgt; +- case 0x340: return SPU_addx; +- case 0x341: return SPU_sfx; +- case 0x342: return SPU_cgx; +- case 0x343: return SPU_bgx; +- case 0x346: return SPU_mpyhha; +- case 0x34E: return SPU_mpyhhau; +- case 0x35C: return SPU_dfma; +- case 0x35D: return SPU_dfms; +- case 0x35E: return SPU_dfnms; +- case 0x35F: return SPU_dfnma; +- case 0x398: return SPU_fscrrd; +- case 0x3B8: return SPU_fesd; +- case 0x3B9: return SPU_frds; +- case 0x3BA: return SPU_fscrwr; +- case 0x3BF: return SPU_dftsv; +- case 0x3C0: return SPU_ceq; +- case 0x3C2: return SPU_fceq; +- case 0x3C3: return SPU_dfceq; +- case 0x3C4: return SPU_mpy; +- case 0x3C5: return SPU_mpyh; +- case 0x3C6: return SPU_mpyhh; +- case 0x3C7: return SPU_mpys; +- case 0x3C8: return SPU_ceqh; +- case 0x3CA: return SPU_fcmeq; +- case 0x3CB: return SPU_dfcmeq; +- case 0x3CC: return SPU_mpyu; +- case 0x3CE: return SPU_mpyhhu; +- case 0x3D0: return SPU_ceqb; +- case 0x3D4: return SPU_fi; +- case 0x3D8: return SPU_heq; +- default: return SPU_word; +- } +-} +- +-static spu_op spu_dec_ri7(uint32_t op11) { +- switch (op11) { +- case 0x78: return SPU_roti; +- case 0x79: return SPU_rotmi; +- case 0x7A: return SPU_rotmai; +- case 0x7B: return SPU_shli; +- case 0x7C: return SPU_rothi; +- case 0x7D: return SPU_rothmi; +- case 0x7E: return SPU_rotmahi; +- case 0x7F: return SPU_shlhi; +- case 0x1F4: return SPU_cbd; +- case 0x1F5: return SPU_chd; +- case 0x1F6: return SPU_cwd; +- case 0x1F7: return SPU_cdd; +- case 0x1F8: return SPU_rotqbii; +- case 0x1F9: return SPU_rotqmbii; +- case 0x1FB: return SPU_shlqbii; +- case 0x1FC: return SPU_rotqbyi; +- case 0x1FD: return SPU_rotqmbyi; +- case 0x1FF: return SPU_shlqbyi; +- default: return SPU_word; +- } +-} ++/* How spu_decode1 derives imm/tgt. */ ++typedef enum { ++ SPU_F_NONE, /* no immediate: RRR, RR (except stop), LSX, channel ops, .word */ ++ SPU_F_I18, /* ila: full 18-bit immediate */ ++ SPU_F_I18LO, /* other RI18 (hbra/hbrr): low 16 bits of the 18-bit field */ ++ SPU_F_LQA, /* lqa/stqa: absolute 16-byte aligned LS address in tgt */ ++ SPU_F_LQR, /* lqr/stqr: pc-relative 16-byte aligned LS address in tgt */ ++ SPU_F_BREL, /* br/brsl/brz/brnz/brhz/brhnz: pc-relative target in tgt */ ++ SPU_F_BABS, /* bra/brasl: absolute target in tgt */ ++ SPU_F_I16S, /* il: sign-extended 16-bit immediate */ ++ SPU_F_I16U, /* ilh/ilhu/iohl/fsmbi: zero-extended 16-bit immediate */ ++ SPU_F_I10, /* RI10: sign-extended 10-bit immediate */ ++ SPU_F_I10Q, /* lqd/stqd: sign-extended 10-bit immediate scaled by 16 */ ++ SPU_F_I8, /* RI8 float<->int conversions: unsigned 8-bit scale */ ++ SPU_F_STOP, /* stop: 14-bit signal type */ ++ SPU_F_I7S, /* RI7: sign-extended 7-bit immediate */ ++ SPU_F_I7U, /* cbd/chd/cwd/cdd: unsigned 7-bit immediate */ ++} spu_decode_form; + +-static spu_op spu_dec_lsx(uint32_t op11) { +- switch (op11) { +- case 0x144: return SPU_stqx; +- case 0x1C4: return SPU_lqx; +- default: return SPU_word; +- } +-} ++typedef struct { uint8_t op; uint8_t form; } spu_decode_ent; ++_Static_assert(SPU_OP_COUNT <= 256, "spu_op must fit spu_decode_ent.op"); + +-/* signed-vs-unsigned i7 per instruction (Table 2-6) */ +-static int spu_ri7_unsigned(spu_op op) { +- return op == SPU_cbd || op == SPU_cdd || op == SPU_chd || op == SPU_cwd; +-} ++/* Indexed by insn >> 21; precedence is documented in tools/gen_spu_interp.py. */ ++static const spu_decode_ent spu_decode_tab[2048] = { ++ /*000*/ {SPU_stop, SPU_F_STOP}, {SPU_lnop, SPU_F_NONE}, {SPU_sync, SPU_F_NONE}, {SPU_dsync, SPU_F_NONE}, ++ /*004*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*008*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*00C*/ {SPU_mfspr, SPU_F_NONE}, {SPU_rdch, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_rchcnt, SPU_F_NONE}, ++ /*010*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*014*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*018*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*01C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*020*/ {SPU_ori, SPU_F_I10}, {SPU_ori, SPU_F_I10}, {SPU_ori, SPU_F_I10}, {SPU_ori, SPU_F_I10}, ++ /*024*/ {SPU_ori, SPU_F_I10}, {SPU_ori, SPU_F_I10}, {SPU_ori, SPU_F_I10}, {SPU_ori, SPU_F_I10}, ++ /*028*/ {SPU_orhi, SPU_F_I10}, {SPU_orhi, SPU_F_I10}, {SPU_orhi, SPU_F_I10}, {SPU_orhi, SPU_F_I10}, ++ /*02C*/ {SPU_orhi, SPU_F_I10}, {SPU_orhi, SPU_F_I10}, {SPU_orhi, SPU_F_I10}, {SPU_orhi, SPU_F_I10}, ++ /*030*/ {SPU_orbi, SPU_F_I10}, {SPU_orbi, SPU_F_I10}, {SPU_orbi, SPU_F_I10}, {SPU_orbi, SPU_F_I10}, ++ /*034*/ {SPU_orbi, SPU_F_I10}, {SPU_orbi, SPU_F_I10}, {SPU_orbi, SPU_F_I10}, {SPU_orbi, SPU_F_I10}, ++ /*038*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*03C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*040*/ {SPU_sf, SPU_F_NONE}, {SPU_or, SPU_F_NONE}, {SPU_bg, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*044*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*048*/ {SPU_sfh, SPU_F_NONE}, {SPU_nor, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*04C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*050*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_absdb, SPU_F_NONE}, ++ /*054*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*058*/ {SPU_rot, SPU_F_NONE}, {SPU_rotm, SPU_F_NONE}, {SPU_rotma, SPU_F_NONE}, {SPU_shl, SPU_F_NONE}, ++ /*05C*/ {SPU_roth, SPU_F_NONE}, {SPU_rothm, SPU_F_NONE}, {SPU_rotmah, SPU_F_NONE}, {SPU_shlh, SPU_F_NONE}, ++ /*060*/ {SPU_sfi, SPU_F_I10}, {SPU_sfi, SPU_F_I10}, {SPU_sfi, SPU_F_I10}, {SPU_sfi, SPU_F_I10}, ++ /*064*/ {SPU_sfi, SPU_F_I10}, {SPU_sfi, SPU_F_I10}, {SPU_sfi, SPU_F_I10}, {SPU_sfi, SPU_F_I10}, ++ /*068*/ {SPU_sfhi, SPU_F_I10}, {SPU_sfhi, SPU_F_I10}, {SPU_sfhi, SPU_F_I10}, {SPU_sfhi, SPU_F_I10}, ++ /*06C*/ {SPU_sfhi, SPU_F_I10}, {SPU_sfhi, SPU_F_I10}, {SPU_sfhi, SPU_F_I10}, {SPU_sfhi, SPU_F_I10}, ++ /*070*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*074*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*078*/ {SPU_roti, SPU_F_I7S}, {SPU_rotmi, SPU_F_I7S}, {SPU_rotmai, SPU_F_I7S}, {SPU_shli, SPU_F_I7S}, ++ /*07C*/ {SPU_rothi, SPU_F_I7S}, {SPU_rothmi, SPU_F_I7S}, {SPU_rotmahi, SPU_F_I7S}, {SPU_shlhi, SPU_F_I7S}, ++ /*080*/ {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, ++ /*084*/ {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, ++ /*088*/ {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, ++ /*08C*/ {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, ++ /*090*/ {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, ++ /*094*/ {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, ++ /*098*/ {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, ++ /*09C*/ {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, ++ /*0A0*/ {SPU_andi, SPU_F_I10}, {SPU_andi, SPU_F_I10}, {SPU_andi, SPU_F_I10}, {SPU_andi, SPU_F_I10}, ++ /*0A4*/ {SPU_andi, SPU_F_I10}, {SPU_andi, SPU_F_I10}, {SPU_andi, SPU_F_I10}, {SPU_andi, SPU_F_I10}, ++ /*0A8*/ {SPU_andhi, SPU_F_I10}, {SPU_andhi, SPU_F_I10}, {SPU_andhi, SPU_F_I10}, {SPU_andhi, SPU_F_I10}, ++ /*0AC*/ {SPU_andhi, SPU_F_I10}, {SPU_andhi, SPU_F_I10}, {SPU_andhi, SPU_F_I10}, {SPU_andhi, SPU_F_I10}, ++ /*0B0*/ {SPU_andbi, SPU_F_I10}, {SPU_andbi, SPU_F_I10}, {SPU_andbi, SPU_F_I10}, {SPU_andbi, SPU_F_I10}, ++ /*0B4*/ {SPU_andbi, SPU_F_I10}, {SPU_andbi, SPU_F_I10}, {SPU_andbi, SPU_F_I10}, {SPU_andbi, SPU_F_I10}, ++ /*0B8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0BC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0C0*/ {SPU_a, SPU_F_NONE}, {SPU_and, SPU_F_NONE}, {SPU_cg, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0C4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0C8*/ {SPU_ah, SPU_F_NONE}, {SPU_nand, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0CC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0D0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_avgb, SPU_F_NONE}, ++ /*0D4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0D8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0DC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0E0*/ {SPU_ai, SPU_F_I10}, {SPU_ai, SPU_F_I10}, {SPU_ai, SPU_F_I10}, {SPU_ai, SPU_F_I10}, ++ /*0E4*/ {SPU_ai, SPU_F_I10}, {SPU_ai, SPU_F_I10}, {SPU_ai, SPU_F_I10}, {SPU_ai, SPU_F_I10}, ++ /*0E8*/ {SPU_ahi, SPU_F_I10}, {SPU_ahi, SPU_F_I10}, {SPU_ahi, SPU_F_I10}, {SPU_ahi, SPU_F_I10}, ++ /*0EC*/ {SPU_ahi, SPU_F_I10}, {SPU_ahi, SPU_F_I10}, {SPU_ahi, SPU_F_I10}, {SPU_ahi, SPU_F_I10}, ++ /*0F0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0F4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0F8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0FC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*100*/ {SPU_brz, SPU_F_BREL}, {SPU_brz, SPU_F_BREL}, {SPU_brz, SPU_F_BREL}, {SPU_brz, SPU_F_BREL}, ++ /*104*/ {SPU_stqa, SPU_F_LQA}, {SPU_stqa, SPU_F_LQA}, {SPU_stqa, SPU_F_LQA}, {SPU_stqa, SPU_F_LQA}, ++ /*108*/ {SPU_brnz, SPU_F_BREL}, {SPU_brnz, SPU_F_BREL}, {SPU_brnz, SPU_F_BREL}, {SPU_brnz, SPU_F_BREL}, ++ /*10C*/ {SPU_mtspr, SPU_F_NONE}, {SPU_wrch, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*110*/ {SPU_brhz, SPU_F_BREL}, {SPU_brhz, SPU_F_BREL}, {SPU_brhz, SPU_F_BREL}, {SPU_brhz, SPU_F_BREL}, ++ /*114*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*118*/ {SPU_brhnz, SPU_F_BREL}, {SPU_brhnz, SPU_F_BREL}, {SPU_brhnz, SPU_F_BREL}, {SPU_brhnz, SPU_F_BREL}, ++ /*11C*/ {SPU_stqr, SPU_F_LQR}, {SPU_stqr, SPU_F_LQR}, {SPU_stqr, SPU_F_LQR}, {SPU_stqr, SPU_F_LQR}, ++ /*120*/ {SPU_stqd, SPU_F_I10Q}, {SPU_stqd, SPU_F_I10Q}, {SPU_stqd, SPU_F_I10Q}, {SPU_stqd, SPU_F_I10Q}, ++ /*124*/ {SPU_stqd, SPU_F_I10Q}, {SPU_stqd, SPU_F_I10Q}, {SPU_stqd, SPU_F_I10Q}, {SPU_stqd, SPU_F_I10Q}, ++ /*128*/ {SPU_biz, SPU_F_NONE}, {SPU_binz, SPU_F_NONE}, {SPU_bihz, SPU_F_NONE}, {SPU_bihnz, SPU_F_NONE}, ++ /*12C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*130*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*134*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*138*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*13C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*140*/ {SPU_stopd, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*144*/ {SPU_stqx, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*148*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*14C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*150*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*154*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*158*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*15C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*160*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*164*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*168*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*16C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*170*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*174*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*178*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*17C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*180*/ {SPU_bra, SPU_F_BABS}, {SPU_bra, SPU_F_BABS}, {SPU_bra, SPU_F_BABS}, {SPU_bra, SPU_F_BABS}, ++ /*184*/ {SPU_lqa, SPU_F_LQA}, {SPU_lqa, SPU_F_LQA}, {SPU_lqa, SPU_F_LQA}, {SPU_lqa, SPU_F_LQA}, ++ /*188*/ {SPU_brasl, SPU_F_BABS}, {SPU_brasl, SPU_F_BABS}, {SPU_brasl, SPU_F_BABS}, {SPU_brasl, SPU_F_BABS}, ++ /*18C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*190*/ {SPU_br, SPU_F_BREL}, {SPU_br, SPU_F_BREL}, {SPU_br, SPU_F_BREL}, {SPU_br, SPU_F_BREL}, ++ /*194*/ {SPU_fsmbi, SPU_F_I16U}, {SPU_fsmbi, SPU_F_I16U}, {SPU_fsmbi, SPU_F_I16U}, {SPU_fsmbi, SPU_F_I16U}, ++ /*198*/ {SPU_brsl, SPU_F_BREL}, {SPU_brsl, SPU_F_BREL}, {SPU_brsl, SPU_F_BREL}, {SPU_brsl, SPU_F_BREL}, ++ /*19C*/ {SPU_lqr, SPU_F_LQR}, {SPU_lqr, SPU_F_LQR}, {SPU_lqr, SPU_F_LQR}, {SPU_lqr, SPU_F_LQR}, ++ /*1A0*/ {SPU_lqd, SPU_F_I10Q}, {SPU_lqd, SPU_F_I10Q}, {SPU_lqd, SPU_F_I10Q}, {SPU_lqd, SPU_F_I10Q}, ++ /*1A4*/ {SPU_lqd, SPU_F_I10Q}, {SPU_lqd, SPU_F_I10Q}, {SPU_lqd, SPU_F_I10Q}, {SPU_lqd, SPU_F_I10Q}, ++ /*1A8*/ {SPU_bi, SPU_F_NONE}, {SPU_bisl, SPU_F_NONE}, {SPU_iret, SPU_F_NONE}, {SPU_bisled, SPU_F_NONE}, ++ /*1AC*/ {SPU_hbr, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1B0*/ {SPU_gb, SPU_F_NONE}, {SPU_gbh, SPU_F_NONE}, {SPU_gbb, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1B4*/ {SPU_fsm, SPU_F_NONE}, {SPU_fsmh, SPU_F_NONE}, {SPU_fsmb, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1B8*/ {SPU_frest, SPU_F_NONE}, {SPU_frsqest, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1BC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1C0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1C4*/ {SPU_lqx, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1C8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1CC*/ {SPU_rotqbybi, SPU_F_NONE}, {SPU_rotqmbybi, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_shlqbybi, SPU_F_NONE}, ++ /*1D0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1D4*/ {SPU_cbx, SPU_F_NONE}, {SPU_chx, SPU_F_NONE}, {SPU_cwx, SPU_F_NONE}, {SPU_cdx, SPU_F_NONE}, ++ /*1D8*/ {SPU_rotqbi, SPU_F_NONE}, {SPU_rotqmbi, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_shlqbi, SPU_F_NONE}, ++ /*1DC*/ {SPU_rotqby, SPU_F_NONE}, {SPU_rotqmby, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_shlqby, SPU_F_NONE}, ++ /*1E0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1E4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1E8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1EC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1F0*/ {SPU_orx, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1F4*/ {SPU_cbd, SPU_F_I7U}, {SPU_chd, SPU_F_I7U}, {SPU_cwd, SPU_F_I7U}, {SPU_cdd, SPU_F_I7U}, ++ /*1F8*/ {SPU_rotqbii, SPU_F_I7S}, {SPU_rotqmbii, SPU_F_I7S}, {SPU_word, SPU_F_NONE}, {SPU_shlqbii, SPU_F_I7S}, ++ /*1FC*/ {SPU_rotqbyi, SPU_F_I7S}, {SPU_rotqmbyi, SPU_F_I7S}, {SPU_word, SPU_F_NONE}, {SPU_shlqbyi, SPU_F_I7S}, ++ /*200*/ {SPU_word, SPU_F_NONE}, {SPU_nop, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*204*/ {SPU_il, SPU_F_I16S}, {SPU_il, SPU_F_I16S}, {SPU_il, SPU_F_I16S}, {SPU_il, SPU_F_I16S}, ++ /*208*/ {SPU_ilhu, SPU_F_I16U}, {SPU_ilhu, SPU_F_I16U}, {SPU_ilhu, SPU_F_I16U}, {SPU_ilhu, SPU_F_I16U}, ++ /*20C*/ {SPU_ilh, SPU_F_I16U}, {SPU_ilh, SPU_F_I16U}, {SPU_ilh, SPU_F_I16U}, {SPU_ilh, SPU_F_I16U}, ++ /*210*/ {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, ++ /*214*/ {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, ++ /*218*/ {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, ++ /*21C*/ {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, ++ /*220*/ {SPU_xori, SPU_F_I10}, {SPU_xori, SPU_F_I10}, {SPU_xori, SPU_F_I10}, {SPU_xori, SPU_F_I10}, ++ /*224*/ {SPU_xori, SPU_F_I10}, {SPU_xori, SPU_F_I10}, {SPU_xori, SPU_F_I10}, {SPU_xori, SPU_F_I10}, ++ /*228*/ {SPU_xorhi, SPU_F_I10}, {SPU_xorhi, SPU_F_I10}, {SPU_xorhi, SPU_F_I10}, {SPU_xorhi, SPU_F_I10}, ++ /*22C*/ {SPU_xorhi, SPU_F_I10}, {SPU_xorhi, SPU_F_I10}, {SPU_xorhi, SPU_F_I10}, {SPU_xorhi, SPU_F_I10}, ++ /*230*/ {SPU_xorbi, SPU_F_I10}, {SPU_xorbi, SPU_F_I10}, {SPU_xorbi, SPU_F_I10}, {SPU_xorbi, SPU_F_I10}, ++ /*234*/ {SPU_xorbi, SPU_F_I10}, {SPU_xorbi, SPU_F_I10}, {SPU_xorbi, SPU_F_I10}, {SPU_xorbi, SPU_F_I10}, ++ /*238*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*23C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*240*/ {SPU_cgt, SPU_F_NONE}, {SPU_xor, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*244*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*248*/ {SPU_cgth, SPU_F_NONE}, {SPU_eqv, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*24C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*250*/ {SPU_cgtb, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_sumb, SPU_F_NONE}, ++ /*254*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*258*/ {SPU_hgt, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*25C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*260*/ {SPU_cgti, SPU_F_I10}, {SPU_cgti, SPU_F_I10}, {SPU_cgti, SPU_F_I10}, {SPU_cgti, SPU_F_I10}, ++ /*264*/ {SPU_cgti, SPU_F_I10}, {SPU_cgti, SPU_F_I10}, {SPU_cgti, SPU_F_I10}, {SPU_cgti, SPU_F_I10}, ++ /*268*/ {SPU_cgthi, SPU_F_I10}, {SPU_cgthi, SPU_F_I10}, {SPU_cgthi, SPU_F_I10}, {SPU_cgthi, SPU_F_I10}, ++ /*26C*/ {SPU_cgthi, SPU_F_I10}, {SPU_cgthi, SPU_F_I10}, {SPU_cgthi, SPU_F_I10}, {SPU_cgthi, SPU_F_I10}, ++ /*270*/ {SPU_cgtbi, SPU_F_I10}, {SPU_cgtbi, SPU_F_I10}, {SPU_cgtbi, SPU_F_I10}, {SPU_cgtbi, SPU_F_I10}, ++ /*274*/ {SPU_cgtbi, SPU_F_I10}, {SPU_cgtbi, SPU_F_I10}, {SPU_cgtbi, SPU_F_I10}, {SPU_cgtbi, SPU_F_I10}, ++ /*278*/ {SPU_hgti, SPU_F_I10}, {SPU_hgti, SPU_F_I10}, {SPU_hgti, SPU_F_I10}, {SPU_hgti, SPU_F_I10}, ++ /*27C*/ {SPU_hgti, SPU_F_I10}, {SPU_hgti, SPU_F_I10}, {SPU_hgti, SPU_F_I10}, {SPU_hgti, SPU_F_I10}, ++ /*280*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*284*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*288*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*28C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*290*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*294*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*298*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*29C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2A0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2A4*/ {SPU_word, SPU_F_NONE}, {SPU_clz, SPU_F_NONE}, {SPU_xswd, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2A8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2AC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_xshw, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2B0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2B4*/ {SPU_cntb, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_xsbh, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2B8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2BC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2C0*/ {SPU_clgt, SPU_F_NONE}, {SPU_andc, SPU_F_NONE}, {SPU_fcgt, SPU_F_NONE}, {SPU_dfcgt, SPU_F_NONE}, ++ /*2C4*/ {SPU_fa, SPU_F_NONE}, {SPU_fs, SPU_F_NONE}, {SPU_fm, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2C8*/ {SPU_clgth, SPU_F_NONE}, {SPU_orc, SPU_F_NONE}, {SPU_fcmgt, SPU_F_NONE}, {SPU_dfcmgt, SPU_F_NONE}, ++ /*2CC*/ {SPU_dfa, SPU_F_NONE}, {SPU_dfs, SPU_F_NONE}, {SPU_dfm, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2D0*/ {SPU_clgtb, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2D4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2D8*/ {SPU_hlgt, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2DC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2E0*/ {SPU_clgti, SPU_F_I10}, {SPU_clgti, SPU_F_I10}, {SPU_clgti, SPU_F_I10}, {SPU_clgti, SPU_F_I10}, ++ /*2E4*/ {SPU_clgti, SPU_F_I10}, {SPU_clgti, SPU_F_I10}, {SPU_clgti, SPU_F_I10}, {SPU_clgti, SPU_F_I10}, ++ /*2E8*/ {SPU_clgthi, SPU_F_I10}, {SPU_clgthi, SPU_F_I10}, {SPU_clgthi, SPU_F_I10}, {SPU_clgthi, SPU_F_I10}, ++ /*2EC*/ {SPU_clgthi, SPU_F_I10}, {SPU_clgthi, SPU_F_I10}, {SPU_clgthi, SPU_F_I10}, {SPU_clgthi, SPU_F_I10}, ++ /*2F0*/ {SPU_clgtbi, SPU_F_I10}, {SPU_clgtbi, SPU_F_I10}, {SPU_clgtbi, SPU_F_I10}, {SPU_clgtbi, SPU_F_I10}, ++ /*2F4*/ {SPU_clgtbi, SPU_F_I10}, {SPU_clgtbi, SPU_F_I10}, {SPU_clgtbi, SPU_F_I10}, {SPU_clgtbi, SPU_F_I10}, ++ /*2F8*/ {SPU_hlgti, SPU_F_I10}, {SPU_hlgti, SPU_F_I10}, {SPU_hlgti, SPU_F_I10}, {SPU_hlgti, SPU_F_I10}, ++ /*2FC*/ {SPU_hlgti, SPU_F_I10}, {SPU_hlgti, SPU_F_I10}, {SPU_hlgti, SPU_F_I10}, {SPU_hlgti, SPU_F_I10}, ++ /*300*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*304*/ {SPU_iohl, SPU_F_I16U}, {SPU_iohl, SPU_F_I16U}, {SPU_iohl, SPU_F_I16U}, {SPU_iohl, SPU_F_I16U}, ++ /*308*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*30C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*310*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*314*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*318*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*31C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*320*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*324*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*328*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*32C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*330*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*334*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*338*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*33C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*340*/ {SPU_addx, SPU_F_NONE}, {SPU_sfx, SPU_F_NONE}, {SPU_cgx, SPU_F_NONE}, {SPU_bgx, SPU_F_NONE}, ++ /*344*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_mpyhha, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*348*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*34C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_mpyhhau, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*350*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*354*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*358*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*35C*/ {SPU_dfma, SPU_F_NONE}, {SPU_dfms, SPU_F_NONE}, {SPU_dfnms, SPU_F_NONE}, {SPU_dfnma, SPU_F_NONE}, ++ /*360*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*364*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*368*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*36C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*370*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*374*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*378*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*37C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*380*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*384*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*388*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*38C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*390*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*394*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*398*/ {SPU_fscrrd, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*39C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3A0*/ {SPU_mpyi, SPU_F_I10}, {SPU_mpyi, SPU_F_I10}, {SPU_mpyi, SPU_F_I10}, {SPU_mpyi, SPU_F_I10}, ++ /*3A4*/ {SPU_mpyi, SPU_F_I10}, {SPU_mpyi, SPU_F_I10}, {SPU_mpyi, SPU_F_I10}, {SPU_mpyi, SPU_F_I10}, ++ /*3A8*/ {SPU_mpyui, SPU_F_I10}, {SPU_mpyui, SPU_F_I10}, {SPU_mpyui, SPU_F_I10}, {SPU_mpyui, SPU_F_I10}, ++ /*3AC*/ {SPU_mpyui, SPU_F_I10}, {SPU_mpyui, SPU_F_I10}, {SPU_mpyui, SPU_F_I10}, {SPU_mpyui, SPU_F_I10}, ++ /*3B0*/ {SPU_cflts, SPU_F_I8}, {SPU_cflts, SPU_F_I8}, {SPU_cfltu, SPU_F_I8}, {SPU_cfltu, SPU_F_I8}, ++ /*3B4*/ {SPU_csflt, SPU_F_I8}, {SPU_csflt, SPU_F_I8}, {SPU_cuflt, SPU_F_I8}, {SPU_cuflt, SPU_F_I8}, ++ /*3B8*/ {SPU_fesd, SPU_F_NONE}, {SPU_frds, SPU_F_NONE}, {SPU_fscrwr, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3BC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_dftsv, SPU_F_NONE}, ++ /*3C0*/ {SPU_ceq, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_fceq, SPU_F_NONE}, {SPU_dfceq, SPU_F_NONE}, ++ /*3C4*/ {SPU_mpy, SPU_F_NONE}, {SPU_mpyh, SPU_F_NONE}, {SPU_mpyhh, SPU_F_NONE}, {SPU_mpys, SPU_F_NONE}, ++ /*3C8*/ {SPU_ceqh, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_fcmeq, SPU_F_NONE}, {SPU_dfcmeq, SPU_F_NONE}, ++ /*3CC*/ {SPU_mpyu, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_mpyhhu, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3D0*/ {SPU_ceqb, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3D4*/ {SPU_fi, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3D8*/ {SPU_heq, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3DC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3E0*/ {SPU_ceqi, SPU_F_I10}, {SPU_ceqi, SPU_F_I10}, {SPU_ceqi, SPU_F_I10}, {SPU_ceqi, SPU_F_I10}, ++ /*3E4*/ {SPU_ceqi, SPU_F_I10}, {SPU_ceqi, SPU_F_I10}, {SPU_ceqi, SPU_F_I10}, {SPU_ceqi, SPU_F_I10}, ++ /*3E8*/ {SPU_ceqhi, SPU_F_I10}, {SPU_ceqhi, SPU_F_I10}, {SPU_ceqhi, SPU_F_I10}, {SPU_ceqhi, SPU_F_I10}, ++ /*3EC*/ {SPU_ceqhi, SPU_F_I10}, {SPU_ceqhi, SPU_F_I10}, {SPU_ceqhi, SPU_F_I10}, {SPU_ceqhi, SPU_F_I10}, ++ /*3F0*/ {SPU_ceqbi, SPU_F_I10}, {SPU_ceqbi, SPU_F_I10}, {SPU_ceqbi, SPU_F_I10}, {SPU_ceqbi, SPU_F_I10}, ++ /*3F4*/ {SPU_ceqbi, SPU_F_I10}, {SPU_ceqbi, SPU_F_I10}, {SPU_ceqbi, SPU_F_I10}, {SPU_ceqbi, SPU_F_I10}, ++ /*3F8*/ {SPU_heqi, SPU_F_I10}, {SPU_heqi, SPU_F_I10}, {SPU_heqi, SPU_F_I10}, {SPU_heqi, SPU_F_I10}, ++ /*3FC*/ {SPU_heqi, SPU_F_I10}, {SPU_heqi, SPU_F_I10}, {SPU_heqi, SPU_F_I10}, {SPU_heqi, SPU_F_I10}, ++ /*400*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*404*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*408*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*40C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*410*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*414*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*418*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*41C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*420*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*424*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*428*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*42C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*430*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*434*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*438*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*43C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*440*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*444*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*448*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*44C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*450*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*454*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*458*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*45C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*460*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*464*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*468*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*46C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*470*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*474*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*478*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*47C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*480*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*484*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*488*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*48C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*490*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*494*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*498*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*49C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4A0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4A4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4A8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4AC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4B0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4B4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4B8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4BC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4C0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4C4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4C8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4CC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4D0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4D4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4D8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4DC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4E0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4E4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4E8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4EC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4F0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4F4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4F8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4FC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*500*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*504*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*508*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*50C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*510*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*514*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*518*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*51C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*520*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*524*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*528*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*52C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*530*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*534*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*538*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*53C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*540*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*544*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*548*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*54C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*550*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*554*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*558*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*55C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*560*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*564*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*568*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*56C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*570*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*574*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*578*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*57C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*580*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*584*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*588*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*58C*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*590*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*594*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*598*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*59C*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5A0*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5A4*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5A8*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5AC*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5B0*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5B4*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5B8*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5BC*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5C0*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5C4*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5C8*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5CC*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5D0*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5D4*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5D8*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5DC*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5E0*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5E4*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5E8*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5EC*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5F0*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5F4*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5F8*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5FC*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*600*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*604*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*608*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*60C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*610*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*614*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*618*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*61C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*620*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*624*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*628*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*62C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*630*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*634*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*638*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*63C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*640*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*644*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*648*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*64C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*650*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*654*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*658*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*65C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*660*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*664*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*668*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*66C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*670*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*674*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*678*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*67C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*680*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*684*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*688*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*68C*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*690*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*694*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*698*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*69C*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6A0*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6A4*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6A8*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6AC*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6B0*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6B4*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6B8*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6BC*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6C0*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6C4*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6C8*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6CC*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6D0*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6D4*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6D8*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6DC*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6E0*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6E4*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6E8*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6EC*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6F0*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6F4*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6F8*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6FC*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*700*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*704*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*708*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*70C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*710*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*714*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*718*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*71C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*720*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*724*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*728*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*72C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*730*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*734*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*738*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*73C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*740*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*744*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*748*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*74C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*750*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*754*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*758*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*75C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*760*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*764*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*768*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*76C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*770*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*774*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*778*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*77C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*780*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*784*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*788*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*78C*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*790*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*794*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*798*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*79C*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7A0*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7A4*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7A8*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7AC*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7B0*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7B4*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7B8*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7BC*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7C0*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7C4*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7C8*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7CC*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7D0*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7D4*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7D8*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7DC*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7E0*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7E4*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7E8*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7EC*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7F0*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7F4*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7F8*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7FC*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++}; +diff --git a/runtime/spu/tests/test_spu_decode.c b/runtime/spu/tests/test_spu_decode.c +new file mode 100644 +index 00000000..a5159e17 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_decode.c +@@ -0,0 +1,192 @@ ++/* The interpreter's decode contract: op and every field spu_decode1 hands to ++ * the execute switch, for instructions at the opcode-width and immediate-form ++ * boundaries. Encodings are built here from the SPU ISA field layouts (IBM SPU ++ * ISA v1.2, ch. 2), not from the generated table, so a table whose precedence ++ * or immediate forms drift fails against independent expectations. spu_decode1 ++ * is static, hence the include of the interpreter itself. */ ++#include "../spu_interp.c" ++#include <assert.h> ++#include <stdio.h> ++#include <string.h> ++ ++/* Decode-only test: nothing here executes, so the external hooks must never run. */ ++u128 spu_rdch(spu_context* c, uint32_t ch) { (void)c; (void)ch; abort(); } ++void spu_wrch(spu_context* c, uint32_t ch, u128 v) { (void)c; (void)ch; (void)v; abort(); } ++uint32_t spu_rchcnt(spu_context* c, uint32_t ch) { (void)c; (void)ch; abort(); } ++int g_spu_ls_watch_n, g_spu_ls_probe, g_wws_read_probe, g_wws_code_probe, g_spu_smc_watch; ++spu_lifted_fn spu_lifted_lookup(const spu_context* c, uint32_t a) { (void)c; (void)a; abort(); } ++void spu_spurs_taskset_syscall(spu_context* c) { (void)c; abort(); } ++void spu_ls_watch_slow(uint32_t l, int w, const uint8_t* p, uint32_t pc, uint32_t lr) { ++ (void)l; (void)w; (void)p; (void)pc; (void)lr; abort(); ++} ++ ++/* ISA layouts, bit 0 = LSB. */ ++static uint32_t rrr(uint32_t op4, uint32_t rt, uint32_t rb, uint32_t ra, uint32_t rc) { ++ return (op4 << 28) | (rt << 21) | (rb << 14) | (ra << 7) | rc; ++} ++static uint32_t ri18(uint32_t op7, uint32_t i18, uint32_t rt) { ++ return (op7 << 25) | ((i18 & 0x3FFFF) << 7) | rt; ++} ++static uint32_t ri16(uint32_t op9, uint32_t i16, uint32_t rt) { ++ return (op9 << 23) | ((i16 & 0xFFFF) << 7) | rt; ++} ++static uint32_t ri10(uint32_t op8, uint32_t i10, uint32_t ra, uint32_t rt) { ++ return (op8 << 24) | ((i10 & 0x3FF) << 14) | (ra << 7) | rt; ++} ++static uint32_t ri8(uint32_t op10, uint32_t i8, uint32_t ra, uint32_t rt) { ++ return (op10 << 22) | ((i8 & 0xFF) << 14) | (ra << 7) | rt; ++} ++/* RI7 and RR share the 11-bit opcode; RR's rb sits where RI7's i7 does. */ ++static uint32_t ri7(uint32_t op11, uint32_t i7, uint32_t ra, uint32_t rt) { ++ return (op11 << 21) | ((i7 & 0x7F) << 14) | (ra << 7) | rt; ++} ++ ++static int failures; ++static spu_ins dec(uint32_t insn, uint32_t pc) { ++ spu_ins d; ++ memset(&d, 0xFF, sizeof d); /* decode must overwrite every field, not leak the caller's */ ++ spu_decode1(insn, pc, &d); ++ return d; ++} ++#define CHECK(cond, what, insn) do { if (!(cond)) { \ ++ fprintf(stderr, "FAIL %s insn=%08X: %s\n", what, (unsigned)(insn), #cond); ++failures; } } while (0) ++ ++static void expect_imm(const char* what, uint32_t insn, spu_op op, int32_t imm) { ++ spu_ins d = dec(insn, 0x100); ++ CHECK(d.op == op, what, insn); ++ CHECK(d.imm == imm, what, insn); ++ CHECK(d.tgt == 0, what, insn); ++} ++static void expect_tgt(const char* what, uint32_t insn, uint32_t pc, spu_op op, uint32_t tgt) { ++ spu_ins d = dec(insn, pc); ++ CHECK(d.op == op, what, insn); ++ CHECK(d.tgt == tgt, what, insn); ++ CHECK(d.imm == 0, what, insn); ++} ++ ++int main(void) { ++ /* RRR: shufb rt=5 rb=6 ra=7 rc=8. The destination is the high field, which ++ * the interpreter calls rc; the low field is the third source (rt). */ ++ { ++ uint32_t i = rrr(0xB, 5, 6, 7, 8); ++ spu_ins d = dec(i, 0); ++ CHECK(d.op == SPU_shufb, "shufb", i); ++ CHECK(d.rc == 5 && d.rb == 6 && d.ra == 7 && d.rt == 8, "shufb fields", i); ++ CHECK(d.imm == 0 && d.tgt == 0, "shufb no imm", i); ++ } ++ ++ /* RI18 */ ++ expect_imm("ila 18 bits", ri18(0x21, 0x3FFFF, 3), SPU_ila, 0x3FFFF); ++ expect_imm("ila high bit", ri18(0x21, 0x20000, 3), SPU_ila, 0x20000); ++ { ++ spu_ins d = dec(ri18(0x21, 0x2ABCD, 9), 0); ++ CHECK(d.rt == 9, "ila rt", 0); ++ } ++ ++ /* Hints (hbra/hbrr) are the other RI18 ops: only the low 16 bits of the ++ * 18-bit field are the immediate; the top two belong to the split ROH field. */ ++ expect_imm("hbra low 16", ri18(0x08, 0x3FFFF, 3), SPU_hbra, 0xFFFF); ++ expect_imm("hbrr low 16", ri18(0x09, 0x2ABCD, 3), SPU_hbrr, 0xABCD); ++ ++ /* RI16 immediates: il sign-extends; ilh/ilhu/iohl/fsmbi zero-extend. */ ++ expect_imm("il negative", ri16(0x081, 0x8000, 4), SPU_il, -32768); ++ expect_imm("il -1", ri16(0x081, 0xFFFF, 4), SPU_il, -1); ++ expect_imm("il positive", ri16(0x081, 0x7FFF, 4), SPU_il, 0x7FFF); ++ expect_imm("ilhu", ri16(0x082, 0xFFFF, 4), SPU_ilhu, 0xFFFF); ++ expect_imm("ilh", ri16(0x083, 0x8001, 4), SPU_ilh, 0x8001); ++ expect_imm("iohl unsigned", ri16(0x0C1, 0x8000, 4), SPU_iohl, 0x8000); ++ expect_imm("fsmbi", ri16(0x065, 0xFFFF, 4), SPU_fsmbi, 0xFFFF); ++ ++ /* RI16 targets: pc-relative forms add pc, absolute ones do not; the ++ * quadword forms mask to 16-byte alignment, branches to word alignment. */ ++ expect_tgt("lqr back", ri16(0x067, 0xFFFF, 4), 0x104, SPU_lqr, 0x100); ++ expect_tgt("stqr back", ri16(0x047, 0xFFFF, 4), 0x104, SPU_stqr, 0x100); ++ expect_tgt("lqr wraps past 256K", ri16(0x067, 8, 4), 0x3FFF0, SPU_lqr, 0x10); ++ expect_tgt("lqr wraps below 0", ri16(0x067, 0xFFF0, 4), 0x20, SPU_lqr, 0x3FFE0); ++ expect_tgt("br wraps past 256K", ri16(0x064, 1, 0), 0x3FFFC, SPU_br, 0); ++ expect_tgt("br wraps below 0", ri16(0x064, 0xFFFF, 0), 0, SPU_br, 0x3FFFC); ++ expect_tgt("br forward", ri16(0x064, 0x10, 0), 0x200, SPU_br, 0x240); ++ expect_tgt("brsl", ri16(0x066, 4, 0), 0x400, SPU_brsl, 0x410); ++ expect_tgt("brz", ri16(0x040, 2, 3), 0x800, SPU_brz, 0x808); ++ expect_tgt("brnz", ri16(0x042, 0xFFFE, 3), 0x800, SPU_brnz, 0x7F8); ++ expect_tgt("brhz", ri16(0x044, 1, 3), 0x800, SPU_brhz, 0x804); ++ expect_tgt("brhnz", ri16(0x046, 1, 3), 0x800, SPU_brhnz, 0x804); ++ expect_tgt("bra ignores pc", ri16(0x060, 0x4000, 0), 0x3FFFC, SPU_bra, 0x10000); ++ expect_tgt("bra negative", ri16(0x060, 0xFFFF, 0), 0x100, SPU_bra, 0x3FFFC); ++ expect_tgt("brasl", ri16(0x062, 3, 0), 0x100, SPU_brasl, 0xC); ++ expect_tgt("lqa", ri16(0x061, 0xFFFF, 4), 0x100, SPU_lqa, 0x3FFF0); ++ expect_tgt("stqa", ri16(0x041, 0x0123, 4), 0x100, SPU_stqa, 0x0480); ++ ++ /* RI10: lqd/stqd scale the displacement by 16; the rest do not. */ ++ expect_imm("lqd +3", ri10(0x34, 3, 1, 2), SPU_lqd, 48); ++ expect_imm("lqd -2", ri10(0x34, 0x3FE, 1, 2), SPU_lqd, -32); ++ expect_imm("stqd -512", ri10(0x24, 0x200, 1, 2), SPU_stqd, -8192); ++ expect_imm("stqd +511", ri10(0x24, 0x1FF, 1, 2), SPU_stqd, 8176); ++ expect_imm("ai -1", ri10(0x1C, 0x3FF, 1, 2), SPU_ai, -1); ++ expect_imm("ori +511", ri10(0x04, 0x1FF, 1, 2), SPU_ori, 511); ++ { ++ uint32_t i = ri10(0x1C, 0x155, 17, 90); ++ spu_ins d = dec(i, 0); ++ CHECK(d.ra == 17 && d.rt == 90 && d.ch == 17, "ai fields", i); ++ } ++ ++ /* Channel ops are 11-bit opcodes; wrch (0x10D) must not be taken for the ++ * shift-immediate family whose 11-bit opcode (shli 0x07B) differs. */ ++ { ++ uint32_t i = ri7(0x00D, 0, 5, 6); /* rdch $6, $ch5 */ ++ spu_ins d = dec(i, 0); ++ CHECK(d.op == SPU_rdch && d.ch == 5 && d.rt == 6 && d.imm == 0, "rdch", i); ++ i = ri7(0x10D, 0, 7, 8); ++ d = dec(i, 0); ++ CHECK(d.op == SPU_wrch && d.ch == 7 && d.rt == 8 && d.imm == 0, "wrch", i); ++ i = ri7(0x00F, 0, 9, 10); ++ d = dec(i, 0); ++ CHECK(d.op == SPU_rchcnt && d.ch == 9 && d.rt == 10 && d.imm == 0, "rchcnt", i); ++ /* The whole 7-bit channel field reaches spu_rdch/spu_wrch; SPU channels go up to 127. */ ++ i = ri7(0x00D, 0, 0x7F, 1); ++ d = dec(i, 0); ++ CHECK(d.op == SPU_rdch && d.ch == 0x7F && d.rt == 1, "rdch channel 127", i); ++ expect_imm("shli is not wrch", ri7(0x07B, 3, 5, 6), SPU_shli, 3); ++ } ++ ++ /* STOP: 14-bit signal type, and no other RR form carries an immediate. */ ++ expect_imm("stop 14 bits", 0x00003FFFu, SPU_stop, 0x3FFF); ++ expect_imm("stop 0x2A5", 0x000002A5u, SPU_stop, 0x2A5); ++ expect_imm("stop ignores bit 14", 0x00004001u, SPU_stop, 1); ++ expect_imm("a has no imm", ri7(0x0C0, 0x7F, 1, 2), SPU_a, 0); ++ ++ /* RI7: shifts/rotates sign-extend, the generate-controls zero-extend. */ ++ expect_imm("shli -64", ri7(0x07B, 0x40, 1, 2), SPU_shli, -64); ++ expect_imm("roti 63", ri7(0x078, 0x3F, 1, 2), SPU_roti, 63); ++ expect_imm("rotqbyi -1", ri7(0x1FC, 0x7F, 1, 2), SPU_rotqbyi, -1); ++ expect_imm("cwd 64 unsigned", ri7(0x1F6, 0x40, 1, 2), SPU_cwd, 64); ++ expect_imm("cbd 127 unsigned", ri7(0x1F4, 0x7F, 1, 2), SPU_cbd, 127); ++ ++ /* RI8: unsigned 8-bit scale, for all four conversions. */ ++ expect_imm("cflts 255", ri8(0x1D8, 0xFF, 1, 2), SPU_cflts, 255); ++ expect_imm("cfltu 255", ri8(0x1D9, 0xFF, 1, 2), SPU_cfltu, 255); ++ expect_imm("csflt 0x81", ri8(0x1DA, 0x81, 1, 2), SPU_csflt, 0x81); ++ expect_imm("cuflt 0x80", ri8(0x1DB, 0x80, 1, 2), SPU_cuflt, 0x80); ++ ++ /* RR/LSX register forms. */ ++ { ++ uint32_t i = ri7(0x1C4, 11, 12, 13); /* lqx $13, $12, $11 */ ++ spu_ins d = dec(i, 0); ++ CHECK(d.op == SPU_lqx && d.rb == 11 && d.ra == 12 && d.rt == 13 && d.imm == 0 && d.tgt == 0, ++ "lqx", i); ++ i = ri7(0x144, 11, 12, 13); ++ d = dec(i, 0); ++ CHECK(d.op == SPU_stqx && d.rb == 11 && d.ra == 12 && d.rt == 13, "stqx", i); ++ } ++ ++ /* A word no table claims traps as `.word`, with no immediate. */ ++ { ++ uint32_t i = 0x00800000u; /* 11-bit opcode 0x004 */ ++ spu_ins d = dec(i, 0x40); ++ CHECK(d.op == SPU_word && d.imm == 0 && d.tgt == 0, "invalid word", i); ++ } ++ ++ if (failures) { fprintf(stderr, "%d failure(s)\n", failures); return 1; } ++ printf("spu_decode1: all contract checks passed\n"); ++ return 0; ++} +diff --git a/tools/gen_spu_interp.py b/tools/gen_spu_interp.py +old mode 100644 +new mode 100755 +index 4f658c1e..77ac8f16 +--- a/tools/gen_spu_interp.py ++++ b/tools/gen_spu_interp.py +@@ -1,5 +1,5 @@ + #!/usr/bin/env python3 +-"""Generate the SPU interpreter's decode tables (C) from the validated Python ++"""Generate the SPU interpreter's decode table (C) from the validated Python + decoder (spu_disasm.py). The interpreter is the correctness floor for the SPU + static recompiler: computed/indirect branches (`bi $reg`) and DMA'd or + self-modified code (LBP overlays, spu_0004's `sync; bi $3` trampoline) can't be +@@ -30,13 +30,14 @@ RI7 = { + RI7_UNSIGNED = {"cbd", "chd", "cwd", "cdd"} + RI8 = {0x1d8: "cflts", 0x1d9: "cfltu", 0x1da: "csflt", 0x1db: "cuflt"} # op10 + LSX = {0x1c4: "lqx", 0x144: "stqx"} ++CHANNEL = {0x00D: "rdch", 0x10D: "wrch", 0x00F: "rchcnt"} # op11 + + # Every mnemonic the decoder can emit -> a stable enum. `.word` is the trap. + all_mn = set() + for t in (D.RRR_TABLE, D.RI18_TABLE, D.RI16_TABLE, D.RI10_TABLE, D.SPU_RR, +- RI7, RI8, LSX): ++ RI7, RI8, LSX, CHANNEL): + all_mn.update(t.values()) +-all_mn.update(["rdch", "wrch", "rchcnt", ".word"]) ++all_mn.add(".word") + mnems = sorted(all_mn) + + +@@ -44,11 +45,92 @@ def enum_name(m): + return "SPU_" + ("word" if m == ".word" else m) + + ++# Every opcode field of the SPU ISA (RRR 4 bits, RI18 7, RI16 9, RI10 8, RI8 10, ++# RI7/RR/LSX/channel 11) is a prefix of instruction bits 31..21, so the matched ++# mnemonic is a pure function of p = insn >> 21 and the whole decode collapses ++# into one 2048-entry table. The immediate form is a function of the matched ++# mnemonic and of the table it came from; the position-fixed operand fields ++# (rt/ra/rb/rc/ch) stay in spu_decode1. ++# ++# Prefixes may match more than one table, and the first stage to match wins, so ++# this order IS the decoder's precedence and mirrors spu_disasm.spu_decode: ++# RI16 before RI10 (an RI10 opcode equal to the top 8 bits of an RI16 opcode ++# must not shadow it), channel ops before RI10, RR before RI7, LSX last, else ++# `.word`. With the current tables the only prefixes matched twice are ++# rdch/rchcnt/wrch (channel and RR) and lqx/stqx (RR and LSX), where both ++# stages agree; the order is kept so a table entry added later resolves ++# exactly as the old cascade did instead of silently changing which ++# instruction executes. ++STAGES = ( ++ ("rrr", 4, D.RRR_TABLE), ++ ("ri18", 7, D.RI18_TABLE), ++ ("ri16", 9, D.RI16_TABLE), ++ ("chan", 11, CHANNEL), ++ ("ri10", 8, D.RI10_TABLE), ++ ("ri8", 10, RI8), ++ ("rr", 11, D.SPU_RR), ++ ("ri7", 11, RI7), ++ ("lsx", 11, LSX), ++) ++ ++# How spu_decode1 derives `imm` / `tgt` for a decoded instruction. ++FORMS = ( ++ ("NONE", "no immediate: RRR, RR (except stop), LSX, channel ops, .word"), ++ ("I18", "ila: full 18-bit immediate"), ++ ("I18LO", "other RI18 (hbra/hbrr): low 16 bits of the 18-bit field"), ++ ("LQA", "lqa/stqa: absolute 16-byte aligned LS address in tgt"), ++ ("LQR", "lqr/stqr: pc-relative 16-byte aligned LS address in tgt"), ++ ("BREL", "br/brsl/brz/brnz/brhz/brhnz: pc-relative target in tgt"), ++ ("BABS", "bra/brasl: absolute target in tgt"), ++ ("I16S", "il: sign-extended 16-bit immediate"), ++ ("I16U", "ilh/ilhu/iohl/fsmbi: zero-extended 16-bit immediate"), ++ ("I10", "RI10: sign-extended 10-bit immediate"), ++ ("I10Q", "lqd/stqd: sign-extended 10-bit immediate scaled by 16"), ++ ("I8", "RI8 float<->int conversions: unsigned 8-bit scale"), ++ ("STOP", "stop: 14-bit signal type"), ++ ("I7S", "RI7: sign-extended 7-bit immediate"), ++ ("I7U", "cbd/chd/cwd/cdd: unsigned 7-bit immediate"), ++) ++ ++RI16_FORMS = { ++ "lqa": "LQA", "stqa": "LQA", "lqr": "LQR", "stqr": "LQR", ++ "br": "BREL", "brsl": "BREL", "brz": "BREL", "brnz": "BREL", ++ "brhz": "BREL", "brhnz": "BREL", "bra": "BABS", "brasl": "BABS", ++ "il": "I16S", ++} ++ ++ ++def form_of(stage, mn): ++ if stage == "ri18": ++ return "I18" if mn == "ila" else "I18LO" ++ if stage == "ri16": ++ return RI16_FORMS.get(mn, "I16U") ++ if stage == "ri10": ++ return "I10Q" if mn in ("lqd", "stqd") else "I10" ++ if stage == "ri8": ++ return "I8" ++ if stage == "rr": ++ return "STOP" if mn == "stop" else "NONE" ++ if stage == "ri7": ++ return "I7U" if mn in RI7_UNSIGNED else "I7S" ++ return "NONE" ++ ++ ++def decode_prefix(p): ++ """(mnemonic, form) for the 11-bit prefix p = insn >> 21.""" ++ for stage, bits, table in STAGES: ++ mn = table.get(p >> (11 - bits)) ++ if mn is not None: ++ return mn, form_of(stage, mn) ++ return ".word", "NONE" ++ ++ + out = [] + w = out.append + w("/* GENERATED by tools/gen_spu_interp.py -- do not edit. */") +-w("/* Opcode->mnemonic tables for the SPU interpreter, from the validated") +-w(" * spu_disasm.py decoder. Regenerate after any decoder table change. */") ++w("/* Opcode->mnemonic enum and the insn>>21 decode table for the SPU") ++w(" * interpreter, from the validated spu_disasm.py decoder. Regenerate after") ++w(" * any decoder table change. */") + w("") + w("typedef enum {") + for m in mnems: +@@ -61,31 +143,23 @@ for m in mnems: + w(f' [{enum_name(m)}] = "{m}",') + w("};") + w("") +- +- +-def emit_lookup(fn, table, argbits, argname): +- w(f"static spu_op {fn}(uint32_t {argname}) {{") +- w(" switch (%s) {" % argname) +- for k in sorted(table): +- w(f" case 0x{k:X}: return {enum_name(table[k])};") +- w(f" default: return SPU_word;") +- w(" }") +- w("}") +- w("") +- +- +-emit_lookup("spu_dec_rrr", D.RRR_TABLE, 4, "op4") +-emit_lookup("spu_dec_ri18", D.RI18_TABLE, 7, "op7") +-emit_lookup("spu_dec_ri16", D.RI16_TABLE, 9, "op9") +-emit_lookup("spu_dec_ri10", D.RI10_TABLE, 8, "op8") +-emit_lookup("spu_dec_ri8", RI8, 10, "op10") +-emit_lookup("spu_dec_rr", D.SPU_RR, 11, "op11") +-emit_lookup("spu_dec_ri7", RI7, 11, "op11") +-emit_lookup("spu_dec_lsx", LSX, 11, "op11") +- +-w("/* signed-vs-unsigned i7 per instruction (Table 2-6) */") +-w("static int spu_ri7_unsigned(spu_op op) {") +-w(" return %s;" % " || ".join(f"op == {enum_name(m)}" for m in sorted(RI7_UNSIGNED))) +-w("}") ++w("/* How spu_decode1 derives imm/tgt. */") ++w("typedef enum {") ++for f, why in FORMS: ++ w(f" SPU_F_{f}, /* {why} */") ++w("} spu_decode_form;") ++w("") ++w("typedef struct { uint8_t op; uint8_t form; } spu_decode_ent;") ++w('_Static_assert(SPU_OP_COUNT <= 256, "spu_op must fit spu_decode_ent.op");') ++w("") ++w("/* Indexed by insn >> 21; precedence is documented in tools/gen_spu_interp.py. */") ++w("static const spu_decode_ent spu_decode_tab[2048] = {") ++for base in range(0, 2048, 4): ++ cells = [] ++ for p in range(base, base + 4): ++ mn, form = decode_prefix(p) ++ cells.append("{%s, SPU_F_%s}," % (enum_name(mn), form)) ++ w(f" /*{base:03X}*/ " + " ".join(cells)) ++w("};") + + sys.stdout.write("\n".join(out) + "\n") diff --git a/tasks/sp00nznet__ps3recomp-688/solution/solve.sh b/tasks/sp00nznet__ps3recomp-688/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-688/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-688/task.toml b/tasks/sp00nznet__ps3recomp-688/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..906704b4f383d88a8453bdb93107afcc0ee21cc7 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-688/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-688" +description = "spu_interp: decode by one 2048-entry table indexed by insn >> 21" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/688" +source_access = "auto" +built_at = "2026-11-16T16:09:59.631079+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:42b95f4e6a2a74c8c57f8e91bc85d8b67ddb8bc9754776b957ae2cf9c92898f0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "CMakeLists.txt", + "runtime/spu/spu_interp.c", + "runtime/spu/spu_interp_tables.inc", + "runtime/spu/tests/test_spu_decode.c", + "tools/gen_spu_interp.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 1208 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.156925+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-688/tests/capture.py b/tasks/sp00nznet__ps3recomp-688/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-688/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-688/tests/instruction.md b/tasks/sp00nznet__ps3recomp-688/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..103c80e674098dae414d525560686935cefefa3c --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-688/tests/instruction.md @@ -0,0 +1,109 @@ +# Issue + +**Title:** spu_interp: decode by one 2048-entry table indexed by insn >> 21 + +## Description + +## Summary +Replaces the SPU interpreter's decode cascade in `spu_decode1` with a single 2048-entry table lookup indexed by `insn >> 21`. + +This change is **decode-only**: `spu_ins`, instruction execution semantics, and the execute `switch` are unchanged. `tools/gen_spu_interp.py` generates the C decode table from the imported opcode tables plus the RI7/RI8/LSX/channel definitions it already mirrored; the generated file is checked for freshness. + +## Motivation +In interpreted SPU workloads, instruction decode takes a large share of SPU worker CPU. A Time Profiler of one title put 37 % of its audio job queue's worker CPU and 29 % of its frame job queue's inside `spu_decode1`. + +### The cascade +Previously, `spu_decode1` evaluated every instruction by walking a sequential cascade of generated `switch` helper functions and channel comparisons: +1. RRR (4 bits) via `spu_dec_rrr` +2. RI18 (7 bits) via `spu_dec_ri18` +3. RI16 (9 bits) via `spu_dec_ri16` +4. Channel ops (11 bits) via direct compares for `rdch`, `wrch`, `rchcnt` +5. RI10 (8 bits) via `spu_dec_ri10` +6. RI8 (10 bits) via `spu_dec_ri8` +7. RR (11 bits) via `spu_dec_rr` +8. RI7 (11 bits) via `spu_dec_ri7` +9. LSX (11 bits) via `spu_dec_lsx` +10. Fallback to `SPU_word` + +In addition to this chain of calls and branches per instruction, `spu_decode1` eagerly computed 10-bit, 16-bit, and 18-bit sign- and zero-extended immediate fields up front regardless of which instruction form matched. + +## Why a table is exact +Every SPU opcode field in the ISA is between 4 and 11 bits wide: +- RRR: 4 bits (`insn[31:28]`) +- RI18: 7 bits (`insn[31:25]`) +- RI10: 8 bits (`insn[31:24]`) +- RI16: 9 bits (`insn[31:23]`) +- RI8: 10 bits (`insn[31:22]`) +- RR / RI7 / LSX / Channel: 11 bits (`insn[31:21]`) + +Because every opcode field is a prefix of bits 31..21, the decoded mnemonic and its precedence in the cascade are a pure function of `insn >> 21`. + +`tools/gen_spu_interp.py` now resolves all 2048 possible 11-bit prefixes against the exact precedence order of the old cascade and emits a static 2048-entry table (`spu_decode_tab`) of compact entries (`spu_decode_ent` with 1-byte `op` and 1-byte immediate `form`). + +`spu_decode1` indexes this table with a single load (`insn >> 21`) and evaluates only the specific immediate or target field required by that form. + +## Changes +- `tools/gen_spu_interp.py`: + - Evaluates all 2048 11-bit prefixes using the existing cascade precedence order (RRR -> RI18 -> RI16 -> Channel -> RI10 -> RI8 -> RR -> RI7 -> LSX -> .word). + - Emits `spu_decode_tab[2048]` with `op` and `form`. + - Removes unused `spu_dec_*` functions and `spu_ri7_unsigned`. +- `runtime/spu/spu_interp_tables.inc`: + - Generated lookup table and `spu_decode_form` enum. +- `runtime/spu/spu_interp.c`: + - `spu_decode1` replaced with single table load + form switch. As a side effect this removes undefined behaviour: the old `lqd`/`stqd` path shifted a negative `int` left (`i10 << 4`); UBSan reports `left shift of negative value -512` there. The new path shifts in `uint32_t`. +- `runtime/spu/tests/test_spu_decode.c`: + - New test verifying opcode and field decodes for all 15 immediate forms: signed/unsigned boundaries, LS target wrapping, channel-field width, RRR field order, hints, all four float conversions, and invalid words. Conflicting-prefix precedence was checked separately with an off-tree injected collision. +- `CMakeLists.txt`: + - Registers `test_spu_decode` under unit tests. + +## Validation + +### 1. Exhaustive 2^32 Parity Verification Harness +An off-tree verification harness compared every field of `spu_ins` (`op`, `rt`, `ra`, `rb`, `rc`, `ch`, `imm`, `tgt`) produced by the old cascade against the new table-driven decoder: +- Checked across all $2^{32}$ (4,294,967,296) instruction words at `pc = 0x00000`: **0 mismatches** (3.30 s). +- Checked across all $2^{32}$ (4,294,967,296) instruction words at `pc = 0x3FFFC`: **0 mismatches** (3.24 s). +- Repeated independently (separate harness, separate reviewer): both full sweeps plus 131,072 samples at random aligned pcs covering all 2048 prefixes, **0 mismatches**. A UBSan build over a 1-in-4097 sample is clean for the new decoder. + +### 2. Decode Throughput Microbenchmark +A local off-tree microbenchmark on macOS Apple Silicon timed a synthetic mix of 10,000,000 instructions across opcode formats (no title code), 5 repetitions per arm (`powermode 1`, Low Power mode on battery). The harness is not part of this PR, so treat these numbers as local supporting evidence, not a reproducible upstream benchmark: +- **Old cascade**: + - Runs: 0.1182 s, 0.1181 s, 0.1186 s, 0.1183 s, 0.1181 s + - Mean: **0.1183 s** (spread 0.1181..0.1186 s) — **84.56 M insn/s** +- **New table**: + - Runs: 0.0622 s, 0.0623 s, 0.0624 s, 0.0625 s, 0.0624 s + - Mean: **0.0624 s** (spread 0.0622..0.0625 s) — **160.35 M insn/s** +- **Speedup**: **1.90x** (47.3% decode time reduction). + +### 3. Effect in a commercial title +In one commercial title's replay (same input, 3 runs per arm), its audio middleware's three SPU job images ran 1.4-1.8x faster per job (mean 2.00 -> 1.09 ms, 0.70 -> 0.46 ms, 0.54 -> 0.38 ms), stale audio blocks fell from 1868 to 78 per run, and frame rate rose from 108 to 119 fps. In a Time Profiler, the decode share of worker CPU fell from 37 % to 14 % in the audio queue and from 29 % to 11 % in the frame queue. These are private, workload-local observations, not a general performance guarantee. + +### 4. Test Suites and Toolchain Parity +- Untouched upstream base (`4e8f3ca8`): 22/22 ctest tests pass. +- Patched upstream tree: 23/23 ctest tests pass (`spu_decode` passes in 0.00 s). +- `test_spu_decode` builds and passes with `CC=gcc-16 CXX=g++-16`; GCC's only warnings there are the existing `static inline` + `noinline` attributes in `spu_helpers.h`, not the new decoder. +- `python3 tools/gen_spu_interp.py` regenerates `spu_interp_tables.inc` byte-identically; `tools/test_spu_disasm_ri10.py`, which CI runs, fails if the committed table is stale. That checks freshness against the generator, not decoder equivalence. +- Not run: the Windows clang-cl workflow. The new decoder compiles warning-free for `x86_64-pc-windows-msvc` with clang, and `test_spu_decode` sits inside the existing `if(NOT WIN32)` test block. + +## Test plan +1. Run `python3 tools/test_spu_disasm_ri10.py`: it checks the RI10 expectations and that the committed table matches the generator, without rewriting the checkout. +2. Configure with `-DPS3RECOMP_BUILD_TESTS=ON` and build `test_spu_decode`. +3. Run `ctest -R spu_decode --output-on-failure`. +4. Run full ctest suite to ensure zero regressions across runtime and tools tests. + +Note: CI builds without `PS3RECOMP_BUILD_TESTS`, so `spu_decode`, like the other root CTests, runs only locally. CI still catches a stale table through the tools tests. Running the root CTests in CI would be a separate change; I can send it if wanted. + +## Notes +This PR is intentionally scoped to decode only. Caching decoded instructions across executions (a predecode cache) would need its own invalidation contract for DMA and self-modifying code, so it is left out. No CHANGELOG entry, following the repository's release-time changelog. + +## Checklist +- [x] Builds locally (AppleClang and GCC 16) +- [x] Full test suite passes (23/23) +- [x] Exhaustive parity verified over all 2^32 words (0 mismatches) +- [x] Generator output matches the committed table (freshness check, not an equivalence proof) +- [x] No behavior changes to execution semantics or lifted paths +- [x] No title names, addresses, or game/firmware assets added +- [x] "Allow edits by maintainers" enabled + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-688/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-688/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..bb1541ed8b279fe8b36c48c78629c3c1cd5e1cbf --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-688/tests/oracle.patch @@ -0,0 +1,1310 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 250d8d2c..3704fda4 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -417,6 +417,16 @@ if(PS3RECOMP_BUILD_TESTS) + add_test(NAME spu_float_exact COMMAND test_spu_float_exact) + set_tests_properties(spu_float_exact PROPERTIES TIMEOUT 300) + ++ # The interpreter's op/immediate decode at the opcode-width and ++ # immediate-form boundaries, against ISA-layout encodings. ++ add_executable(test_spu_decode ++ runtime/spu/tests/test_spu_decode.c) ++ target_include_directories(test_spu_decode PRIVATE include runtime/spu) ++ target_compile_options(test_spu_decode PRIVATE -UNDEBUG) ++ target_link_libraries(test_spu_decode PRIVATE m) ++ add_test(NAME spu_decode COMMAND test_spu_decode) ++ set_tests_properties(spu_decode PROPERTIES TIMEOUT 30) ++ + add_executable(test_spu_lockline_wait + runtime/spu/tests/test_spu_lockline_wait.c) + target_include_directories(test_spu_lockline_wait PRIVATE include) +diff --git a/runtime/spu/spu_interp.c b/runtime/spu/spu_interp.c +index e9b8f613..ea85a8a3 100644 +--- a/runtime/spu/spu_interp.c ++++ b/runtime/spu/spu_interp.c +@@ -17,7 +17,7 @@ u128 spu_rdch(spu_context* ctx, uint32_t channel); + void spu_wrch(spu_context* ctx, uint32_t channel, u128 value); + uint32_t spu_rchcnt(spu_context* ctx, uint32_t channel); + +-#include "spu_interp_tables.inc" /* spu_op enum, spu_op_name[], spu_dec_* */ ++#include "spu_interp_tables.inc" /* spu_op enum, spu_op_name[], spu_decode_tab[] */ + + /* Work descriptor for the next SYS_SPU_THREAD_STOP_RECEIVE_EVENT service, set + * by the event-port send that wakes a sim SPU. Single-slot: dispatch is +@@ -25,7 +25,7 @@ uint32_t spu_rchcnt(spu_context* ctx, uint32_t channel); + uint32_t g_spu_pending_evt[3]; + int g_spu_pending_evt_valid; + +-/* ---- decode: 32-bit insn -> fields (mirrors spu_disasm.spu_decode order) ---- */ ++/* ---- decode: 32-bit insn -> fields (one lookup in spu_decode_tab) ---- */ + typedef struct { + spu_op op; + uint8_t rt, ra, rb, rc, ch; +@@ -38,61 +38,38 @@ static int32_t sx(uint32_t v, int bits) { + return (int32_t)((v ^ m) - m); + } + ++/* Every opcode field is a prefix of bits 31..21, so the op and the immediate ++ * form come from one table load; the cascade precedence is baked into the ++ * table by tools/gen_spu_interp.py. Only the fields the form needs are ++ * computed. */ + static void spu_decode1(uint32_t insn, uint32_t pc, spu_ins* d) { +- uint32_t op4 = (insn >> 28) & 0xF, op7 = (insn >> 25) & 0x7F; +- uint32_t op8 = (insn >> 24) & 0xFF, op9 = (insn >> 23) & 0x1FF; +- uint32_t op10 = (insn >> 22) & 0x3FF, op11 = (insn >> 21) & 0x7FF; ++ const spu_decode_ent e = spu_decode_tab[insn >> 21]; ++ d->op = (spu_op)e.op; + d->rt = insn & 0x7F; d->ra = (insn >> 7) & 0x7F; + d->rb = (insn >> 14) & 0x7F; d->rc = (insn >> 21) & 0x7F; + d->ch = (insn >> 7) & 0x7F; d->imm = 0; d->tgt = 0; +- int32_t i10 = sx((insn >> 14) & 0x3FF, 10); +- int32_t i16 = sx((insn >> 7) & 0xFFFF, 16); +- uint32_t i18 = (insn >> 7) & 0x3FFFF; + +- /* RRR (4) */ +- if ((d->op = spu_dec_rrr(op4)) != SPU_word) return; +- /* RI18 (7) */ +- if ((d->op = spu_dec_ri18(op7)) != SPU_word) { +- d->imm = (d->op == SPU_ila) ? (int32_t)i18 : (int32_t)(i18 & 0xFFFF); +- return; ++ switch ((spu_decode_form)e.form) { ++ case SPU_F_NONE: break; ++ case SPU_F_I18: d->imm = (int32_t)((insn >> 7) & 0x3FFFF); break; ++ case SPU_F_I18LO: d->imm = (int32_t)((insn >> 7) & 0xFFFF); break; ++ case SPU_F_LQA: ++ d->tgt = ((((insn >> 7) & 0xFFFF) << 2)) & 0x3FFF0; break; ++ case SPU_F_LQR: ++ d->tgt = ((uint32_t)(sx((insn >> 7) & 0xFFFF, 16) * 4) + pc) & 0x3FFF0; break; ++ case SPU_F_BREL: ++ d->tgt = ((uint32_t)(sx((insn >> 7) & 0xFFFF, 16) * 4) + pc) & 0x3FFFF; break; ++ case SPU_F_BABS: ++ d->tgt = ((uint32_t)(sx((insn >> 7) & 0xFFFF, 16) * 4)) & 0x3FFFF; break; ++ case SPU_F_I16S: d->imm = sx((insn >> 7) & 0xFFFF, 16); break; ++ case SPU_F_I16U: d->imm = (int32_t)((insn >> 7) & 0xFFFF); break; ++ case SPU_F_I10: d->imm = sx((insn >> 14) & 0x3FF, 10); break; ++ case SPU_F_I10Q: d->imm = (int32_t)((uint32_t)sx((insn >> 14) & 0x3FF, 10) << 4); break; ++ case SPU_F_I8: d->imm = (insn >> 14) & 0xFF; break; ++ case SPU_F_STOP: d->imm = insn & 0x3FFF; break; ++ case SPU_F_I7S: d->imm = sx(d->rb, 7); break; ++ case SPU_F_I7U: d->imm = d->rb; break; + } +- /* RI16 (9) — before RI10 (shared top-8-bit opcodes) */ +- if ((d->op = spu_dec_ri16(op9)) != SPU_word) { +- switch (d->op) { +- case SPU_lqa: case SPU_stqa: d->tgt = ((uint32_t)(i16 & 0xFFFF) << 2) & 0x3FFF0; break; +- case SPU_lqr: case SPU_stqr: d->tgt = ((uint32_t)(i16 * 4) + pc) & 0x3FFF0; break; +- case SPU_br: case SPU_brsl: case SPU_brz: case SPU_brnz: +- case SPU_brhz: case SPU_brhnz: d->tgt = ((uint32_t)(i16 * 4) + pc) & 0x3FFFF; break; +- case SPU_bra: case SPU_brasl: d->tgt = ((uint32_t)(i16 * 4)) & 0x3FFFF; break; +- case SPU_il: d->imm = i16; break; +- default: d->imm = (int32_t)(i16 & 0xFFFF); break; /* ilh/ilhu/iohl */ +- } +- return; +- } +- /* channel ops (op11) — before RI10 (wrch/shli op8 clash) */ +- if (op11 == 0x00D) { d->op = SPU_rdch; return; } +- if (op11 == 0x10D) { d->op = SPU_wrch; return; } +- if (op11 == 0x00F) { d->op = SPU_rchcnt; return; } +- /* RI10 (8) */ +- if ((d->op = spu_dec_ri10(op8)) != SPU_word) { +- d->imm = (d->op == SPU_lqd || d->op == SPU_stqd) ? (i10 << 4) : i10; +- return; +- } +- /* RI8 (10) float<->int conversions */ +- if ((d->op = spu_dec_ri8(op10)) != SPU_word) { d->imm = (insn >> 14) & 0xFF; return; } +- /* RR (11) */ +- if ((d->op = spu_dec_rr(op11)) != SPU_word) { +- if (d->op == SPU_stop) d->imm = insn & 0x3FFF; +- return; +- } +- /* RI7 (11) rotate/shift/gen-control immediates */ +- if ((d->op = spu_dec_ri7(op11)) != SPU_word) { +- d->imm = spu_ri7_unsigned(d->op) ? d->rb : sx(d->rb, 7); +- return; +- } +- /* LSX (redundant with RR's lqx/stqx, kept for order-parity) */ +- if ((d->op = spu_dec_lsx(op11)) != SPU_word) return; +- d->op = SPU_word; + } + + /* spu_lifted_lookup() is defined by spu_fn_registry.c (the single owner of the +diff --git a/runtime/spu/spu_interp_tables.inc b/runtime/spu/spu_interp_tables.inc +index 90f9dd8c..ee32cf28 100644 +--- a/runtime/spu/spu_interp_tables.inc ++++ b/runtime/spu/spu_interp_tables.inc +@@ -1,6 +1,7 @@ + /* GENERATED by tools/gen_spu_interp.py -- do not edit. */ +-/* Opcode->mnemonic tables for the SPU interpreter, from the validated +- * spu_disasm.py decoder. Regenerate after any decoder table change. */ ++/* Opcode->mnemonic enum and the insn>>21 decode table for the SPU ++ * interpreter, from the validated spu_disasm.py decoder. Regenerate after ++ * any decoder table change. */ + + typedef enum { + SPU_word, +@@ -409,256 +410,540 @@ static const char* const spu_op_name[SPU_OP_COUNT] = { + [SPU_xswd] = "xswd", + }; + +-static spu_op spu_dec_rrr(uint32_t op4) { +- switch (op4) { +- case 0x8: return SPU_selb; +- case 0xB: return SPU_shufb; +- case 0xC: return SPU_mpya; +- case 0xD: return SPU_fnms; +- case 0xE: return SPU_fma; +- case 0xF: return SPU_fms; +- default: return SPU_word; +- } +-} +- +-static spu_op spu_dec_ri18(uint32_t op7) { +- switch (op7) { +- case 0x8: return SPU_hbra; +- case 0x9: return SPU_hbrr; +- case 0x21: return SPU_ila; +- default: return SPU_word; +- } +-} +- +-static spu_op spu_dec_ri16(uint32_t op9) { +- switch (op9) { +- case 0x40: return SPU_brz; +- case 0x41: return SPU_stqa; +- case 0x42: return SPU_brnz; +- case 0x44: return SPU_brhz; +- case 0x46: return SPU_brhnz; +- case 0x47: return SPU_stqr; +- case 0x60: return SPU_bra; +- case 0x61: return SPU_lqa; +- case 0x62: return SPU_brasl; +- case 0x64: return SPU_br; +- case 0x65: return SPU_fsmbi; +- case 0x66: return SPU_brsl; +- case 0x67: return SPU_lqr; +- case 0x81: return SPU_il; +- case 0x82: return SPU_ilhu; +- case 0x83: return SPU_ilh; +- case 0xC1: return SPU_iohl; +- default: return SPU_word; +- } +-} +- +-static spu_op spu_dec_ri10(uint32_t op8) { +- switch (op8) { +- case 0x4: return SPU_ori; +- case 0x5: return SPU_orhi; +- case 0x6: return SPU_orbi; +- case 0xC: return SPU_sfi; +- case 0xD: return SPU_sfhi; +- case 0x14: return SPU_andi; +- case 0x15: return SPU_andhi; +- case 0x16: return SPU_andbi; +- case 0x1C: return SPU_ai; +- case 0x1D: return SPU_ahi; +- case 0x24: return SPU_stqd; +- case 0x34: return SPU_lqd; +- case 0x44: return SPU_xori; +- case 0x45: return SPU_xorhi; +- case 0x46: return SPU_xorbi; +- case 0x4C: return SPU_cgti; +- case 0x4D: return SPU_cgthi; +- case 0x4E: return SPU_cgtbi; +- case 0x4F: return SPU_hgti; +- case 0x5C: return SPU_clgti; +- case 0x5D: return SPU_clgthi; +- case 0x5E: return SPU_clgtbi; +- case 0x5F: return SPU_hlgti; +- case 0x74: return SPU_mpyi; +- case 0x75: return SPU_mpyui; +- case 0x7C: return SPU_ceqi; +- case 0x7D: return SPU_ceqhi; +- case 0x7E: return SPU_ceqbi; +- case 0x7F: return SPU_heqi; +- default: return SPU_word; +- } +-} +- +-static spu_op spu_dec_ri8(uint32_t op10) { +- switch (op10) { +- case 0x1D8: return SPU_cflts; +- case 0x1D9: return SPU_cfltu; +- case 0x1DA: return SPU_csflt; +- case 0x1DB: return SPU_cuflt; +- default: return SPU_word; +- } +-} +- +-static spu_op spu_dec_rr(uint32_t op11) { +- switch (op11) { +- case 0x0: return SPU_stop; +- case 0x1: return SPU_lnop; +- case 0x2: return SPU_sync; +- case 0x3: return SPU_dsync; +- case 0xC: return SPU_mfspr; +- case 0xD: return SPU_rdch; +- case 0xF: return SPU_rchcnt; +- case 0x40: return SPU_sf; +- case 0x41: return SPU_or; +- case 0x42: return SPU_bg; +- case 0x48: return SPU_sfh; +- case 0x49: return SPU_nor; +- case 0x53: return SPU_absdb; +- case 0x58: return SPU_rot; +- case 0x59: return SPU_rotm; +- case 0x5A: return SPU_rotma; +- case 0x5B: return SPU_shl; +- case 0x5C: return SPU_roth; +- case 0x5D: return SPU_rothm; +- case 0x5E: return SPU_rotmah; +- case 0x5F: return SPU_shlh; +- case 0xC0: return SPU_a; +- case 0xC1: return SPU_and; +- case 0xC2: return SPU_cg; +- case 0xC8: return SPU_ah; +- case 0xC9: return SPU_nand; +- case 0xD3: return SPU_avgb; +- case 0x10C: return SPU_mtspr; +- case 0x10D: return SPU_wrch; +- case 0x128: return SPU_biz; +- case 0x129: return SPU_binz; +- case 0x12A: return SPU_bihz; +- case 0x12B: return SPU_bihnz; +- case 0x140: return SPU_stopd; +- case 0x144: return SPU_stqx; +- case 0x1A8: return SPU_bi; +- case 0x1A9: return SPU_bisl; +- case 0x1AA: return SPU_iret; +- case 0x1AB: return SPU_bisled; +- case 0x1AC: return SPU_hbr; +- case 0x1B0: return SPU_gb; +- case 0x1B1: return SPU_gbh; +- case 0x1B2: return SPU_gbb; +- case 0x1B4: return SPU_fsm; +- case 0x1B5: return SPU_fsmh; +- case 0x1B6: return SPU_fsmb; +- case 0x1B8: return SPU_frest; +- case 0x1B9: return SPU_frsqest; +- case 0x1C4: return SPU_lqx; +- case 0x1CC: return SPU_rotqbybi; +- case 0x1CD: return SPU_rotqmbybi; +- case 0x1CF: return SPU_shlqbybi; +- case 0x1D4: return SPU_cbx; +- case 0x1D5: return SPU_chx; +- case 0x1D6: return SPU_cwx; +- case 0x1D7: return SPU_cdx; +- case 0x1D8: return SPU_rotqbi; +- case 0x1D9: return SPU_rotqmbi; +- case 0x1DB: return SPU_shlqbi; +- case 0x1DC: return SPU_rotqby; +- case 0x1DD: return SPU_rotqmby; +- case 0x1DF: return SPU_shlqby; +- case 0x1F0: return SPU_orx; +- case 0x201: return SPU_nop; +- case 0x240: return SPU_cgt; +- case 0x241: return SPU_xor; +- case 0x248: return SPU_cgth; +- case 0x249: return SPU_eqv; +- case 0x250: return SPU_cgtb; +- case 0x253: return SPU_sumb; +- case 0x258: return SPU_hgt; +- case 0x2A5: return SPU_clz; +- case 0x2A6: return SPU_xswd; +- case 0x2AE: return SPU_xshw; +- case 0x2B4: return SPU_cntb; +- case 0x2B6: return SPU_xsbh; +- case 0x2C0: return SPU_clgt; +- case 0x2C1: return SPU_andc; +- case 0x2C2: return SPU_fcgt; +- case 0x2C3: return SPU_dfcgt; +- case 0x2C4: return SPU_fa; +- case 0x2C5: return SPU_fs; +- case 0x2C6: return SPU_fm; +- case 0x2C8: return SPU_clgth; +- case 0x2C9: return SPU_orc; +- case 0x2CA: return SPU_fcmgt; +- case 0x2CB: return SPU_dfcmgt; +- case 0x2CC: return SPU_dfa; +- case 0x2CD: return SPU_dfs; +- case 0x2CE: return SPU_dfm; +- case 0x2D0: return SPU_clgtb; +- case 0x2D8: return SPU_hlgt; +- case 0x340: return SPU_addx; +- case 0x341: return SPU_sfx; +- case 0x342: return SPU_cgx; +- case 0x343: return SPU_bgx; +- case 0x346: return SPU_mpyhha; +- case 0x34E: return SPU_mpyhhau; +- case 0x35C: return SPU_dfma; +- case 0x35D: return SPU_dfms; +- case 0x35E: return SPU_dfnms; +- case 0x35F: return SPU_dfnma; +- case 0x398: return SPU_fscrrd; +- case 0x3B8: return SPU_fesd; +- case 0x3B9: return SPU_frds; +- case 0x3BA: return SPU_fscrwr; +- case 0x3BF: return SPU_dftsv; +- case 0x3C0: return SPU_ceq; +- case 0x3C2: return SPU_fceq; +- case 0x3C3: return SPU_dfceq; +- case 0x3C4: return SPU_mpy; +- case 0x3C5: return SPU_mpyh; +- case 0x3C6: return SPU_mpyhh; +- case 0x3C7: return SPU_mpys; +- case 0x3C8: return SPU_ceqh; +- case 0x3CA: return SPU_fcmeq; +- case 0x3CB: return SPU_dfcmeq; +- case 0x3CC: return SPU_mpyu; +- case 0x3CE: return SPU_mpyhhu; +- case 0x3D0: return SPU_ceqb; +- case 0x3D4: return SPU_fi; +- case 0x3D8: return SPU_heq; +- default: return SPU_word; +- } +-} +- +-static spu_op spu_dec_ri7(uint32_t op11) { +- switch (op11) { +- case 0x78: return SPU_roti; +- case 0x79: return SPU_rotmi; +- case 0x7A: return SPU_rotmai; +- case 0x7B: return SPU_shli; +- case 0x7C: return SPU_rothi; +- case 0x7D: return SPU_rothmi; +- case 0x7E: return SPU_rotmahi; +- case 0x7F: return SPU_shlhi; +- case 0x1F4: return SPU_cbd; +- case 0x1F5: return SPU_chd; +- case 0x1F6: return SPU_cwd; +- case 0x1F7: return SPU_cdd; +- case 0x1F8: return SPU_rotqbii; +- case 0x1F9: return SPU_rotqmbii; +- case 0x1FB: return SPU_shlqbii; +- case 0x1FC: return SPU_rotqbyi; +- case 0x1FD: return SPU_rotqmbyi; +- case 0x1FF: return SPU_shlqbyi; +- default: return SPU_word; +- } +-} ++/* How spu_decode1 derives imm/tgt. */ ++typedef enum { ++ SPU_F_NONE, /* no immediate: RRR, RR (except stop), LSX, channel ops, .word */ ++ SPU_F_I18, /* ila: full 18-bit immediate */ ++ SPU_F_I18LO, /* other RI18 (hbra/hbrr): low 16 bits of the 18-bit field */ ++ SPU_F_LQA, /* lqa/stqa: absolute 16-byte aligned LS address in tgt */ ++ SPU_F_LQR, /* lqr/stqr: pc-relative 16-byte aligned LS address in tgt */ ++ SPU_F_BREL, /* br/brsl/brz/brnz/brhz/brhnz: pc-relative target in tgt */ ++ SPU_F_BABS, /* bra/brasl: absolute target in tgt */ ++ SPU_F_I16S, /* il: sign-extended 16-bit immediate */ ++ SPU_F_I16U, /* ilh/ilhu/iohl/fsmbi: zero-extended 16-bit immediate */ ++ SPU_F_I10, /* RI10: sign-extended 10-bit immediate */ ++ SPU_F_I10Q, /* lqd/stqd: sign-extended 10-bit immediate scaled by 16 */ ++ SPU_F_I8, /* RI8 float<->int conversions: unsigned 8-bit scale */ ++ SPU_F_STOP, /* stop: 14-bit signal type */ ++ SPU_F_I7S, /* RI7: sign-extended 7-bit immediate */ ++ SPU_F_I7U, /* cbd/chd/cwd/cdd: unsigned 7-bit immediate */ ++} spu_decode_form; + +-static spu_op spu_dec_lsx(uint32_t op11) { +- switch (op11) { +- case 0x144: return SPU_stqx; +- case 0x1C4: return SPU_lqx; +- default: return SPU_word; +- } +-} ++typedef struct { uint8_t op; uint8_t form; } spu_decode_ent; ++_Static_assert(SPU_OP_COUNT <= 256, "spu_op must fit spu_decode_ent.op"); + +-/* signed-vs-unsigned i7 per instruction (Table 2-6) */ +-static int spu_ri7_unsigned(spu_op op) { +- return op == SPU_cbd || op == SPU_cdd || op == SPU_chd || op == SPU_cwd; +-} ++/* Indexed by insn >> 21; precedence is documented in tools/gen_spu_interp.py. */ ++static const spu_decode_ent spu_decode_tab[2048] = { ++ /*000*/ {SPU_stop, SPU_F_STOP}, {SPU_lnop, SPU_F_NONE}, {SPU_sync, SPU_F_NONE}, {SPU_dsync, SPU_F_NONE}, ++ /*004*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*008*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*00C*/ {SPU_mfspr, SPU_F_NONE}, {SPU_rdch, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_rchcnt, SPU_F_NONE}, ++ /*010*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*014*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*018*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*01C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*020*/ {SPU_ori, SPU_F_I10}, {SPU_ori, SPU_F_I10}, {SPU_ori, SPU_F_I10}, {SPU_ori, SPU_F_I10}, ++ /*024*/ {SPU_ori, SPU_F_I10}, {SPU_ori, SPU_F_I10}, {SPU_ori, SPU_F_I10}, {SPU_ori, SPU_F_I10}, ++ /*028*/ {SPU_orhi, SPU_F_I10}, {SPU_orhi, SPU_F_I10}, {SPU_orhi, SPU_F_I10}, {SPU_orhi, SPU_F_I10}, ++ /*02C*/ {SPU_orhi, SPU_F_I10}, {SPU_orhi, SPU_F_I10}, {SPU_orhi, SPU_F_I10}, {SPU_orhi, SPU_F_I10}, ++ /*030*/ {SPU_orbi, SPU_F_I10}, {SPU_orbi, SPU_F_I10}, {SPU_orbi, SPU_F_I10}, {SPU_orbi, SPU_F_I10}, ++ /*034*/ {SPU_orbi, SPU_F_I10}, {SPU_orbi, SPU_F_I10}, {SPU_orbi, SPU_F_I10}, {SPU_orbi, SPU_F_I10}, ++ /*038*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*03C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*040*/ {SPU_sf, SPU_F_NONE}, {SPU_or, SPU_F_NONE}, {SPU_bg, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*044*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*048*/ {SPU_sfh, SPU_F_NONE}, {SPU_nor, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*04C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*050*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_absdb, SPU_F_NONE}, ++ /*054*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*058*/ {SPU_rot, SPU_F_NONE}, {SPU_rotm, SPU_F_NONE}, {SPU_rotma, SPU_F_NONE}, {SPU_shl, SPU_F_NONE}, ++ /*05C*/ {SPU_roth, SPU_F_NONE}, {SPU_rothm, SPU_F_NONE}, {SPU_rotmah, SPU_F_NONE}, {SPU_shlh, SPU_F_NONE}, ++ /*060*/ {SPU_sfi, SPU_F_I10}, {SPU_sfi, SPU_F_I10}, {SPU_sfi, SPU_F_I10}, {SPU_sfi, SPU_F_I10}, ++ /*064*/ {SPU_sfi, SPU_F_I10}, {SPU_sfi, SPU_F_I10}, {SPU_sfi, SPU_F_I10}, {SPU_sfi, SPU_F_I10}, ++ /*068*/ {SPU_sfhi, SPU_F_I10}, {SPU_sfhi, SPU_F_I10}, {SPU_sfhi, SPU_F_I10}, {SPU_sfhi, SPU_F_I10}, ++ /*06C*/ {SPU_sfhi, SPU_F_I10}, {SPU_sfhi, SPU_F_I10}, {SPU_sfhi, SPU_F_I10}, {SPU_sfhi, SPU_F_I10}, ++ /*070*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*074*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*078*/ {SPU_roti, SPU_F_I7S}, {SPU_rotmi, SPU_F_I7S}, {SPU_rotmai, SPU_F_I7S}, {SPU_shli, SPU_F_I7S}, ++ /*07C*/ {SPU_rothi, SPU_F_I7S}, {SPU_rothmi, SPU_F_I7S}, {SPU_rotmahi, SPU_F_I7S}, {SPU_shlhi, SPU_F_I7S}, ++ /*080*/ {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, ++ /*084*/ {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, ++ /*088*/ {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, ++ /*08C*/ {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, {SPU_hbra, SPU_F_I18LO}, ++ /*090*/ {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, ++ /*094*/ {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, ++ /*098*/ {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, ++ /*09C*/ {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, {SPU_hbrr, SPU_F_I18LO}, ++ /*0A0*/ {SPU_andi, SPU_F_I10}, {SPU_andi, SPU_F_I10}, {SPU_andi, SPU_F_I10}, {SPU_andi, SPU_F_I10}, ++ /*0A4*/ {SPU_andi, SPU_F_I10}, {SPU_andi, SPU_F_I10}, {SPU_andi, SPU_F_I10}, {SPU_andi, SPU_F_I10}, ++ /*0A8*/ {SPU_andhi, SPU_F_I10}, {SPU_andhi, SPU_F_I10}, {SPU_andhi, SPU_F_I10}, {SPU_andhi, SPU_F_I10}, ++ /*0AC*/ {SPU_andhi, SPU_F_I10}, {SPU_andhi, SPU_F_I10}, {SPU_andhi, SPU_F_I10}, {SPU_andhi, SPU_F_I10}, ++ /*0B0*/ {SPU_andbi, SPU_F_I10}, {SPU_andbi, SPU_F_I10}, {SPU_andbi, SPU_F_I10}, {SPU_andbi, SPU_F_I10}, ++ /*0B4*/ {SPU_andbi, SPU_F_I10}, {SPU_andbi, SPU_F_I10}, {SPU_andbi, SPU_F_I10}, {SPU_andbi, SPU_F_I10}, ++ /*0B8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0BC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0C0*/ {SPU_a, SPU_F_NONE}, {SPU_and, SPU_F_NONE}, {SPU_cg, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0C4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0C8*/ {SPU_ah, SPU_F_NONE}, {SPU_nand, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0CC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0D0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_avgb, SPU_F_NONE}, ++ /*0D4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0D8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0DC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0E0*/ {SPU_ai, SPU_F_I10}, {SPU_ai, SPU_F_I10}, {SPU_ai, SPU_F_I10}, {SPU_ai, SPU_F_I10}, ++ /*0E4*/ {SPU_ai, SPU_F_I10}, {SPU_ai, SPU_F_I10}, {SPU_ai, SPU_F_I10}, {SPU_ai, SPU_F_I10}, ++ /*0E8*/ {SPU_ahi, SPU_F_I10}, {SPU_ahi, SPU_F_I10}, {SPU_ahi, SPU_F_I10}, {SPU_ahi, SPU_F_I10}, ++ /*0EC*/ {SPU_ahi, SPU_F_I10}, {SPU_ahi, SPU_F_I10}, {SPU_ahi, SPU_F_I10}, {SPU_ahi, SPU_F_I10}, ++ /*0F0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0F4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0F8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*0FC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*100*/ {SPU_brz, SPU_F_BREL}, {SPU_brz, SPU_F_BREL}, {SPU_brz, SPU_F_BREL}, {SPU_brz, SPU_F_BREL}, ++ /*104*/ {SPU_stqa, SPU_F_LQA}, {SPU_stqa, SPU_F_LQA}, {SPU_stqa, SPU_F_LQA}, {SPU_stqa, SPU_F_LQA}, ++ /*108*/ {SPU_brnz, SPU_F_BREL}, {SPU_brnz, SPU_F_BREL}, {SPU_brnz, SPU_F_BREL}, {SPU_brnz, SPU_F_BREL}, ++ /*10C*/ {SPU_mtspr, SPU_F_NONE}, {SPU_wrch, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*110*/ {SPU_brhz, SPU_F_BREL}, {SPU_brhz, SPU_F_BREL}, {SPU_brhz, SPU_F_BREL}, {SPU_brhz, SPU_F_BREL}, ++ /*114*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*118*/ {SPU_brhnz, SPU_F_BREL}, {SPU_brhnz, SPU_F_BREL}, {SPU_brhnz, SPU_F_BREL}, {SPU_brhnz, SPU_F_BREL}, ++ /*11C*/ {SPU_stqr, SPU_F_LQR}, {SPU_stqr, SPU_F_LQR}, {SPU_stqr, SPU_F_LQR}, {SPU_stqr, SPU_F_LQR}, ++ /*120*/ {SPU_stqd, SPU_F_I10Q}, {SPU_stqd, SPU_F_I10Q}, {SPU_stqd, SPU_F_I10Q}, {SPU_stqd, SPU_F_I10Q}, ++ /*124*/ {SPU_stqd, SPU_F_I10Q}, {SPU_stqd, SPU_F_I10Q}, {SPU_stqd, SPU_F_I10Q}, {SPU_stqd, SPU_F_I10Q}, ++ /*128*/ {SPU_biz, SPU_F_NONE}, {SPU_binz, SPU_F_NONE}, {SPU_bihz, SPU_F_NONE}, {SPU_bihnz, SPU_F_NONE}, ++ /*12C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*130*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*134*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*138*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*13C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*140*/ {SPU_stopd, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*144*/ {SPU_stqx, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*148*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*14C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*150*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*154*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*158*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*15C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*160*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*164*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*168*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*16C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*170*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*174*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*178*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*17C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*180*/ {SPU_bra, SPU_F_BABS}, {SPU_bra, SPU_F_BABS}, {SPU_bra, SPU_F_BABS}, {SPU_bra, SPU_F_BABS}, ++ /*184*/ {SPU_lqa, SPU_F_LQA}, {SPU_lqa, SPU_F_LQA}, {SPU_lqa, SPU_F_LQA}, {SPU_lqa, SPU_F_LQA}, ++ /*188*/ {SPU_brasl, SPU_F_BABS}, {SPU_brasl, SPU_F_BABS}, {SPU_brasl, SPU_F_BABS}, {SPU_brasl, SPU_F_BABS}, ++ /*18C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*190*/ {SPU_br, SPU_F_BREL}, {SPU_br, SPU_F_BREL}, {SPU_br, SPU_F_BREL}, {SPU_br, SPU_F_BREL}, ++ /*194*/ {SPU_fsmbi, SPU_F_I16U}, {SPU_fsmbi, SPU_F_I16U}, {SPU_fsmbi, SPU_F_I16U}, {SPU_fsmbi, SPU_F_I16U}, ++ /*198*/ {SPU_brsl, SPU_F_BREL}, {SPU_brsl, SPU_F_BREL}, {SPU_brsl, SPU_F_BREL}, {SPU_brsl, SPU_F_BREL}, ++ /*19C*/ {SPU_lqr, SPU_F_LQR}, {SPU_lqr, SPU_F_LQR}, {SPU_lqr, SPU_F_LQR}, {SPU_lqr, SPU_F_LQR}, ++ /*1A0*/ {SPU_lqd, SPU_F_I10Q}, {SPU_lqd, SPU_F_I10Q}, {SPU_lqd, SPU_F_I10Q}, {SPU_lqd, SPU_F_I10Q}, ++ /*1A4*/ {SPU_lqd, SPU_F_I10Q}, {SPU_lqd, SPU_F_I10Q}, {SPU_lqd, SPU_F_I10Q}, {SPU_lqd, SPU_F_I10Q}, ++ /*1A8*/ {SPU_bi, SPU_F_NONE}, {SPU_bisl, SPU_F_NONE}, {SPU_iret, SPU_F_NONE}, {SPU_bisled, SPU_F_NONE}, ++ /*1AC*/ {SPU_hbr, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1B0*/ {SPU_gb, SPU_F_NONE}, {SPU_gbh, SPU_F_NONE}, {SPU_gbb, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1B4*/ {SPU_fsm, SPU_F_NONE}, {SPU_fsmh, SPU_F_NONE}, {SPU_fsmb, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1B8*/ {SPU_frest, SPU_F_NONE}, {SPU_frsqest, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1BC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1C0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1C4*/ {SPU_lqx, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1C8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1CC*/ {SPU_rotqbybi, SPU_F_NONE}, {SPU_rotqmbybi, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_shlqbybi, SPU_F_NONE}, ++ /*1D0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1D4*/ {SPU_cbx, SPU_F_NONE}, {SPU_chx, SPU_F_NONE}, {SPU_cwx, SPU_F_NONE}, {SPU_cdx, SPU_F_NONE}, ++ /*1D8*/ {SPU_rotqbi, SPU_F_NONE}, {SPU_rotqmbi, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_shlqbi, SPU_F_NONE}, ++ /*1DC*/ {SPU_rotqby, SPU_F_NONE}, {SPU_rotqmby, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_shlqby, SPU_F_NONE}, ++ /*1E0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1E4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1E8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1EC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1F0*/ {SPU_orx, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*1F4*/ {SPU_cbd, SPU_F_I7U}, {SPU_chd, SPU_F_I7U}, {SPU_cwd, SPU_F_I7U}, {SPU_cdd, SPU_F_I7U}, ++ /*1F8*/ {SPU_rotqbii, SPU_F_I7S}, {SPU_rotqmbii, SPU_F_I7S}, {SPU_word, SPU_F_NONE}, {SPU_shlqbii, SPU_F_I7S}, ++ /*1FC*/ {SPU_rotqbyi, SPU_F_I7S}, {SPU_rotqmbyi, SPU_F_I7S}, {SPU_word, SPU_F_NONE}, {SPU_shlqbyi, SPU_F_I7S}, ++ /*200*/ {SPU_word, SPU_F_NONE}, {SPU_nop, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*204*/ {SPU_il, SPU_F_I16S}, {SPU_il, SPU_F_I16S}, {SPU_il, SPU_F_I16S}, {SPU_il, SPU_F_I16S}, ++ /*208*/ {SPU_ilhu, SPU_F_I16U}, {SPU_ilhu, SPU_F_I16U}, {SPU_ilhu, SPU_F_I16U}, {SPU_ilhu, SPU_F_I16U}, ++ /*20C*/ {SPU_ilh, SPU_F_I16U}, {SPU_ilh, SPU_F_I16U}, {SPU_ilh, SPU_F_I16U}, {SPU_ilh, SPU_F_I16U}, ++ /*210*/ {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, ++ /*214*/ {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, ++ /*218*/ {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, ++ /*21C*/ {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, {SPU_ila, SPU_F_I18}, ++ /*220*/ {SPU_xori, SPU_F_I10}, {SPU_xori, SPU_F_I10}, {SPU_xori, SPU_F_I10}, {SPU_xori, SPU_F_I10}, ++ /*224*/ {SPU_xori, SPU_F_I10}, {SPU_xori, SPU_F_I10}, {SPU_xori, SPU_F_I10}, {SPU_xori, SPU_F_I10}, ++ /*228*/ {SPU_xorhi, SPU_F_I10}, {SPU_xorhi, SPU_F_I10}, {SPU_xorhi, SPU_F_I10}, {SPU_xorhi, SPU_F_I10}, ++ /*22C*/ {SPU_xorhi, SPU_F_I10}, {SPU_xorhi, SPU_F_I10}, {SPU_xorhi, SPU_F_I10}, {SPU_xorhi, SPU_F_I10}, ++ /*230*/ {SPU_xorbi, SPU_F_I10}, {SPU_xorbi, SPU_F_I10}, {SPU_xorbi, SPU_F_I10}, {SPU_xorbi, SPU_F_I10}, ++ /*234*/ {SPU_xorbi, SPU_F_I10}, {SPU_xorbi, SPU_F_I10}, {SPU_xorbi, SPU_F_I10}, {SPU_xorbi, SPU_F_I10}, ++ /*238*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*23C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*240*/ {SPU_cgt, SPU_F_NONE}, {SPU_xor, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*244*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*248*/ {SPU_cgth, SPU_F_NONE}, {SPU_eqv, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*24C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*250*/ {SPU_cgtb, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_sumb, SPU_F_NONE}, ++ /*254*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*258*/ {SPU_hgt, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*25C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*260*/ {SPU_cgti, SPU_F_I10}, {SPU_cgti, SPU_F_I10}, {SPU_cgti, SPU_F_I10}, {SPU_cgti, SPU_F_I10}, ++ /*264*/ {SPU_cgti, SPU_F_I10}, {SPU_cgti, SPU_F_I10}, {SPU_cgti, SPU_F_I10}, {SPU_cgti, SPU_F_I10}, ++ /*268*/ {SPU_cgthi, SPU_F_I10}, {SPU_cgthi, SPU_F_I10}, {SPU_cgthi, SPU_F_I10}, {SPU_cgthi, SPU_F_I10}, ++ /*26C*/ {SPU_cgthi, SPU_F_I10}, {SPU_cgthi, SPU_F_I10}, {SPU_cgthi, SPU_F_I10}, {SPU_cgthi, SPU_F_I10}, ++ /*270*/ {SPU_cgtbi, SPU_F_I10}, {SPU_cgtbi, SPU_F_I10}, {SPU_cgtbi, SPU_F_I10}, {SPU_cgtbi, SPU_F_I10}, ++ /*274*/ {SPU_cgtbi, SPU_F_I10}, {SPU_cgtbi, SPU_F_I10}, {SPU_cgtbi, SPU_F_I10}, {SPU_cgtbi, SPU_F_I10}, ++ /*278*/ {SPU_hgti, SPU_F_I10}, {SPU_hgti, SPU_F_I10}, {SPU_hgti, SPU_F_I10}, {SPU_hgti, SPU_F_I10}, ++ /*27C*/ {SPU_hgti, SPU_F_I10}, {SPU_hgti, SPU_F_I10}, {SPU_hgti, SPU_F_I10}, {SPU_hgti, SPU_F_I10}, ++ /*280*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*284*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*288*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*28C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*290*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*294*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*298*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*29C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2A0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2A4*/ {SPU_word, SPU_F_NONE}, {SPU_clz, SPU_F_NONE}, {SPU_xswd, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2A8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2AC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_xshw, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2B0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2B4*/ {SPU_cntb, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_xsbh, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2B8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2BC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2C0*/ {SPU_clgt, SPU_F_NONE}, {SPU_andc, SPU_F_NONE}, {SPU_fcgt, SPU_F_NONE}, {SPU_dfcgt, SPU_F_NONE}, ++ /*2C4*/ {SPU_fa, SPU_F_NONE}, {SPU_fs, SPU_F_NONE}, {SPU_fm, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2C8*/ {SPU_clgth, SPU_F_NONE}, {SPU_orc, SPU_F_NONE}, {SPU_fcmgt, SPU_F_NONE}, {SPU_dfcmgt, SPU_F_NONE}, ++ /*2CC*/ {SPU_dfa, SPU_F_NONE}, {SPU_dfs, SPU_F_NONE}, {SPU_dfm, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2D0*/ {SPU_clgtb, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2D4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2D8*/ {SPU_hlgt, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2DC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*2E0*/ {SPU_clgti, SPU_F_I10}, {SPU_clgti, SPU_F_I10}, {SPU_clgti, SPU_F_I10}, {SPU_clgti, SPU_F_I10}, ++ /*2E4*/ {SPU_clgti, SPU_F_I10}, {SPU_clgti, SPU_F_I10}, {SPU_clgti, SPU_F_I10}, {SPU_clgti, SPU_F_I10}, ++ /*2E8*/ {SPU_clgthi, SPU_F_I10}, {SPU_clgthi, SPU_F_I10}, {SPU_clgthi, SPU_F_I10}, {SPU_clgthi, SPU_F_I10}, ++ /*2EC*/ {SPU_clgthi, SPU_F_I10}, {SPU_clgthi, SPU_F_I10}, {SPU_clgthi, SPU_F_I10}, {SPU_clgthi, SPU_F_I10}, ++ /*2F0*/ {SPU_clgtbi, SPU_F_I10}, {SPU_clgtbi, SPU_F_I10}, {SPU_clgtbi, SPU_F_I10}, {SPU_clgtbi, SPU_F_I10}, ++ /*2F4*/ {SPU_clgtbi, SPU_F_I10}, {SPU_clgtbi, SPU_F_I10}, {SPU_clgtbi, SPU_F_I10}, {SPU_clgtbi, SPU_F_I10}, ++ /*2F8*/ {SPU_hlgti, SPU_F_I10}, {SPU_hlgti, SPU_F_I10}, {SPU_hlgti, SPU_F_I10}, {SPU_hlgti, SPU_F_I10}, ++ /*2FC*/ {SPU_hlgti, SPU_F_I10}, {SPU_hlgti, SPU_F_I10}, {SPU_hlgti, SPU_F_I10}, {SPU_hlgti, SPU_F_I10}, ++ /*300*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*304*/ {SPU_iohl, SPU_F_I16U}, {SPU_iohl, SPU_F_I16U}, {SPU_iohl, SPU_F_I16U}, {SPU_iohl, SPU_F_I16U}, ++ /*308*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*30C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*310*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*314*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*318*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*31C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*320*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*324*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*328*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*32C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*330*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*334*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*338*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*33C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*340*/ {SPU_addx, SPU_F_NONE}, {SPU_sfx, SPU_F_NONE}, {SPU_cgx, SPU_F_NONE}, {SPU_bgx, SPU_F_NONE}, ++ /*344*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_mpyhha, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*348*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*34C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_mpyhhau, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*350*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*354*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*358*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*35C*/ {SPU_dfma, SPU_F_NONE}, {SPU_dfms, SPU_F_NONE}, {SPU_dfnms, SPU_F_NONE}, {SPU_dfnma, SPU_F_NONE}, ++ /*360*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*364*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*368*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*36C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*370*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*374*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*378*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*37C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*380*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*384*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*388*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*38C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*390*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*394*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*398*/ {SPU_fscrrd, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*39C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3A0*/ {SPU_mpyi, SPU_F_I10}, {SPU_mpyi, SPU_F_I10}, {SPU_mpyi, SPU_F_I10}, {SPU_mpyi, SPU_F_I10}, ++ /*3A4*/ {SPU_mpyi, SPU_F_I10}, {SPU_mpyi, SPU_F_I10}, {SPU_mpyi, SPU_F_I10}, {SPU_mpyi, SPU_F_I10}, ++ /*3A8*/ {SPU_mpyui, SPU_F_I10}, {SPU_mpyui, SPU_F_I10}, {SPU_mpyui, SPU_F_I10}, {SPU_mpyui, SPU_F_I10}, ++ /*3AC*/ {SPU_mpyui, SPU_F_I10}, {SPU_mpyui, SPU_F_I10}, {SPU_mpyui, SPU_F_I10}, {SPU_mpyui, SPU_F_I10}, ++ /*3B0*/ {SPU_cflts, SPU_F_I8}, {SPU_cflts, SPU_F_I8}, {SPU_cfltu, SPU_F_I8}, {SPU_cfltu, SPU_F_I8}, ++ /*3B4*/ {SPU_csflt, SPU_F_I8}, {SPU_csflt, SPU_F_I8}, {SPU_cuflt, SPU_F_I8}, {SPU_cuflt, SPU_F_I8}, ++ /*3B8*/ {SPU_fesd, SPU_F_NONE}, {SPU_frds, SPU_F_NONE}, {SPU_fscrwr, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3BC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_dftsv, SPU_F_NONE}, ++ /*3C0*/ {SPU_ceq, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_fceq, SPU_F_NONE}, {SPU_dfceq, SPU_F_NONE}, ++ /*3C4*/ {SPU_mpy, SPU_F_NONE}, {SPU_mpyh, SPU_F_NONE}, {SPU_mpyhh, SPU_F_NONE}, {SPU_mpys, SPU_F_NONE}, ++ /*3C8*/ {SPU_ceqh, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_fcmeq, SPU_F_NONE}, {SPU_dfcmeq, SPU_F_NONE}, ++ /*3CC*/ {SPU_mpyu, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_mpyhhu, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3D0*/ {SPU_ceqb, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3D4*/ {SPU_fi, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3D8*/ {SPU_heq, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3DC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*3E0*/ {SPU_ceqi, SPU_F_I10}, {SPU_ceqi, SPU_F_I10}, {SPU_ceqi, SPU_F_I10}, {SPU_ceqi, SPU_F_I10}, ++ /*3E4*/ {SPU_ceqi, SPU_F_I10}, {SPU_ceqi, SPU_F_I10}, {SPU_ceqi, SPU_F_I10}, {SPU_ceqi, SPU_F_I10}, ++ /*3E8*/ {SPU_ceqhi, SPU_F_I10}, {SPU_ceqhi, SPU_F_I10}, {SPU_ceqhi, SPU_F_I10}, {SPU_ceqhi, SPU_F_I10}, ++ /*3EC*/ {SPU_ceqhi, SPU_F_I10}, {SPU_ceqhi, SPU_F_I10}, {SPU_ceqhi, SPU_F_I10}, {SPU_ceqhi, SPU_F_I10}, ++ /*3F0*/ {SPU_ceqbi, SPU_F_I10}, {SPU_ceqbi, SPU_F_I10}, {SPU_ceqbi, SPU_F_I10}, {SPU_ceqbi, SPU_F_I10}, ++ /*3F4*/ {SPU_ceqbi, SPU_F_I10}, {SPU_ceqbi, SPU_F_I10}, {SPU_ceqbi, SPU_F_I10}, {SPU_ceqbi, SPU_F_I10}, ++ /*3F8*/ {SPU_heqi, SPU_F_I10}, {SPU_heqi, SPU_F_I10}, {SPU_heqi, SPU_F_I10}, {SPU_heqi, SPU_F_I10}, ++ /*3FC*/ {SPU_heqi, SPU_F_I10}, {SPU_heqi, SPU_F_I10}, {SPU_heqi, SPU_F_I10}, {SPU_heqi, SPU_F_I10}, ++ /*400*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*404*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*408*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*40C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*410*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*414*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*418*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*41C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*420*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*424*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*428*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*42C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*430*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*434*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*438*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*43C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*440*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*444*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*448*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*44C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*450*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*454*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*458*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*45C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*460*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*464*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*468*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*46C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*470*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*474*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*478*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*47C*/ {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, {SPU_selb, SPU_F_NONE}, ++ /*480*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*484*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*488*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*48C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*490*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*494*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*498*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*49C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4A0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4A4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4A8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4AC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4B0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4B4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4B8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4BC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4C0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4C4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4C8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4CC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4D0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4D4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4D8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4DC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4E0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4E4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4E8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4EC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4F0*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4F4*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4F8*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*4FC*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*500*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*504*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*508*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*50C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*510*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*514*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*518*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*51C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*520*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*524*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*528*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*52C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*530*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*534*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*538*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*53C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*540*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*544*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*548*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*54C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*550*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*554*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*558*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*55C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*560*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*564*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*568*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*56C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*570*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*574*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*578*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*57C*/ {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, {SPU_word, SPU_F_NONE}, ++ /*580*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*584*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*588*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*58C*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*590*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*594*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*598*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*59C*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5A0*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5A4*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5A8*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5AC*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5B0*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5B4*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5B8*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5BC*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5C0*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5C4*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5C8*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5CC*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5D0*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5D4*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5D8*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5DC*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5E0*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5E4*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5E8*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5EC*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5F0*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5F4*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5F8*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*5FC*/ {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, {SPU_shufb, SPU_F_NONE}, ++ /*600*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*604*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*608*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*60C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*610*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*614*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*618*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*61C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*620*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*624*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*628*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*62C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*630*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*634*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*638*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*63C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*640*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*644*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*648*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*64C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*650*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*654*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*658*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*65C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*660*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*664*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*668*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*66C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*670*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*674*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*678*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*67C*/ {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, {SPU_mpya, SPU_F_NONE}, ++ /*680*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*684*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*688*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*68C*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*690*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*694*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*698*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*69C*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6A0*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6A4*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6A8*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6AC*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6B0*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6B4*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6B8*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6BC*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6C0*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6C4*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6C8*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6CC*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6D0*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6D4*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6D8*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6DC*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6E0*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6E4*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6E8*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6EC*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6F0*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6F4*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6F8*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*6FC*/ {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, {SPU_fnms, SPU_F_NONE}, ++ /*700*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*704*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*708*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*70C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*710*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*714*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*718*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*71C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*720*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*724*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*728*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*72C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*730*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*734*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*738*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*73C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*740*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*744*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*748*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*74C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*750*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*754*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*758*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*75C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*760*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*764*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*768*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*76C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*770*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*774*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*778*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*77C*/ {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, {SPU_fma, SPU_F_NONE}, ++ /*780*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*784*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*788*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*78C*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*790*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*794*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*798*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*79C*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7A0*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7A4*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7A8*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7AC*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7B0*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7B4*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7B8*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7BC*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7C0*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7C4*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7C8*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7CC*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7D0*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7D4*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7D8*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7DC*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7E0*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7E4*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7E8*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7EC*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7F0*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7F4*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7F8*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++ /*7FC*/ {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, {SPU_fms, SPU_F_NONE}, ++}; +diff --git a/runtime/spu/tests/test_spu_decode.c b/runtime/spu/tests/test_spu_decode.c +new file mode 100644 +index 00000000..a5159e17 +--- /dev/null ++++ b/runtime/spu/tests/test_spu_decode.c +@@ -0,0 +1,192 @@ ++/* The interpreter's decode contract: op and every field spu_decode1 hands to ++ * the execute switch, for instructions at the opcode-width and immediate-form ++ * boundaries. Encodings are built here from the SPU ISA field layouts (IBM SPU ++ * ISA v1.2, ch. 2), not from the generated table, so a table whose precedence ++ * or immediate forms drift fails against independent expectations. spu_decode1 ++ * is static, hence the include of the interpreter itself. */ ++#include "../spu_interp.c" ++#include <assert.h> ++#include <stdio.h> ++#include <string.h> ++ ++/* Decode-only test: nothing here executes, so the external hooks must never run. */ ++u128 spu_rdch(spu_context* c, uint32_t ch) { (void)c; (void)ch; abort(); } ++void spu_wrch(spu_context* c, uint32_t ch, u128 v) { (void)c; (void)ch; (void)v; abort(); } ++uint32_t spu_rchcnt(spu_context* c, uint32_t ch) { (void)c; (void)ch; abort(); } ++int g_spu_ls_watch_n, g_spu_ls_probe, g_wws_read_probe, g_wws_code_probe, g_spu_smc_watch; ++spu_lifted_fn spu_lifted_lookup(const spu_context* c, uint32_t a) { (void)c; (void)a; abort(); } ++void spu_spurs_taskset_syscall(spu_context* c) { (void)c; abort(); } ++void spu_ls_watch_slow(uint32_t l, int w, const uint8_t* p, uint32_t pc, uint32_t lr) { ++ (void)l; (void)w; (void)p; (void)pc; (void)lr; abort(); ++} ++ ++/* ISA layouts, bit 0 = LSB. */ ++static uint32_t rrr(uint32_t op4, uint32_t rt, uint32_t rb, uint32_t ra, uint32_t rc) { ++ return (op4 << 28) | (rt << 21) | (rb << 14) | (ra << 7) | rc; ++} ++static uint32_t ri18(uint32_t op7, uint32_t i18, uint32_t rt) { ++ return (op7 << 25) | ((i18 & 0x3FFFF) << 7) | rt; ++} ++static uint32_t ri16(uint32_t op9, uint32_t i16, uint32_t rt) { ++ return (op9 << 23) | ((i16 & 0xFFFF) << 7) | rt; ++} ++static uint32_t ri10(uint32_t op8, uint32_t i10, uint32_t ra, uint32_t rt) { ++ return (op8 << 24) | ((i10 & 0x3FF) << 14) | (ra << 7) | rt; ++} ++static uint32_t ri8(uint32_t op10, uint32_t i8, uint32_t ra, uint32_t rt) { ++ return (op10 << 22) | ((i8 & 0xFF) << 14) | (ra << 7) | rt; ++} ++/* RI7 and RR share the 11-bit opcode; RR's rb sits where RI7's i7 does. */ ++static uint32_t ri7(uint32_t op11, uint32_t i7, uint32_t ra, uint32_t rt) { ++ return (op11 << 21) | ((i7 & 0x7F) << 14) | (ra << 7) | rt; ++} ++ ++static int failures; ++static spu_ins dec(uint32_t insn, uint32_t pc) { ++ spu_ins d; ++ memset(&d, 0xFF, sizeof d); /* decode must overwrite every field, not leak the caller's */ ++ spu_decode1(insn, pc, &d); ++ return d; ++} ++#define CHECK(cond, what, insn) do { if (!(cond)) { \ ++ fprintf(stderr, "FAIL %s insn=%08X: %s\n", what, (unsigned)(insn), #cond); ++failures; } } while (0) ++ ++static void expect_imm(const char* what, uint32_t insn, spu_op op, int32_t imm) { ++ spu_ins d = dec(insn, 0x100); ++ CHECK(d.op == op, what, insn); ++ CHECK(d.imm == imm, what, insn); ++ CHECK(d.tgt == 0, what, insn); ++} ++static void expect_tgt(const char* what, uint32_t insn, uint32_t pc, spu_op op, uint32_t tgt) { ++ spu_ins d = dec(insn, pc); ++ CHECK(d.op == op, what, insn); ++ CHECK(d.tgt == tgt, what, insn); ++ CHECK(d.imm == 0, what, insn); ++} ++ ++int main(void) { ++ /* RRR: shufb rt=5 rb=6 ra=7 rc=8. The destination is the high field, which ++ * the interpreter calls rc; the low field is the third source (rt). */ ++ { ++ uint32_t i = rrr(0xB, 5, 6, 7, 8); ++ spu_ins d = dec(i, 0); ++ CHECK(d.op == SPU_shufb, "shufb", i); ++ CHECK(d.rc == 5 && d.rb == 6 && d.ra == 7 && d.rt == 8, "shufb fields", i); ++ CHECK(d.imm == 0 && d.tgt == 0, "shufb no imm", i); ++ } ++ ++ /* RI18 */ ++ expect_imm("ila 18 bits", ri18(0x21, 0x3FFFF, 3), SPU_ila, 0x3FFFF); ++ expect_imm("ila high bit", ri18(0x21, 0x20000, 3), SPU_ila, 0x20000); ++ { ++ spu_ins d = dec(ri18(0x21, 0x2ABCD, 9), 0); ++ CHECK(d.rt == 9, "ila rt", 0); ++ } ++ ++ /* Hints (hbra/hbrr) are the other RI18 ops: only the low 16 bits of the ++ * 18-bit field are the immediate; the top two belong to the split ROH field. */ ++ expect_imm("hbra low 16", ri18(0x08, 0x3FFFF, 3), SPU_hbra, 0xFFFF); ++ expect_imm("hbrr low 16", ri18(0x09, 0x2ABCD, 3), SPU_hbrr, 0xABCD); ++ ++ /* RI16 immediates: il sign-extends; ilh/ilhu/iohl/fsmbi zero-extend. */ ++ expect_imm("il negative", ri16(0x081, 0x8000, 4), SPU_il, -32768); ++ expect_imm("il -1", ri16(0x081, 0xFFFF, 4), SPU_il, -1); ++ expect_imm("il positive", ri16(0x081, 0x7FFF, 4), SPU_il, 0x7FFF); ++ expect_imm("ilhu", ri16(0x082, 0xFFFF, 4), SPU_ilhu, 0xFFFF); ++ expect_imm("ilh", ri16(0x083, 0x8001, 4), SPU_ilh, 0x8001); ++ expect_imm("iohl unsigned", ri16(0x0C1, 0x8000, 4), SPU_iohl, 0x8000); ++ expect_imm("fsmbi", ri16(0x065, 0xFFFF, 4), SPU_fsmbi, 0xFFFF); ++ ++ /* RI16 targets: pc-relative forms add pc, absolute ones do not; the ++ * quadword forms mask to 16-byte alignment, branches to word alignment. */ ++ expect_tgt("lqr back", ri16(0x067, 0xFFFF, 4), 0x104, SPU_lqr, 0x100); ++ expect_tgt("stqr back", ri16(0x047, 0xFFFF, 4), 0x104, SPU_stqr, 0x100); ++ expect_tgt("lqr wraps past 256K", ri16(0x067, 8, 4), 0x3FFF0, SPU_lqr, 0x10); ++ expect_tgt("lqr wraps below 0", ri16(0x067, 0xFFF0, 4), 0x20, SPU_lqr, 0x3FFE0); ++ expect_tgt("br wraps past 256K", ri16(0x064, 1, 0), 0x3FFFC, SPU_br, 0); ++ expect_tgt("br wraps below 0", ri16(0x064, 0xFFFF, 0), 0, SPU_br, 0x3FFFC); ++ expect_tgt("br forward", ri16(0x064, 0x10, 0), 0x200, SPU_br, 0x240); ++ expect_tgt("brsl", ri16(0x066, 4, 0), 0x400, SPU_brsl, 0x410); ++ expect_tgt("brz", ri16(0x040, 2, 3), 0x800, SPU_brz, 0x808); ++ expect_tgt("brnz", ri16(0x042, 0xFFFE, 3), 0x800, SPU_brnz, 0x7F8); ++ expect_tgt("brhz", ri16(0x044, 1, 3), 0x800, SPU_brhz, 0x804); ++ expect_tgt("brhnz", ri16(0x046, 1, 3), 0x800, SPU_brhnz, 0x804); ++ expect_tgt("bra ignores pc", ri16(0x060, 0x4000, 0), 0x3FFFC, SPU_bra, 0x10000); ++ expect_tgt("bra negative", ri16(0x060, 0xFFFF, 0), 0x100, SPU_bra, 0x3FFFC); ++ expect_tgt("brasl", ri16(0x062, 3, 0), 0x100, SPU_brasl, 0xC); ++ expect_tgt("lqa", ri16(0x061, 0xFFFF, 4), 0x100, SPU_lqa, 0x3FFF0); ++ expect_tgt("stqa", ri16(0x041, 0x0123, 4), 0x100, SPU_stqa, 0x0480); ++ ++ /* RI10: lqd/stqd scale the displacement by 16; the rest do not. */ ++ expect_imm("lqd +3", ri10(0x34, 3, 1, 2), SPU_lqd, 48); ++ expect_imm("lqd -2", ri10(0x34, 0x3FE, 1, 2), SPU_lqd, -32); ++ expect_imm("stqd -512", ri10(0x24, 0x200, 1, 2), SPU_stqd, -8192); ++ expect_imm("stqd +511", ri10(0x24, 0x1FF, 1, 2), SPU_stqd, 8176); ++ expect_imm("ai -1", ri10(0x1C, 0x3FF, 1, 2), SPU_ai, -1); ++ expect_imm("ori +511", ri10(0x04, 0x1FF, 1, 2), SPU_ori, 511); ++ { ++ uint32_t i = ri10(0x1C, 0x155, 17, 90); ++ spu_ins d = dec(i, 0); ++ CHECK(d.ra == 17 && d.rt == 90 && d.ch == 17, "ai fields", i); ++ } ++ ++ /* Channel ops are 11-bit opcodes; wrch (0x10D) must not be taken for the ++ * shift-immediate family whose 11-bit opcode (shli 0x07B) differs. */ ++ { ++ uint32_t i = ri7(0x00D, 0, 5, 6); /* rdch $6, $ch5 */ ++ spu_ins d = dec(i, 0); ++ CHECK(d.op == SPU_rdch && d.ch == 5 && d.rt == 6 && d.imm == 0, "rdch", i); ++ i = ri7(0x10D, 0, 7, 8); ++ d = dec(i, 0); ++ CHECK(d.op == SPU_wrch && d.ch == 7 && d.rt == 8 && d.imm == 0, "wrch", i); ++ i = ri7(0x00F, 0, 9, 10); ++ d = dec(i, 0); ++ CHECK(d.op == SPU_rchcnt && d.ch == 9 && d.rt == 10 && d.imm == 0, "rchcnt", i); ++ /* The whole 7-bit channel field reaches spu_rdch/spu_wrch; SPU channels go up to 127. */ ++ i = ri7(0x00D, 0, 0x7F, 1); ++ d = dec(i, 0); ++ CHECK(d.op == SPU_rdch && d.ch == 0x7F && d.rt == 1, "rdch channel 127", i); ++ expect_imm("shli is not wrch", ri7(0x07B, 3, 5, 6), SPU_shli, 3); ++ } ++ ++ /* STOP: 14-bit signal type, and no other RR form carries an immediate. */ ++ expect_imm("stop 14 bits", 0x00003FFFu, SPU_stop, 0x3FFF); ++ expect_imm("stop 0x2A5", 0x000002A5u, SPU_stop, 0x2A5); ++ expect_imm("stop ignores bit 14", 0x00004001u, SPU_stop, 1); ++ expect_imm("a has no imm", ri7(0x0C0, 0x7F, 1, 2), SPU_a, 0); ++ ++ /* RI7: shifts/rotates sign-extend, the generate-controls zero-extend. */ ++ expect_imm("shli -64", ri7(0x07B, 0x40, 1, 2), SPU_shli, -64); ++ expect_imm("roti 63", ri7(0x078, 0x3F, 1, 2), SPU_roti, 63); ++ expect_imm("rotqbyi -1", ri7(0x1FC, 0x7F, 1, 2), SPU_rotqbyi, -1); ++ expect_imm("cwd 64 unsigned", ri7(0x1F6, 0x40, 1, 2), SPU_cwd, 64); ++ expect_imm("cbd 127 unsigned", ri7(0x1F4, 0x7F, 1, 2), SPU_cbd, 127); ++ ++ /* RI8: unsigned 8-bit scale, for all four conversions. */ ++ expect_imm("cflts 255", ri8(0x1D8, 0xFF, 1, 2), SPU_cflts, 255); ++ expect_imm("cfltu 255", ri8(0x1D9, 0xFF, 1, 2), SPU_cfltu, 255); ++ expect_imm("csflt 0x81", ri8(0x1DA, 0x81, 1, 2), SPU_csflt, 0x81); ++ expect_imm("cuflt 0x80", ri8(0x1DB, 0x80, 1, 2), SPU_cuflt, 0x80); ++ ++ /* RR/LSX register forms. */ ++ { ++ uint32_t i = ri7(0x1C4, 11, 12, 13); /* lqx $13, $12, $11 */ ++ spu_ins d = dec(i, 0); ++ CHECK(d.op == SPU_lqx && d.rb == 11 && d.ra == 12 && d.rt == 13 && d.imm == 0 && d.tgt == 0, ++ "lqx", i); ++ i = ri7(0x144, 11, 12, 13); ++ d = dec(i, 0); ++ CHECK(d.op == SPU_stqx && d.rb == 11 && d.ra == 12 && d.rt == 13, "stqx", i); ++ } ++ ++ /* A word no table claims traps as `.word`, with no immediate. */ ++ { ++ uint32_t i = 0x00800000u; /* 11-bit opcode 0x004 */ ++ spu_ins d = dec(i, 0x40); ++ CHECK(d.op == SPU_word && d.imm == 0 && d.tgt == 0, "invalid word", i); ++ } ++ ++ if (failures) { fprintf(stderr, "%d failure(s)\n", failures); return 1; } ++ printf("spu_decode1: all contract checks passed\n"); ++ return 0; ++} +diff --git a/tools/gen_spu_interp.py b/tools/gen_spu_interp.py +old mode 100644 +new mode 100755 +index 4f658c1e..77ac8f16 +--- a/tools/gen_spu_interp.py ++++ b/tools/gen_spu_interp.py +@@ -1,5 +1,5 @@ + #!/usr/bin/env python3 +-"""Generate the SPU interpreter's decode tables (C) from the validated Python ++"""Generate the SPU interpreter's decode table (C) from the validated Python + decoder (spu_disasm.py). The interpreter is the correctness floor for the SPU + static recompiler: computed/indirect branches (`bi $reg`) and DMA'd or + self-modified code (LBP overlays, spu_0004's `sync; bi $3` trampoline) can't be +@@ -30,13 +30,14 @@ RI7 = { + RI7_UNSIGNED = {"cbd", "chd", "cwd", "cdd"} + RI8 = {0x1d8: "cflts", 0x1d9: "cfltu", 0x1da: "csflt", 0x1db: "cuflt"} # op10 + LSX = {0x1c4: "lqx", 0x144: "stqx"} ++CHANNEL = {0x00D: "rdch", 0x10D: "wrch", 0x00F: "rchcnt"} # op11 + + # Every mnemonic the decoder can emit -> a stable enum. `.word` is the trap. + all_mn = set() + for t in (D.RRR_TABLE, D.RI18_TABLE, D.RI16_TABLE, D.RI10_TABLE, D.SPU_RR, +- RI7, RI8, LSX): ++ RI7, RI8, LSX, CHANNEL): + all_mn.update(t.values()) +-all_mn.update(["rdch", "wrch", "rchcnt", ".word"]) ++all_mn.add(".word") + mnems = sorted(all_mn) + + +@@ -44,11 +45,92 @@ def enum_name(m): + return "SPU_" + ("word" if m == ".word" else m) + + ++# Every opcode field of the SPU ISA (RRR 4 bits, RI18 7, RI16 9, RI10 8, RI8 10, ++# RI7/RR/LSX/channel 11) is a prefix of instruction bits 31..21, so the matched ++# mnemonic is a pure function of p = insn >> 21 and the whole decode collapses ++# into one 2048-entry table. The immediate form is a function of the matched ++# mnemonic and of the table it came from; the position-fixed operand fields ++# (rt/ra/rb/rc/ch) stay in spu_decode1. ++# ++# Prefixes may match more than one table, and the first stage to match wins, so ++# this order IS the decoder's precedence and mirrors spu_disasm.spu_decode: ++# RI16 before RI10 (an RI10 opcode equal to the top 8 bits of an RI16 opcode ++# must not shadow it), channel ops before RI10, RR before RI7, LSX last, else ++# `.word`. With the current tables the only prefixes matched twice are ++# rdch/rchcnt/wrch (channel and RR) and lqx/stqx (RR and LSX), where both ++# stages agree; the order is kept so a table entry added later resolves ++# exactly as the old cascade did instead of silently changing which ++# instruction executes. ++STAGES = ( ++ ("rrr", 4, D.RRR_TABLE), ++ ("ri18", 7, D.RI18_TABLE), ++ ("ri16", 9, D.RI16_TABLE), ++ ("chan", 11, CHANNEL), ++ ("ri10", 8, D.RI10_TABLE), ++ ("ri8", 10, RI8), ++ ("rr", 11, D.SPU_RR), ++ ("ri7", 11, RI7), ++ ("lsx", 11, LSX), ++) ++ ++# How spu_decode1 derives `imm` / `tgt` for a decoded instruction. ++FORMS = ( ++ ("NONE", "no immediate: RRR, RR (except stop), LSX, channel ops, .word"), ++ ("I18", "ila: full 18-bit immediate"), ++ ("I18LO", "other RI18 (hbra/hbrr): low 16 bits of the 18-bit field"), ++ ("LQA", "lqa/stqa: absolute 16-byte aligned LS address in tgt"), ++ ("LQR", "lqr/stqr: pc-relative 16-byte aligned LS address in tgt"), ++ ("BREL", "br/brsl/brz/brnz/brhz/brhnz: pc-relative target in tgt"), ++ ("BABS", "bra/brasl: absolute target in tgt"), ++ ("I16S", "il: sign-extended 16-bit immediate"), ++ ("I16U", "ilh/ilhu/iohl/fsmbi: zero-extended 16-bit immediate"), ++ ("I10", "RI10: sign-extended 10-bit immediate"), ++ ("I10Q", "lqd/stqd: sign-extended 10-bit immediate scaled by 16"), ++ ("I8", "RI8 float<->int conversions: unsigned 8-bit scale"), ++ ("STOP", "stop: 14-bit signal type"), ++ ("I7S", "RI7: sign-extended 7-bit immediate"), ++ ("I7U", "cbd/chd/cwd/cdd: unsigned 7-bit immediate"), ++) ++ ++RI16_FORMS = { ++ "lqa": "LQA", "stqa": "LQA", "lqr": "LQR", "stqr": "LQR", ++ "br": "BREL", "brsl": "BREL", "brz": "BREL", "brnz": "BREL", ++ "brhz": "BREL", "brhnz": "BREL", "bra": "BABS", "brasl": "BABS", ++ "il": "I16S", ++} ++ ++ ++def form_of(stage, mn): ++ if stage == "ri18": ++ return "I18" if mn == "ila" else "I18LO" ++ if stage == "ri16": ++ return RI16_FORMS.get(mn, "I16U") ++ if stage == "ri10": ++ return "I10Q" if mn in ("lqd", "stqd") else "I10" ++ if stage == "ri8": ++ return "I8" ++ if stage == "rr": ++ return "STOP" if mn == "stop" else "NONE" ++ if stage == "ri7": ++ return "I7U" if mn in RI7_UNSIGNED else "I7S" ++ return "NONE" ++ ++ ++def decode_prefix(p): ++ """(mnemonic, form) for the 11-bit prefix p = insn >> 21.""" ++ for stage, bits, table in STAGES: ++ mn = table.get(p >> (11 - bits)) ++ if mn is not None: ++ return mn, form_of(stage, mn) ++ return ".word", "NONE" ++ ++ + out = [] + w = out.append + w("/* GENERATED by tools/gen_spu_interp.py -- do not edit. */") +-w("/* Opcode->mnemonic tables for the SPU interpreter, from the validated") +-w(" * spu_disasm.py decoder. Regenerate after any decoder table change. */") ++w("/* Opcode->mnemonic enum and the insn>>21 decode table for the SPU") ++w(" * interpreter, from the validated spu_disasm.py decoder. Regenerate after") ++w(" * any decoder table change. */") + w("") + w("typedef enum {") + for m in mnems: +@@ -61,31 +143,23 @@ for m in mnems: + w(f' [{enum_name(m)}] = "{m}",') + w("};") + w("") +- +- +-def emit_lookup(fn, table, argbits, argname): +- w(f"static spu_op {fn}(uint32_t {argname}) {{") +- w(" switch (%s) {" % argname) +- for k in sorted(table): +- w(f" case 0x{k:X}: return {enum_name(table[k])};") +- w(f" default: return SPU_word;") +- w(" }") +- w("}") +- w("") +- +- +-emit_lookup("spu_dec_rrr", D.RRR_TABLE, 4, "op4") +-emit_lookup("spu_dec_ri18", D.RI18_TABLE, 7, "op7") +-emit_lookup("spu_dec_ri16", D.RI16_TABLE, 9, "op9") +-emit_lookup("spu_dec_ri10", D.RI10_TABLE, 8, "op8") +-emit_lookup("spu_dec_ri8", RI8, 10, "op10") +-emit_lookup("spu_dec_rr", D.SPU_RR, 11, "op11") +-emit_lookup("spu_dec_ri7", RI7, 11, "op11") +-emit_lookup("spu_dec_lsx", LSX, 11, "op11") +- +-w("/* signed-vs-unsigned i7 per instruction (Table 2-6) */") +-w("static int spu_ri7_unsigned(spu_op op) {") +-w(" return %s;" % " || ".join(f"op == {enum_name(m)}" for m in sorted(RI7_UNSIGNED))) +-w("}") ++w("/* How spu_decode1 derives imm/tgt. */") ++w("typedef enum {") ++for f, why in FORMS: ++ w(f" SPU_F_{f}, /* {why} */") ++w("} spu_decode_form;") ++w("") ++w("typedef struct { uint8_t op; uint8_t form; } spu_decode_ent;") ++w('_Static_assert(SPU_OP_COUNT <= 256, "spu_op must fit spu_decode_ent.op");') ++w("") ++w("/* Indexed by insn >> 21; precedence is documented in tools/gen_spu_interp.py. */") ++w("static const spu_decode_ent spu_decode_tab[2048] = {") ++for base in range(0, 2048, 4): ++ cells = [] ++ for p in range(base, base + 4): ++ mn, form = decode_prefix(p) ++ cells.append("{%s, SPU_F_%s}," % (enum_name(mn), form)) ++ w(f" /*{base:03X}*/ " + " ".join(cells)) ++w("};") + + sys.stdout.write("\n".join(out) + "\n") diff --git a/tasks/sp00nznet__ps3recomp-688/tests/test.sh b/tasks/sp00nznet__ps3recomp-688/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-688/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-688/tests/verifier.py b/tasks/sp00nznet__ps3recomp-688/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-688/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-689/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-689/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-689/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-689/instruction.md b/tasks/sp00nznet__ps3recomp-689/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..49208ba7b9f1c5d7219fe2c85876d8aafe9471d1 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-689/instruction.md @@ -0,0 +1,74 @@ +# Issue + +**Title:** cellSysutilAvc2: export Load, Unload and the setters + +## Description + +## Why + +`cellSysutilAvc2.c` exports `LoadAsync` but not the synchronous `cellSysutilAvc2Load` (NID 0xC6C93D62), which takes the +same arguments. J-Stars Victory VS+ (BLUS31519) loads voice chat with `Load` when it creates or joins an online room. +With no handler for that NID, the call went to the unresolved-NID path and the title's Avc2 callback was never stored. +`JoinChatRequest` then queued its JOIN_SUCCEEDED to nobody, and the room screen waited for it until it timed out. + +## Change + +- `cellSysutilAvc2Load` does what `LoadAsync` does: it stores the callback and userdata and reports LOAD_SUCCEEDED. +- `cellSysutilAvc2Unload` reports UNLOAD_SUCCEEDED, as `UnloadAsync` does. +- `SetAttribute`, `SetSpeakerVolumeLevel`, `SetSpeakerMuting`, `SetVoiceMuting`, `StartVoiceDetection` and + `StopVoiceDetection` return OK, like the rest of this silent chat. The same title calls all of them while it sets + up the room. + +The HLE table is generated from the function names, so defining the functions is what exports their NIDs. + +## Tests + +New `libs/network/tests/test_avc2_load.c`, run in `linux.yml`, `macos.yml` and `windows.yml` (after the NAT traversal +step). It compiles `cellSysutilAvc2.c` in with `cellSysutilQueueGuestCallbackArgs` stubbed, and checks that: + +- `ps3_compute_nid("cellSysutilAvc2Load")` is 0xC6C93D62 and `"cellSysutilAvc2Unload"` is 0x38F33624, the NIDs titles + import; +- `Load` queues LOAD_SUCCEEDED (1) to the title's callback with its userdata, and a later `JoinChatRequest` queues + JOIN_SUCCEEDED (5) to the same callback; +- the setters return OK and queue nothing; +- `LeaveChatRequest` and `Unload` queue LEAVE_SUCCEEDED and UNLOAD_SUCCEEDED. + +``` +gcc -std=gnu17 -I include -o /tmp/test_avc2_load libs/network/tests/test_avc2_load.c +/tmp/test_avc2_load # test_avc2_load: ok (4 events) +``` + +The test calls functions that master does not have, so it cannot build there. As the control, on master the same +file fails to compile (`implicit declaration of function 'cellSysutilAvc2Load'`, and the same for the setters), and a +game build from master has no handler for 0xC6C93D62. + +## Evidence + +- The new test passes with gcc and clang (`-Wall`, no warnings). +- All `linux.yml` steps run locally with gcc and clang (Release) on this commit: 38 of 40 pass with both. The 2 that + fail also fail on master on this machine: the guest shader translation test is not built because glslang and + spirv-cross are not installed here, and the POSIX host check reports "right x stick = 131 NOT CENTRED" because a + real controller is plugged in. +- The game: J-Stars Victory VS+ (BLUS31519), built on v0.18.0 with this change, run under Proton against the in-tree + psnr server on loopback. Before the change the room screen timed out. With it the title gets LOAD_SUCCEEDED and + JOIN_SUCCEEDED, the room opens, and a second instance can join (with the sceNpSignaling PR sent alongside this one). + +Not run: macOS and Windows natively (the workflows will cover them). One Avc2 NID the title imports, 0x02C5417A, +still has no name here and is not part of this PR. + +## Overlap + +No open PR touches `cellSysutilAvc2.c`. + +Open PRs that edit `linux.yml`, `macos.yml` or `windows.yml`: the workflow hunks of #687, #683, #681, #680, #669, +#658, #655, #633, #612, #611, #605, #550 and #470 apply on top of this branch (#550 already conflicts with master in +other files). #590 only changes the `uses:` lines near the top of each workflow, far from the step added here; its +hunks do not apply to master either. + +The sceNpSignaling PR sent alongside adds its step in a different place, and either can merge first. #673 makes +`ppu_memory.h` call `spu_linelock_lock` and `spu_linelock_release` and adds stubs for them to the network tests; the +new test already has the same two stubs. I have not built it with #673 applied. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-689/solution/patch.diff b/tasks/sp00nznet__ps3recomp-689/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a328f0ca51777e84a8a297f36540c2efc51b90d3 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-689/solution/patch.diff @@ -0,0 +1,185 @@ +diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml +index 99c0b20c..66354bf3 100644 +--- a/.github/workflows/linux.yml ++++ b/.github/workflows/linux.yml +@@ -203,6 +203,13 @@ jobs: + ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} -std=gnu17 -I include -o /tmp/test_np_nat libs/network/tests/test_np_nat.c + /tmp/test_np_nat + ++ # cellSysutilAvc2: the synchronous Load is exported under the NID titles ++ # import and its callback gets LOAD_SUCCEEDED and JOIN_SUCCEEDED. ++ - name: Run the Avc2 Load test ++ run: | ++ ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} -std=gnu17 -I include -o /tmp/test_avc2_load libs/network/tests/test_avc2_load.c ++ /tmp/test_avc2_load ++ + # sceNpCommerce2CreateCtx takes the SDK's five arguments and stores the context id through the fifth. + - name: Run the Commerce2 CreateCtx test + run: | +diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml +index aeb9e948..ba60ea66 100644 +--- a/.github/workflows/macos.yml ++++ b/.github/workflows/macos.yml +@@ -184,6 +184,13 @@ jobs: + clang -std=gnu17 -I include -o /tmp/test_np_nat libs/network/tests/test_np_nat.c + /tmp/test_np_nat + ++ # cellSysutilAvc2: the synchronous Load is exported under the NID titles ++ # import and its callback gets LOAD_SUCCEEDED and JOIN_SUCCEEDED. ++ - name: Run the Avc2 Load test ++ run: | ++ clang -std=gnu17 -I include -o /tmp/test_avc2_load libs/network/tests/test_avc2_load.c ++ /tmp/test_avc2_load ++ + # cellPadSetActDirect: the small motor is on/off at full strength, and + # a rumble lasts until the title changes it (renewed from the pad poll). + - name: Run the pad rumble test +diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml +index c4596291..e9a23600 100644 +--- a/.github/workflows/windows.yml ++++ b/.github/workflows/windows.yml +@@ -137,6 +137,15 @@ jobs: + .\test_np_nat.exe + if ($LASTEXITCODE -ne 0) { exit 1 } + ++ # cellSysutilAvc2: the synchronous Load is exported under the NID titles ++ # import and its callback gets LOAD_SUCCEEDED and JOIN_SUCCEEDED. ++ - name: Run the Avc2 Load test ++ run: | ++ clang-cl /nologo /W0 /D_CRT_SECURE_NO_WARNINGS /I include /Fe:test_avc2_load.exe libs/network/tests/test_avc2_load.c ++ if ($LASTEXITCODE -ne 0) { exit 1 } ++ .\test_avc2_load.exe ++ if ($LASTEXITCODE -ne 0) { exit 1 } ++ + # arithmetic with no host API in it, so it runs everywhere, and it is the + # regression net for having lifted that maths out of the D3D12 uploader. + # sync_stress has always been the Windows-native suite; now that its +diff --git a/libs/network/cellSysutilAvc2.c b/libs/network/cellSysutilAvc2.c +index 264b9b04..f85ec82e 100644 +--- a/libs/network/cellSysutilAvc2.c ++++ b/libs/network/cellSysutilAvc2.c +@@ -54,6 +54,33 @@ s32 cellSysutilAvc2LoadAsync(u16 ctxId, u32 container, u32 callback, u32 userdat + return CELL_OK; + } + ++/* The synchronous load, same arguments. J-Stars Victory VS+ calls this one, not LoadAsync: with it unexported the ++ * title's callback was never stored, so JoinChatRequest's JOIN_SUCCEEDED had no one to go to and the room screen ++ * timed out. Load reports LOAD_SUCCEEDED through the callback as LoadAsync does; the title proceeds on it. */ ++s32 cellSysutilAvc2Load(u16 ctxId, u32 container, u32 callback, u32 userdata, u32 initParam) ++{ ++ (void)ctxId; (void)container; (void)initParam; ++ s_cb = callback; ++ s_userdata = userdata; ++ printf("[cellSysutilAvc2] Load: voice chat up, silent\n"); ++ avc2_event(AVC2_EVENT_LOAD_SUCCEEDED); ++ return CELL_OK; ++} ++ ++s32 cellSysutilAvc2Unload(void) ++{ ++ avc2_event(AVC2_EVENT_UNLOAD_SUCCEEDED); ++ return CELL_OK; ++} ++ ++/* Settings of a chat that carries no audio: accepted. (CellSysutilAvc2AttributeId, CellSysutilAvc2Attribute*) */ ++s32 cellSysutilAvc2SetAttribute(u32 attr) { (void)attr; return CELL_OK; } ++s32 cellSysutilAvc2SetSpeakerVolumeLevel(u32 level) { (void)level; return CELL_OK; } ++s32 cellSysutilAvc2SetSpeakerMuting(u8 muting) { (void)muting; return CELL_OK; } ++s32 cellSysutilAvc2SetVoiceMuting(u8 muting) { (void)muting; return CELL_OK; } ++s32 cellSysutilAvc2StartVoiceDetection(void) { return CELL_OK; } ++s32 cellSysutilAvc2StopVoiceDetection(void) { return CELL_OK; } ++ + s32 cellSysutilAvc2UnloadAsync(void) + { + avc2_event(AVC2_EVENT_UNLOAD_SUCCEEDED); +diff --git a/libs/network/tests/test_avc2_load.c b/libs/network/tests/test_avc2_load.c +new file mode 100644 +index 00000000..a52b1206 +--- /dev/null ++++ b/libs/network/tests/test_avc2_load.c +@@ -0,0 +1,85 @@ ++/* ++ * test_avc2_load - cellSysutilAvc2Load and the setters. ++ * ++ * cc -std=gnu17 -I include -o test_avc2_load libs/network/tests/test_avc2_load.c ++ * ++ * Compiles cellSysutilAvc2.c into this file with sysutil stubbed: the stub ++ * records what would be queued for the title's callback. Checks that the ++ * synchronous Load is defined under the name whose NID titles import ++ * (0xC6C93D62; the HLE table is built from these names), that it stores the ++ * callback so LOAD_SUCCEEDED and a later JoinChatRequest's JOIN_SUCCEEDED ++ * reach it with the title's userdata, and that Unload and the setters return OK. ++ */ ++#include "../cellSysutilAvc2.c" ++#include "ps3emu/nid.h" ++ ++#include <assert.h> ++ ++uint8_t* vm_base; ++int g_resv_store_active; ++uint32_t g_ww_lo, g_ww_hi; ++void ppu_resv_break_store(uint64_t ea) { (void)ea; } ++void ps3_ww_report_inline(uint32_t a, uint64_t v, int w) { (void)a; (void)v; (void)w; } ++int spu_coh_is_reserved(uint32_t a) { (void)a; return 0; } ++void spu_coh_notify_write(uint32_t a) { (void)a; } ++void spu_lockline_lock(void) {} ++void spu_lockline_unlock(void) {} ++void spu_linelock_lock(uint32_t a) { (void)a; } /* ppu_memory.h's per-line lock, where it has one */ ++void spu_linelock_release(uint32_t a) { (void)a; } ++ ++#define QMAX 8 ++static struct { u32 opd; u64 a[8]; } s_q[QMAX]; ++static int s_nq; ++s32 cellSysutilQueueGuestCallbackArgs(u32 opd, const u64 args[8]) ++{ ++ assert(s_nq < QMAX); ++ s_q[s_nq].opd = opd; ++ memcpy(s_q[s_nq].a, args, sizeof(s_q[s_nq].a)); ++ s_nq++; ++ return CELL_OK; ++} ++ ++/* The queued call k: callback opd, (event_id, event_param, userdata). */ ++static void expect(int k, u32 opd, u32 event, u32 userdata) ++{ ++ assert(k < s_nq); ++ assert(s_q[k].opd == opd && s_q[k].a[0] == event && s_q[k].a[1] == 0 && s_q[k].a[2] == userdata); ++} ++ ++int main(void) ++{ ++ static uint8_t mem[0x1000]; ++ vm_base = mem; ++ const u32 CB = 0x8000, UD = 0x1234; ++ ++ /* The names resolve to the NIDs titles import. */ ++ assert(ps3_compute_nid("cellSysutilAvc2Load") == 0xC6C93D62u); ++ assert(ps3_compute_nid("cellSysutilAvc2Unload") == 0x38F33624u); ++ ++ assert(cellSysutilAvc2InitParam(0x120, 0x100) == CELL_OK); ++ assert(cellSysutilAvc2Load(1, 0, CB, UD, 0x100) == CELL_OK); ++ assert(s_nq == 1); ++ expect(0, CB, AVC2_EVENT_LOAD_SUCCEEDED, UD); ++ ++ /* The stored callback gets the join. */ ++ assert(cellSysutilAvc2JoinChatRequest(0x200) == CELL_OK); ++ assert(s_nq == 2); ++ expect(1, CB, AVC2_EVENT_JOIN_SUCCEEDED, UD); ++ ++ assert(cellSysutilAvc2SetAttribute(0x300) == CELL_OK); ++ assert(cellSysutilAvc2SetSpeakerVolumeLevel(0x304) == CELL_OK); ++ assert(cellSysutilAvc2SetSpeakerMuting(1) == CELL_OK); ++ assert(cellSysutilAvc2SetVoiceMuting(1) == CELL_OK); ++ assert(cellSysutilAvc2StartVoiceDetection() == CELL_OK); ++ assert(cellSysutilAvc2StopVoiceDetection() == CELL_OK); ++ assert(s_nq == 2); ++ ++ assert(cellSysutilAvc2LeaveChatRequest() == CELL_OK); ++ assert(cellSysutilAvc2Unload() == CELL_OK); ++ assert(s_nq == 4); ++ expect(2, CB, AVC2_EVENT_LEAVE_SUCCEEDED, UD); ++ expect(3, CB, AVC2_EVENT_UNLOAD_SUCCEEDED, UD); ++ ++ printf("test_avc2_load: ok (%d events)\n", s_nq); ++ return 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-689/solution/solve.sh b/tasks/sp00nznet__ps3recomp-689/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-689/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-689/task.toml b/tasks/sp00nznet__ps3recomp-689/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1701efaad4379818f09be13e2b1846aafe42d541 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-689/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-689" +description = "cellSysutilAvc2: export Load, Unload and the setters" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/689" +source_access = "auto" +built_at = "2026-11-16T16:09:59.709348+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:980505739a0d65ff0eb45bf6b5be3c1ac9a34b349b31fc995f14ddf1ec108520" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + ".github/workflows/linux.yml", + ".github/workflows/macos.yml", + ".github/workflows/windows.yml", + "libs/network/cellSysutilAvc2.c", + "libs/network/tests/test_avc2_load.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 135 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.157488+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-689/tests/capture.py b/tasks/sp00nznet__ps3recomp-689/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-689/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-689/tests/instruction.md b/tasks/sp00nznet__ps3recomp-689/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..49208ba7b9f1c5d7219fe2c85876d8aafe9471d1 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-689/tests/instruction.md @@ -0,0 +1,74 @@ +# Issue + +**Title:** cellSysutilAvc2: export Load, Unload and the setters + +## Description + +## Why + +`cellSysutilAvc2.c` exports `LoadAsync` but not the synchronous `cellSysutilAvc2Load` (NID 0xC6C93D62), which takes the +same arguments. J-Stars Victory VS+ (BLUS31519) loads voice chat with `Load` when it creates or joins an online room. +With no handler for that NID, the call went to the unresolved-NID path and the title's Avc2 callback was never stored. +`JoinChatRequest` then queued its JOIN_SUCCEEDED to nobody, and the room screen waited for it until it timed out. + +## Change + +- `cellSysutilAvc2Load` does what `LoadAsync` does: it stores the callback and userdata and reports LOAD_SUCCEEDED. +- `cellSysutilAvc2Unload` reports UNLOAD_SUCCEEDED, as `UnloadAsync` does. +- `SetAttribute`, `SetSpeakerVolumeLevel`, `SetSpeakerMuting`, `SetVoiceMuting`, `StartVoiceDetection` and + `StopVoiceDetection` return OK, like the rest of this silent chat. The same title calls all of them while it sets + up the room. + +The HLE table is generated from the function names, so defining the functions is what exports their NIDs. + +## Tests + +New `libs/network/tests/test_avc2_load.c`, run in `linux.yml`, `macos.yml` and `windows.yml` (after the NAT traversal +step). It compiles `cellSysutilAvc2.c` in with `cellSysutilQueueGuestCallbackArgs` stubbed, and checks that: + +- `ps3_compute_nid("cellSysutilAvc2Load")` is 0xC6C93D62 and `"cellSysutilAvc2Unload"` is 0x38F33624, the NIDs titles + import; +- `Load` queues LOAD_SUCCEEDED (1) to the title's callback with its userdata, and a later `JoinChatRequest` queues + JOIN_SUCCEEDED (5) to the same callback; +- the setters return OK and queue nothing; +- `LeaveChatRequest` and `Unload` queue LEAVE_SUCCEEDED and UNLOAD_SUCCEEDED. + +``` +gcc -std=gnu17 -I include -o /tmp/test_avc2_load libs/network/tests/test_avc2_load.c +/tmp/test_avc2_load # test_avc2_load: ok (4 events) +``` + +The test calls functions that master does not have, so it cannot build there. As the control, on master the same +file fails to compile (`implicit declaration of function 'cellSysutilAvc2Load'`, and the same for the setters), and a +game build from master has no handler for 0xC6C93D62. + +## Evidence + +- The new test passes with gcc and clang (`-Wall`, no warnings). +- All `linux.yml` steps run locally with gcc and clang (Release) on this commit: 38 of 40 pass with both. The 2 that + fail also fail on master on this machine: the guest shader translation test is not built because glslang and + spirv-cross are not installed here, and the POSIX host check reports "right x stick = 131 NOT CENTRED" because a + real controller is plugged in. +- The game: J-Stars Victory VS+ (BLUS31519), built on v0.18.0 with this change, run under Proton against the in-tree + psnr server on loopback. Before the change the room screen timed out. With it the title gets LOAD_SUCCEEDED and + JOIN_SUCCEEDED, the room opens, and a second instance can join (with the sceNpSignaling PR sent alongside this one). + +Not run: macOS and Windows natively (the workflows will cover them). One Avc2 NID the title imports, 0x02C5417A, +still has no name here and is not part of this PR. + +## Overlap + +No open PR touches `cellSysutilAvc2.c`. + +Open PRs that edit `linux.yml`, `macos.yml` or `windows.yml`: the workflow hunks of #687, #683, #681, #680, #669, +#658, #655, #633, #612, #611, #605, #550 and #470 apply on top of this branch (#550 already conflicts with master in +other files). #590 only changes the `uses:` lines near the top of each workflow, far from the step added here; its +hunks do not apply to master either. + +The sceNpSignaling PR sent alongside adds its step in a different place, and either can merge first. #673 makes +`ppu_memory.h` call `spu_linelock_lock` and `spu_linelock_release` and adds stubs for them to the network tests; the +new test already has the same two stubs. I have not built it with #673 applied. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-689/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-689/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a328f0ca51777e84a8a297f36540c2efc51b90d3 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-689/tests/oracle.patch @@ -0,0 +1,185 @@ +diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml +index 99c0b20c..66354bf3 100644 +--- a/.github/workflows/linux.yml ++++ b/.github/workflows/linux.yml +@@ -203,6 +203,13 @@ jobs: + ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} -std=gnu17 -I include -o /tmp/test_np_nat libs/network/tests/test_np_nat.c + /tmp/test_np_nat + ++ # cellSysutilAvc2: the synchronous Load is exported under the NID titles ++ # import and its callback gets LOAD_SUCCEEDED and JOIN_SUCCEEDED. ++ - name: Run the Avc2 Load test ++ run: | ++ ${{ matrix.compiler == 'clang' && 'clang' || 'gcc' }} -std=gnu17 -I include -o /tmp/test_avc2_load libs/network/tests/test_avc2_load.c ++ /tmp/test_avc2_load ++ + # sceNpCommerce2CreateCtx takes the SDK's five arguments and stores the context id through the fifth. + - name: Run the Commerce2 CreateCtx test + run: | +diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml +index aeb9e948..ba60ea66 100644 +--- a/.github/workflows/macos.yml ++++ b/.github/workflows/macos.yml +@@ -184,6 +184,13 @@ jobs: + clang -std=gnu17 -I include -o /tmp/test_np_nat libs/network/tests/test_np_nat.c + /tmp/test_np_nat + ++ # cellSysutilAvc2: the synchronous Load is exported under the NID titles ++ # import and its callback gets LOAD_SUCCEEDED and JOIN_SUCCEEDED. ++ - name: Run the Avc2 Load test ++ run: | ++ clang -std=gnu17 -I include -o /tmp/test_avc2_load libs/network/tests/test_avc2_load.c ++ /tmp/test_avc2_load ++ + # cellPadSetActDirect: the small motor is on/off at full strength, and + # a rumble lasts until the title changes it (renewed from the pad poll). + - name: Run the pad rumble test +diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml +index c4596291..e9a23600 100644 +--- a/.github/workflows/windows.yml ++++ b/.github/workflows/windows.yml +@@ -137,6 +137,15 @@ jobs: + .\test_np_nat.exe + if ($LASTEXITCODE -ne 0) { exit 1 } + ++ # cellSysutilAvc2: the synchronous Load is exported under the NID titles ++ # import and its callback gets LOAD_SUCCEEDED and JOIN_SUCCEEDED. ++ - name: Run the Avc2 Load test ++ run: | ++ clang-cl /nologo /W0 /D_CRT_SECURE_NO_WARNINGS /I include /Fe:test_avc2_load.exe libs/network/tests/test_avc2_load.c ++ if ($LASTEXITCODE -ne 0) { exit 1 } ++ .\test_avc2_load.exe ++ if ($LASTEXITCODE -ne 0) { exit 1 } ++ + # arithmetic with no host API in it, so it runs everywhere, and it is the + # regression net for having lifted that maths out of the D3D12 uploader. + # sync_stress has always been the Windows-native suite; now that its +diff --git a/libs/network/cellSysutilAvc2.c b/libs/network/cellSysutilAvc2.c +index 264b9b04..f85ec82e 100644 +--- a/libs/network/cellSysutilAvc2.c ++++ b/libs/network/cellSysutilAvc2.c +@@ -54,6 +54,33 @@ s32 cellSysutilAvc2LoadAsync(u16 ctxId, u32 container, u32 callback, u32 userdat + return CELL_OK; + } + ++/* The synchronous load, same arguments. J-Stars Victory VS+ calls this one, not LoadAsync: with it unexported the ++ * title's callback was never stored, so JoinChatRequest's JOIN_SUCCEEDED had no one to go to and the room screen ++ * timed out. Load reports LOAD_SUCCEEDED through the callback as LoadAsync does; the title proceeds on it. */ ++s32 cellSysutilAvc2Load(u16 ctxId, u32 container, u32 callback, u32 userdata, u32 initParam) ++{ ++ (void)ctxId; (void)container; (void)initParam; ++ s_cb = callback; ++ s_userdata = userdata; ++ printf("[cellSysutilAvc2] Load: voice chat up, silent\n"); ++ avc2_event(AVC2_EVENT_LOAD_SUCCEEDED); ++ return CELL_OK; ++} ++ ++s32 cellSysutilAvc2Unload(void) ++{ ++ avc2_event(AVC2_EVENT_UNLOAD_SUCCEEDED); ++ return CELL_OK; ++} ++ ++/* Settings of a chat that carries no audio: accepted. (CellSysutilAvc2AttributeId, CellSysutilAvc2Attribute*) */ ++s32 cellSysutilAvc2SetAttribute(u32 attr) { (void)attr; return CELL_OK; } ++s32 cellSysutilAvc2SetSpeakerVolumeLevel(u32 level) { (void)level; return CELL_OK; } ++s32 cellSysutilAvc2SetSpeakerMuting(u8 muting) { (void)muting; return CELL_OK; } ++s32 cellSysutilAvc2SetVoiceMuting(u8 muting) { (void)muting; return CELL_OK; } ++s32 cellSysutilAvc2StartVoiceDetection(void) { return CELL_OK; } ++s32 cellSysutilAvc2StopVoiceDetection(void) { return CELL_OK; } ++ + s32 cellSysutilAvc2UnloadAsync(void) + { + avc2_event(AVC2_EVENT_UNLOAD_SUCCEEDED); +diff --git a/libs/network/tests/test_avc2_load.c b/libs/network/tests/test_avc2_load.c +new file mode 100644 +index 00000000..a52b1206 +--- /dev/null ++++ b/libs/network/tests/test_avc2_load.c +@@ -0,0 +1,85 @@ ++/* ++ * test_avc2_load - cellSysutilAvc2Load and the setters. ++ * ++ * cc -std=gnu17 -I include -o test_avc2_load libs/network/tests/test_avc2_load.c ++ * ++ * Compiles cellSysutilAvc2.c into this file with sysutil stubbed: the stub ++ * records what would be queued for the title's callback. Checks that the ++ * synchronous Load is defined under the name whose NID titles import ++ * (0xC6C93D62; the HLE table is built from these names), that it stores the ++ * callback so LOAD_SUCCEEDED and a later JoinChatRequest's JOIN_SUCCEEDED ++ * reach it with the title's userdata, and that Unload and the setters return OK. ++ */ ++#include "../cellSysutilAvc2.c" ++#include "ps3emu/nid.h" ++ ++#include <assert.h> ++ ++uint8_t* vm_base; ++int g_resv_store_active; ++uint32_t g_ww_lo, g_ww_hi; ++void ppu_resv_break_store(uint64_t ea) { (void)ea; } ++void ps3_ww_report_inline(uint32_t a, uint64_t v, int w) { (void)a; (void)v; (void)w; } ++int spu_coh_is_reserved(uint32_t a) { (void)a; return 0; } ++void spu_coh_notify_write(uint32_t a) { (void)a; } ++void spu_lockline_lock(void) {} ++void spu_lockline_unlock(void) {} ++void spu_linelock_lock(uint32_t a) { (void)a; } /* ppu_memory.h's per-line lock, where it has one */ ++void spu_linelock_release(uint32_t a) { (void)a; } ++ ++#define QMAX 8 ++static struct { u32 opd; u64 a[8]; } s_q[QMAX]; ++static int s_nq; ++s32 cellSysutilQueueGuestCallbackArgs(u32 opd, const u64 args[8]) ++{ ++ assert(s_nq < QMAX); ++ s_q[s_nq].opd = opd; ++ memcpy(s_q[s_nq].a, args, sizeof(s_q[s_nq].a)); ++ s_nq++; ++ return CELL_OK; ++} ++ ++/* The queued call k: callback opd, (event_id, event_param, userdata). */ ++static void expect(int k, u32 opd, u32 event, u32 userdata) ++{ ++ assert(k < s_nq); ++ assert(s_q[k].opd == opd && s_q[k].a[0] == event && s_q[k].a[1] == 0 && s_q[k].a[2] == userdata); ++} ++ ++int main(void) ++{ ++ static uint8_t mem[0x1000]; ++ vm_base = mem; ++ const u32 CB = 0x8000, UD = 0x1234; ++ ++ /* The names resolve to the NIDs titles import. */ ++ assert(ps3_compute_nid("cellSysutilAvc2Load") == 0xC6C93D62u); ++ assert(ps3_compute_nid("cellSysutilAvc2Unload") == 0x38F33624u); ++ ++ assert(cellSysutilAvc2InitParam(0x120, 0x100) == CELL_OK); ++ assert(cellSysutilAvc2Load(1, 0, CB, UD, 0x100) == CELL_OK); ++ assert(s_nq == 1); ++ expect(0, CB, AVC2_EVENT_LOAD_SUCCEEDED, UD); ++ ++ /* The stored callback gets the join. */ ++ assert(cellSysutilAvc2JoinChatRequest(0x200) == CELL_OK); ++ assert(s_nq == 2); ++ expect(1, CB, AVC2_EVENT_JOIN_SUCCEEDED, UD); ++ ++ assert(cellSysutilAvc2SetAttribute(0x300) == CELL_OK); ++ assert(cellSysutilAvc2SetSpeakerVolumeLevel(0x304) == CELL_OK); ++ assert(cellSysutilAvc2SetSpeakerMuting(1) == CELL_OK); ++ assert(cellSysutilAvc2SetVoiceMuting(1) == CELL_OK); ++ assert(cellSysutilAvc2StartVoiceDetection() == CELL_OK); ++ assert(cellSysutilAvc2StopVoiceDetection() == CELL_OK); ++ assert(s_nq == 2); ++ ++ assert(cellSysutilAvc2LeaveChatRequest() == CELL_OK); ++ assert(cellSysutilAvc2Unload() == CELL_OK); ++ assert(s_nq == 4); ++ expect(2, CB, AVC2_EVENT_LEAVE_SUCCEEDED, UD); ++ expect(3, CB, AVC2_EVENT_UNLOAD_SUCCEEDED, UD); ++ ++ printf("test_avc2_load: ok (%d events)\n", s_nq); ++ return 0; ++} diff --git a/tasks/sp00nznet__ps3recomp-689/tests/test.sh b/tasks/sp00nznet__ps3recomp-689/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-689/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-689/tests/verifier.py b/tasks/sp00nznet__ps3recomp-689/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-689/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-691/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-691/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-691/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-691/instruction.md b/tasks/sp00nznet__ps3recomp-691/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c834d11c11f789ef9b74dbf10d28fb166db96c3 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-691/instruction.md @@ -0,0 +1,61 @@ +# Issue + +**Title:** ppu_lifter: recover module TOC from OPD majority when .got section name is absent + +## Description + +## Problem + +In the ELF path, when the entry descriptor is detected as bogus (its toc +word repeats the code word), the TOCFIX fallback only tries +`.got + 0x8000`. Stripped homebrew ELFs — e.g. PSL1GHT `EBOOT.BIN` with an +emptied shstrtab, such as **TanakaDOOM-cGcm v0.3** — have no usable section +names at all, so the `.got` lookup finds nothing and the fallback silently +does nothing. The bogus entry toc word is then kept as THE module TOC, and +every `ld r2, N(r1)` TOC-restore lowering hardcodes that garbage constant +(`/*TOCFIX*/`). The guest reads its OPD-hook table through the wrong r2, +sees a null pointer, and spins forever in a `b .` loop. + +Concrete numbers for TanakaDOOM-cGcm v0.3: bogus toc `0x103F8`, true module +TOC `0xA3328`. RPCS3 runs the same ELF fine because crt0 establishes r2 +itself — the entry descriptor's toc word is never used at runtime, which is +why the broken translation only shows up in the static recompilation. + +## Fix + +When the entry descriptor is bogus **and** no `.got` section can be found, +scan the data segments for OPD descriptor pairs `{known-function-start, toc}` +and elect the most frequent toc (threshold: >= 8 votes). Restricting the +code half to detected function starts means incidental pointer data cannot +vote. + +Two details matter: + +- **OPD descriptors are 16 bytes in ELF64** (`{code64, toc64}`). Reading two + consecutive DWORDs pairs `code_lo` with `code_hi == 0`, and 0x0 then wins + the majority vote (TanakaDOOM: 1832 bogus votes for 0x0 vs 1817 real + descriptors). The first version of this patch did exactly that. +- The change lives entirely inside the existing `bogus entry + .got` branch; + ELFs with intact section names take the unchanged `.got+0x8000` route. + +## Validation + +Re-lifting TanakaDOOM-cGcm v0.3 now prints: + +``` +TOC: entry descriptor bogus, no .got; OPD-majority toc = 0xA3328 (1817 descriptors) +``` + +`0xA3328` matches the unanimous toc of all 1817 OPD descriptors and is +self-consistent with the .got tail. The rebuilt native executable passes +the full game init: its TTY log is line-for-line identical to the RPCS3 +reference (RPCS3 being the behavioral ground truth), reaching the title +screen and playing the title music — previously it hung silently before +guest main produced any output. + +Regression coverage for existing samples is expected from the lifter test +suite / CI full run. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-691/solution/patch.diff b/tasks/sp00nznet__ps3recomp-691/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c4bfbbf88d0996683261d5e5e2566d2d6dc38d9f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-691/solution/patch.diff @@ -0,0 +1,52 @@ +diff --git a/tools/ppu_lifter.py b/tools/ppu_lifter.py +index a657ba61..464ff41b 100644 +--- a/tools/ppu_lifter.py ++++ b/tools/ppu_lifter.py +@@ -5340,6 +5340,47 @@ def main() -> None: + if got_addr: + toc = (got_addr + 0x8000) & 0xFFFFFFFF + print(f" TOC: entry descriptor bogus, using .got+0x8000 = 0x{toc:X}") ++ else: ++ # Stripped homebrew ELFs (e.g. PSL1GHT EBOOT.BIN with an ++ # emptied shstrtab) carry no usable section names, so the ++ # .got lookup finds nothing and the bogus entry toc-word ++ # (which repeats the code address) would be kept as THE ++ # module TOC -- every `ld r2, N(r1)` restore lowering then ++ # hardcodes that garbage and the guest spins in the first ++ # OPD-hook poll (TanakaDOOM: 0x103F8 vs true 0xA3328). ++ # Recover the TOC from the OPD instead: scan data segments ++ # for descriptor pairs {known-function-start, toc} and take ++ # the most frequent toc. The code half must be a detected ++ # function start, so incidental pointer data can't vote. ++ from collections import Counter ++ _starts = set(s for s, _ in func_bounds) ++ _toc_freq = Counter() ++ for v0, v1, d in seg_map: ++ if v0 <= text_lo < v1: ++ continue # skip the text segment itself ++ # OPD descriptors are 16 bytes in ELF64: ++ # {code(8), toc(8)}. Reading two consecutive ++ # DWORDs instead would pair code_lo with ++ # code_hi==0 and elect 0x0 as the "majority ++ # TOC" (TanakaDOOM: 1832 bogus votes). ++ _bo = 'big' if big_endian else 'little' ++ for off in range(0, len(d) - 16, 4): ++ c = int.from_bytes(d[off:off + 8], _bo) ++ t = int.from_bytes(d[off + 8:off + 16], _bo) ++ if c in _starts and (t & 3) == 0 and t != c: ++ _toc_freq[t] += 1 ++ if _toc_freq: ++ _t_best, _n_best = _toc_freq.most_common(1)[0] ++ if _n_best >= 8: ++ toc = _t_best ++ print(f" TOC: entry descriptor bogus, no .got; " ++ f"OPD-majority toc = 0x{toc:X} ({_n_best} descriptors)") ++ else: ++ print(f" TOC: entry descriptor bogus, no .got; " ++ f"OPD scan inconclusive (best 0x{_t_best:X} x{_n_best})") ++ else: ++ print(" TOC: entry descriptor bogus, no .got; " ++ "OPD scan found no descriptors") + # Multi-TOC executables (large Sony-toolchain builds like LBP carry + # two or more TOCs): harvest candidates by scanning the data + # segments for OPD descriptor pairs {code-in-text, toc} and keeping diff --git a/tasks/sp00nznet__ps3recomp-691/solution/solve.sh b/tasks/sp00nznet__ps3recomp-691/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-691/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-691/task.toml b/tasks/sp00nznet__ps3recomp-691/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f99d5f73f6ffe273841cc5d1907acbf6618ddeea --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-691/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-691" +description = "ppu_lifter: recover module TOC from OPD majority when .got section name is absent" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/691" +source_access = "auto" +built_at = "2026-11-16T16:09:59.707530+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f80d1f8cb9523a9d5695bc7dc2a43df694dacb6b31f2591439322c0074b34b5c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + "tools/ppu_lifter.py", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 41 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.158035+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-691/tests/capture.py b/tasks/sp00nznet__ps3recomp-691/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-691/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-691/tests/instruction.md b/tasks/sp00nznet__ps3recomp-691/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c834d11c11f789ef9b74dbf10d28fb166db96c3 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-691/tests/instruction.md @@ -0,0 +1,61 @@ +# Issue + +**Title:** ppu_lifter: recover module TOC from OPD majority when .got section name is absent + +## Description + +## Problem + +In the ELF path, when the entry descriptor is detected as bogus (its toc +word repeats the code word), the TOCFIX fallback only tries +`.got + 0x8000`. Stripped homebrew ELFs — e.g. PSL1GHT `EBOOT.BIN` with an +emptied shstrtab, such as **TanakaDOOM-cGcm v0.3** — have no usable section +names at all, so the `.got` lookup finds nothing and the fallback silently +does nothing. The bogus entry toc word is then kept as THE module TOC, and +every `ld r2, N(r1)` TOC-restore lowering hardcodes that garbage constant +(`/*TOCFIX*/`). The guest reads its OPD-hook table through the wrong r2, +sees a null pointer, and spins forever in a `b .` loop. + +Concrete numbers for TanakaDOOM-cGcm v0.3: bogus toc `0x103F8`, true module +TOC `0xA3328`. RPCS3 runs the same ELF fine because crt0 establishes r2 +itself — the entry descriptor's toc word is never used at runtime, which is +why the broken translation only shows up in the static recompilation. + +## Fix + +When the entry descriptor is bogus **and** no `.got` section can be found, +scan the data segments for OPD descriptor pairs `{known-function-start, toc}` +and elect the most frequent toc (threshold: >= 8 votes). Restricting the +code half to detected function starts means incidental pointer data cannot +vote. + +Two details matter: + +- **OPD descriptors are 16 bytes in ELF64** (`{code64, toc64}`). Reading two + consecutive DWORDs pairs `code_lo` with `code_hi == 0`, and 0x0 then wins + the majority vote (TanakaDOOM: 1832 bogus votes for 0x0 vs 1817 real + descriptors). The first version of this patch did exactly that. +- The change lives entirely inside the existing `bogus entry + .got` branch; + ELFs with intact section names take the unchanged `.got+0x8000` route. + +## Validation + +Re-lifting TanakaDOOM-cGcm v0.3 now prints: + +``` +TOC: entry descriptor bogus, no .got; OPD-majority toc = 0xA3328 (1817 descriptors) +``` + +`0xA3328` matches the unanimous toc of all 1817 OPD descriptors and is +self-consistent with the .got tail. The rebuilt native executable passes +the full game init: its TTY log is line-for-line identical to the RPCS3 +reference (RPCS3 being the behavioral ground truth), reaching the title +screen and playing the title music — previously it hung silently before +guest main produced any output. + +Regression coverage for existing samples is expected from the lifter test +suite / CI full run. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-691/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-691/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c4bfbbf88d0996683261d5e5e2566d2d6dc38d9f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-691/tests/oracle.patch @@ -0,0 +1,52 @@ +diff --git a/tools/ppu_lifter.py b/tools/ppu_lifter.py +index a657ba61..464ff41b 100644 +--- a/tools/ppu_lifter.py ++++ b/tools/ppu_lifter.py +@@ -5340,6 +5340,47 @@ def main() -> None: + if got_addr: + toc = (got_addr + 0x8000) & 0xFFFFFFFF + print(f" TOC: entry descriptor bogus, using .got+0x8000 = 0x{toc:X}") ++ else: ++ # Stripped homebrew ELFs (e.g. PSL1GHT EBOOT.BIN with an ++ # emptied shstrtab) carry no usable section names, so the ++ # .got lookup finds nothing and the bogus entry toc-word ++ # (which repeats the code address) would be kept as THE ++ # module TOC -- every `ld r2, N(r1)` restore lowering then ++ # hardcodes that garbage and the guest spins in the first ++ # OPD-hook poll (TanakaDOOM: 0x103F8 vs true 0xA3328). ++ # Recover the TOC from the OPD instead: scan data segments ++ # for descriptor pairs {known-function-start, toc} and take ++ # the most frequent toc. The code half must be a detected ++ # function start, so incidental pointer data can't vote. ++ from collections import Counter ++ _starts = set(s for s, _ in func_bounds) ++ _toc_freq = Counter() ++ for v0, v1, d in seg_map: ++ if v0 <= text_lo < v1: ++ continue # skip the text segment itself ++ # OPD descriptors are 16 bytes in ELF64: ++ # {code(8), toc(8)}. Reading two consecutive ++ # DWORDs instead would pair code_lo with ++ # code_hi==0 and elect 0x0 as the "majority ++ # TOC" (TanakaDOOM: 1832 bogus votes). ++ _bo = 'big' if big_endian else 'little' ++ for off in range(0, len(d) - 16, 4): ++ c = int.from_bytes(d[off:off + 8], _bo) ++ t = int.from_bytes(d[off + 8:off + 16], _bo) ++ if c in _starts and (t & 3) == 0 and t != c: ++ _toc_freq[t] += 1 ++ if _toc_freq: ++ _t_best, _n_best = _toc_freq.most_common(1)[0] ++ if _n_best >= 8: ++ toc = _t_best ++ print(f" TOC: entry descriptor bogus, no .got; " ++ f"OPD-majority toc = 0x{toc:X} ({_n_best} descriptors)") ++ else: ++ print(f" TOC: entry descriptor bogus, no .got; " ++ f"OPD scan inconclusive (best 0x{_t_best:X} x{_n_best})") ++ else: ++ print(" TOC: entry descriptor bogus, no .got; " ++ "OPD scan found no descriptors") + # Multi-TOC executables (large Sony-toolchain builds like LBP carry + # two or more TOCs): harvest candidates by scanning the data + # segments for OPD descriptor pairs {code-in-text, toc} and keeping diff --git a/tasks/sp00nznet__ps3recomp-691/tests/test.sh b/tasks/sp00nznet__ps3recomp-691/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-691/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-691/tests/verifier.py b/tasks/sp00nznet__ps3recomp-691/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-691/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-692/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-692/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-692/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-692/instruction.md b/tasks/sp00nznet__ps3recomp-692/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..98326663b068f27423e8f01e1637e2c3c2875e3f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-692/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** cellGame: report 40 GiB - 256 KiB free above 4 GiB, so hddFreeSizeKB * 1024 cannot wrap + +## Description + +## Why + +Games turn `hddFreeSizeKB` into bytes with `hddFreeSizeKB * 1024` in 32 bits. With 4 GiB or more free, that wraps. What the game sees is the host's free space modulo 4 GiB, so depending on how full the disk happens to be the install check gets a few MB and fails with "not enough space". inFAMOUS 2 refused to boot this way with 41.7 GB free, and the same machine booted it after a few GB changed hands. + +RPCS3 avoids this by reporting `40 * 1024 * 1024 - 256` KB in every one of these calls (`cellGame.cpp`, see the comment in `cellHddGameCheck`). Times 1024 that is `0xFFFC0000`, still nearly 4 GiB after the wrap. + +## What + +`content_free_kb_reported()` sits between the measurement and the guest: +- below 4 GiB it reports the measured value, which cannot wrap, so a nearly full disk still reads as nearly full; +- at 4 GiB and above it reports RPCS3's 40 GiB - 256 KiB. + +It is used for `hddFreeSizeKB` in: +- `cellGameBootCheck`; +- `cellGameDataCheck`; +- the get block of the `cellGameDataCheckCreate(2)` status callback. + +**To turn it off:** `PS3_GAME_FREE_SPACE_RAW=1` reports the measured value always (capped at `INT32_MAX` KB, as before). + +## Tests + +`libs/system/tests/test_game_space.c`: +- The 12 GiB case now expects 40 GiB - 256 KiB, and checks that its 32-bit byte count is `0xFFFC0000`. +- New cases: + - 4 GiB - 4 KiB is reported as is; + - exactly 4 GiB is replaced (its byte count wraps to 0); + - `PS3_GAME_FREE_SPACE_RAW=1` gives the measured 12 GiB. +- The test no longer linked: `cellGame.c` now reads `ppu_vfs_root`, so it gets a stub. No workflow ran it, so `macos.yml` now runs it with the other self-contained sysutil tests (it needs `-Wl,-dead_strip`, like they do). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-692/solution/patch.diff b/tasks/sp00nznet__ps3recomp-692/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f3885bdc653fe53b174a3ce958c42db2ab6bc0b3 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-692/solution/patch.diff @@ -0,0 +1,109 @@ +diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml +index aeb9e948..d622fa90 100644 +--- a/.github/workflows/macos.yml ++++ b/.github/workflows/macos.yml +@@ -76,6 +76,8 @@ jobs: + /tmp/test_savedata_root + clang -std=gnu17 -I include libs/system/tests/test_sysconf.c libs/system/cellSysutil.c -Wl,-dead_strip -pthread -o /tmp/test_sysconf + /tmp/test_sysconf ++ clang -std=gnu17 -I include libs/system/tests/test_game_space.c -Wl,-dead_strip -o /tmp/test_game_space ++ /tmp/test_game_space + + - name: Run self-contained SPU helper tests + run: | +diff --git a/libs/system/cellGame.c b/libs/system/cellGame.c +index 5a1d37fa..a52b76ac 100644 +--- a/libs/system/cellGame.c ++++ b/libs/system/cellGame.c +@@ -184,6 +184,27 @@ static s32 content_free_kb(void) + return 0; + } + ++/* hddFreeSizeKB as the guest reads it. Games compute hddFreeSizeKB * 1024 ++ * in 32 bits to get bytes, so a real free space of 4 GiB or more wraps to ++ * whatever is left over modulo 4 GiB: depending on how full the host disk ++ * happens to be, the install check sees a few MB and fails with "not enough ++ * space" (inFAMOUS 2 did, at boot, with 41.7 GB free). RPCS3 reports 40 GiB ++ * - 256 KiB for every one of these calls for that reason (cellGame.cpp, ++ * cellHddGameCheck): times 1024 that is 0xFFFC0000, still nearly 4 GiB ++ * after the wrap. Here the measured value is kept below 4 GiB, where it ++ * cannot wrap and a nearly full disk still reads as one, and RPCS3's figure ++ * is reported above it. PS3_GAME_FREE_SPACE_RAW=1 reports the measured ++ * value (capped at INT32_MAX KB) always, as before. */ ++#define CELL_GAME_FREE_KB_WRAP (4 * 1024 * 1024) /* x1024 = 2^32 */ ++#define CELL_GAME_FREE_KB_REPORTED (40 * 1024 * 1024 - 256) /* RPCS3 */ ++static s32 content_free_kb_reported(void) ++{ ++ const s32 kb = content_free_kb(); ++ const char* raw = getenv("PS3_GAME_FREE_SPACE_RAW"); ++ if (raw && *raw && *raw != '0') return kb; ++ return kb >= CELL_GAME_FREE_KB_WRAP ? CELL_GAME_FREE_KB_REPORTED : kb; ++} ++ + /* --------------------------------------------------------------------------- + * Configuration + * -----------------------------------------------------------------------*/ +@@ -360,7 +381,7 @@ s32 cellGameBootCheck(u32* type, u32* attributes, CellGameContentSize* size, + if (attr_ea) vm_write32(attr_ea, 0); + + if (size_ea) { +- vm_write32(size_ea + 0, (u32)content_free_kb()); ++ vm_write32(size_ea + 0, (u32)content_free_kb_reported()); + vm_write32(size_ea + 4, (uint32_t)CELL_GAME_SIZEKB_NOTCALC); + vm_write32(size_ea + 8, 0); /* sysSizeKB */ + } +@@ -447,7 +468,7 @@ s32 cellGameDataCheck(u32 type, const char* dirName, CellGameContentSize* size) + + uint32_t size_ea = (uint32_t)(uintptr_t)size; + if (size_ea) { +- vm_write32(size_ea + 0, (u32)content_free_kb()); ++ vm_write32(size_ea + 0, (u32)content_free_kb_reported()); + vm_write32(size_ea + 4, (uint32_t)CELL_GAME_SIZEKB_NOTCALC); + vm_write32(size_ea + 8, 0); + } +@@ -512,7 +533,7 @@ static s32 gamedata_stat_callback(const char* tag, u32 version, uint32_t dir_ea, + memset(vm_base + cb, 0, (set + 0x20) - cb); + + /* CellGameDataStatGet (offsets per SDK, RPCS3-verified). */ +- vm_write32(get + 0x000, (u32)content_free_kb()); ++ vm_write32(get + 0x000, (u32)content_free_kb_reported()); + vm_write32(get + 0x004, is_new_data); /* isNewData = 0 (data exists) */ + snprintf((char*)(vm_base + get + 0x008), 96, "/dev_hdd0/game/%s", dir); /* contentInfoPath */ + snprintf((char*)(vm_base + get + 0x427), 96, "/dev_hdd0/game/%s/USRDIR", dir); /* gameDataPath */ +diff --git a/libs/system/tests/test_game_space.c b/libs/system/tests/test_game_space.c +index 97ac987d..138bc347 100644 +--- a/libs/system/tests/test_game_space.c ++++ b/libs/system/tests/test_game_space.c +@@ -33,6 +33,7 @@ void spu_lockline_lock(void) {} + void spu_lockline_unlock(void) {} + + ps3_guest_caller_fn g_ps3_guest_caller; ++const char* ppu_vfs_root = "."; + int main(void) + { + vm_base = calloc(1, 65536); assert(vm_base); +@@ -40,9 +41,22 @@ int main(void) + memcpy(vm_base + 0x100, "TEST00000", 10); + assert(cellGameDataCheck(3, (void*)0x100, (void*)0x200) == CELL_GAME_RET_NONE); + assert(queries == 4); +- assert(vm_read32(0x200) == 12u * 1024u * 1024u); ++ /* 12 GiB free: hddFreeSizeKB * 1024 would wrap in 32 bits, so the guest ++ * gets RPCS3's 40 GiB - 256 KiB, whose x1024 is 0xFFFC0000. */ ++ assert(content_free_kb() == 12 * 1024 * 1024); ++ assert(vm_read32(0x200) == 40u * 1024u * 1024u - 256u); ++ assert((uint32_t)(vm_read32(0x200) * 1024u) == 0xFFFC0000u); + assert(vm_read32(0x204) == 0 && vm_read32(0x208) == 0); +- assert(vm_base[0x200] == 0 && vm_base[0x201] == 0xC0); ++ assert(vm_base[0x200] == 0x02 && vm_base[0x201] == 0x7F); /* big-endian 0x027FFF00 */ ++ /* Below 4 GiB the real figure cannot wrap and is reported as is. */ ++ blocks = 1024 * 1024 - 1; /* 4 GiB - 4 KiB */ ++ assert(content_free_kb_reported() == 4 * 1024 * 1024 - 4); ++ blocks = 1024 * 1024; /* exactly 4 GiB: x1024 = 2^32 wraps to 0 */ ++ assert(content_free_kb_reported() == 40 * 1024 * 1024 - 256); ++ blocks = 3ULL * 1024 * 1024; ++ setenv("PS3_GAME_FREE_SPACE_RAW", "1", 1); /* the measured value, as before */ ++ assert(content_free_kb_reported() == 12 * 1024 * 1024); ++ unsetenv("PS3_GAME_FREE_SPACE_RAW"); + blocks = UINT64_MAX; + assert(content_free_kb() == INT32_MAX); + blocks = 0; assert(content_free_kb() == 0); diff --git a/tasks/sp00nznet__ps3recomp-692/solution/solve.sh b/tasks/sp00nznet__ps3recomp-692/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-692/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-692/task.toml b/tasks/sp00nznet__ps3recomp-692/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f32679f7511b682cd4a3ee03d8307e6e9818865c --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-692/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-692" +description = "cellGame: report 40 GiB - 256 KiB free above 4 GiB, so hddFreeSizeKB * 1024 cannot wrap" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/692" +source_access = "auto" +built_at = "2026-11-16T16:09:59.705606+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:db88591452c0264f66e0d959c22ee3a52e11ac2cd8fbb967497ebf80865954f1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:42Z" +diff_format = "unified" +context_files = [ + ".github/workflows/macos.yml", + "libs/system/cellGame.c", + "libs/system/tests/test_game_space.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 47 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.158610+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-692/tests/capture.py b/tasks/sp00nznet__ps3recomp-692/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-692/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-692/tests/instruction.md b/tasks/sp00nznet__ps3recomp-692/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..98326663b068f27423e8f01e1637e2c3c2875e3f --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-692/tests/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** cellGame: report 40 GiB - 256 KiB free above 4 GiB, so hddFreeSizeKB * 1024 cannot wrap + +## Description + +## Why + +Games turn `hddFreeSizeKB` into bytes with `hddFreeSizeKB * 1024` in 32 bits. With 4 GiB or more free, that wraps. What the game sees is the host's free space modulo 4 GiB, so depending on how full the disk happens to be the install check gets a few MB and fails with "not enough space". inFAMOUS 2 refused to boot this way with 41.7 GB free, and the same machine booted it after a few GB changed hands. + +RPCS3 avoids this by reporting `40 * 1024 * 1024 - 256` KB in every one of these calls (`cellGame.cpp`, see the comment in `cellHddGameCheck`). Times 1024 that is `0xFFFC0000`, still nearly 4 GiB after the wrap. + +## What + +`content_free_kb_reported()` sits between the measurement and the guest: +- below 4 GiB it reports the measured value, which cannot wrap, so a nearly full disk still reads as nearly full; +- at 4 GiB and above it reports RPCS3's 40 GiB - 256 KiB. + +It is used for `hddFreeSizeKB` in: +- `cellGameBootCheck`; +- `cellGameDataCheck`; +- the get block of the `cellGameDataCheckCreate(2)` status callback. + +**To turn it off:** `PS3_GAME_FREE_SPACE_RAW=1` reports the measured value always (capped at `INT32_MAX` KB, as before). + +## Tests + +`libs/system/tests/test_game_space.c`: +- The 12 GiB case now expects 40 GiB - 256 KiB, and checks that its 32-bit byte count is `0xFFFC0000`. +- New cases: + - 4 GiB - 4 KiB is reported as is; + - exactly 4 GiB is replaced (its byte count wraps to 0); + - `PS3_GAME_FREE_SPACE_RAW=1` gives the measured 12 GiB. +- The test no longer linked: `cellGame.c` now reads `ppu_vfs_root`, so it gets a stub. No workflow ran it, so `macos.yml` now runs it with the other self-contained sysutil tests (it needs `-Wl,-dead_strip`, like they do). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-692/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-692/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f3885bdc653fe53b174a3ce958c42db2ab6bc0b3 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-692/tests/oracle.patch @@ -0,0 +1,109 @@ +diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml +index aeb9e948..d622fa90 100644 +--- a/.github/workflows/macos.yml ++++ b/.github/workflows/macos.yml +@@ -76,6 +76,8 @@ jobs: + /tmp/test_savedata_root + clang -std=gnu17 -I include libs/system/tests/test_sysconf.c libs/system/cellSysutil.c -Wl,-dead_strip -pthread -o /tmp/test_sysconf + /tmp/test_sysconf ++ clang -std=gnu17 -I include libs/system/tests/test_game_space.c -Wl,-dead_strip -o /tmp/test_game_space ++ /tmp/test_game_space + + - name: Run self-contained SPU helper tests + run: | +diff --git a/libs/system/cellGame.c b/libs/system/cellGame.c +index 5a1d37fa..a52b76ac 100644 +--- a/libs/system/cellGame.c ++++ b/libs/system/cellGame.c +@@ -184,6 +184,27 @@ static s32 content_free_kb(void) + return 0; + } + ++/* hddFreeSizeKB as the guest reads it. Games compute hddFreeSizeKB * 1024 ++ * in 32 bits to get bytes, so a real free space of 4 GiB or more wraps to ++ * whatever is left over modulo 4 GiB: depending on how full the host disk ++ * happens to be, the install check sees a few MB and fails with "not enough ++ * space" (inFAMOUS 2 did, at boot, with 41.7 GB free). RPCS3 reports 40 GiB ++ * - 256 KiB for every one of these calls for that reason (cellGame.cpp, ++ * cellHddGameCheck): times 1024 that is 0xFFFC0000, still nearly 4 GiB ++ * after the wrap. Here the measured value is kept below 4 GiB, where it ++ * cannot wrap and a nearly full disk still reads as one, and RPCS3's figure ++ * is reported above it. PS3_GAME_FREE_SPACE_RAW=1 reports the measured ++ * value (capped at INT32_MAX KB) always, as before. */ ++#define CELL_GAME_FREE_KB_WRAP (4 * 1024 * 1024) /* x1024 = 2^32 */ ++#define CELL_GAME_FREE_KB_REPORTED (40 * 1024 * 1024 - 256) /* RPCS3 */ ++static s32 content_free_kb_reported(void) ++{ ++ const s32 kb = content_free_kb(); ++ const char* raw = getenv("PS3_GAME_FREE_SPACE_RAW"); ++ if (raw && *raw && *raw != '0') return kb; ++ return kb >= CELL_GAME_FREE_KB_WRAP ? CELL_GAME_FREE_KB_REPORTED : kb; ++} ++ + /* --------------------------------------------------------------------------- + * Configuration + * -----------------------------------------------------------------------*/ +@@ -360,7 +381,7 @@ s32 cellGameBootCheck(u32* type, u32* attributes, CellGameContentSize* size, + if (attr_ea) vm_write32(attr_ea, 0); + + if (size_ea) { +- vm_write32(size_ea + 0, (u32)content_free_kb()); ++ vm_write32(size_ea + 0, (u32)content_free_kb_reported()); + vm_write32(size_ea + 4, (uint32_t)CELL_GAME_SIZEKB_NOTCALC); + vm_write32(size_ea + 8, 0); /* sysSizeKB */ + } +@@ -447,7 +468,7 @@ s32 cellGameDataCheck(u32 type, const char* dirName, CellGameContentSize* size) + + uint32_t size_ea = (uint32_t)(uintptr_t)size; + if (size_ea) { +- vm_write32(size_ea + 0, (u32)content_free_kb()); ++ vm_write32(size_ea + 0, (u32)content_free_kb_reported()); + vm_write32(size_ea + 4, (uint32_t)CELL_GAME_SIZEKB_NOTCALC); + vm_write32(size_ea + 8, 0); + } +@@ -512,7 +533,7 @@ static s32 gamedata_stat_callback(const char* tag, u32 version, uint32_t dir_ea, + memset(vm_base + cb, 0, (set + 0x20) - cb); + + /* CellGameDataStatGet (offsets per SDK, RPCS3-verified). */ +- vm_write32(get + 0x000, (u32)content_free_kb()); ++ vm_write32(get + 0x000, (u32)content_free_kb_reported()); + vm_write32(get + 0x004, is_new_data); /* isNewData = 0 (data exists) */ + snprintf((char*)(vm_base + get + 0x008), 96, "/dev_hdd0/game/%s", dir); /* contentInfoPath */ + snprintf((char*)(vm_base + get + 0x427), 96, "/dev_hdd0/game/%s/USRDIR", dir); /* gameDataPath */ +diff --git a/libs/system/tests/test_game_space.c b/libs/system/tests/test_game_space.c +index 97ac987d..138bc347 100644 +--- a/libs/system/tests/test_game_space.c ++++ b/libs/system/tests/test_game_space.c +@@ -33,6 +33,7 @@ void spu_lockline_lock(void) {} + void spu_lockline_unlock(void) {} + + ps3_guest_caller_fn g_ps3_guest_caller; ++const char* ppu_vfs_root = "."; + int main(void) + { + vm_base = calloc(1, 65536); assert(vm_base); +@@ -40,9 +41,22 @@ int main(void) + memcpy(vm_base + 0x100, "TEST00000", 10); + assert(cellGameDataCheck(3, (void*)0x100, (void*)0x200) == CELL_GAME_RET_NONE); + assert(queries == 4); +- assert(vm_read32(0x200) == 12u * 1024u * 1024u); ++ /* 12 GiB free: hddFreeSizeKB * 1024 would wrap in 32 bits, so the guest ++ * gets RPCS3's 40 GiB - 256 KiB, whose x1024 is 0xFFFC0000. */ ++ assert(content_free_kb() == 12 * 1024 * 1024); ++ assert(vm_read32(0x200) == 40u * 1024u * 1024u - 256u); ++ assert((uint32_t)(vm_read32(0x200) * 1024u) == 0xFFFC0000u); + assert(vm_read32(0x204) == 0 && vm_read32(0x208) == 0); +- assert(vm_base[0x200] == 0 && vm_base[0x201] == 0xC0); ++ assert(vm_base[0x200] == 0x02 && vm_base[0x201] == 0x7F); /* big-endian 0x027FFF00 */ ++ /* Below 4 GiB the real figure cannot wrap and is reported as is. */ ++ blocks = 1024 * 1024 - 1; /* 4 GiB - 4 KiB */ ++ assert(content_free_kb_reported() == 4 * 1024 * 1024 - 4); ++ blocks = 1024 * 1024; /* exactly 4 GiB: x1024 = 2^32 wraps to 0 */ ++ assert(content_free_kb_reported() == 40 * 1024 * 1024 - 256); ++ blocks = 3ULL * 1024 * 1024; ++ setenv("PS3_GAME_FREE_SPACE_RAW", "1", 1); /* the measured value, as before */ ++ assert(content_free_kb_reported() == 12 * 1024 * 1024); ++ unsetenv("PS3_GAME_FREE_SPACE_RAW"); + blocks = UINT64_MAX; + assert(content_free_kb() == INT32_MAX); + blocks = 0; assert(content_free_kb() == 0); diff --git a/tasks/sp00nznet__ps3recomp-692/tests/test.sh b/tasks/sp00nznet__ps3recomp-692/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-692/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-692/tests/verifier.py b/tasks/sp00nznet__ps3recomp-692/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-692/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/sp00nznet__ps3recomp-695/environment/Dockerfile b/tasks/sp00nznet__ps3recomp-695/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc866db643a9697fb7cf191e6589714eada1944d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-695/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/sp00nznet/ps3recomp.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/sp00nznet/ps3recomp.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/sp00nznet/ps3recomp.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/sp00nznet__ps3recomp-695/instruction.md b/tasks/sp00nznet__ps3recomp-695/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d6f4228c39f27882ca635f6c5e3d6fc5af3e381e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-695/instruction.md @@ -0,0 +1,57 @@ +# Issue + +**Title:** D3D12: present the CPU-blit scanout when a frame has zero RSX commands + +## Description + +## Problem + +Some games render entirely on the PPU and only memcpy finished frames into +the GCM VRAM mapping, never emitting any RSX commands. One example is +TanakaDOOM-cGcm v0.3, a Chocolate Doom port whose software renderer writes +directly to the display buffers. + +On such games the D3D12 backend shows a black window: game logic, audio and +flip tracking all run correctly (the title music plays, the demo loop +advances), but because no draw records are ever recorded, the backend keeps +presenting its "never rendered" surface. + +## Fix + +- `libs/video/cellGcmSys.c`: add `cellGcm_current_scanout()`, exposing the + current display buffer offset/pitch/size from the module's own + `s_display_buffers` table. cellGcmSys is the authoritative source here — + in this mode the draw engine may never have been started, so its tables + can be empty. +- `libs/video/rsx_d3d12_backend.c`: add `scanout_auto_present()`, called from + `render_frame()` right after `guest_fb_present()`. It fires only when the + frame had zero draw records, reads the current scanout via + `cellGcm_current_scanout()`, and blits the guest buffer from + `vm_base + 0xC0000000 + offset` into the backbuffer with A,R,G,B -> + R,G,B,A byte-order swap (guest pixels are big-endian 32-bit) and alpha + forced to 0xFF. + +No behaviour change for games that do emit RSX commands: the fallback is +skipped whenever `s_dbg_last_draws != 0`, and skipped entirely when the +`GCM_GUEST_FB` debug override is in use. + +## Env knobs + +- `SCANOUT_FB=0` — disable the fallback +- `SCANOUT_FB_DBG=1` — log got offset/pitch each present + +## Verification + +Recompiled [TanakaDOOM-cGcm v0.3](https://github.com/kan8223-dotcom) with the +patched lifter: TTY output matches RPCS3 line for line, and the D3D12 window +now renders the title screen, menus and E1M1 gameplay with correct colours. + +## Scope + +This covers fully CPU-rendered (zero-RSX-command) frames only. Games that mix +CPU blits with RSX-drawn overlays are untested; the fallback would leave the +RSX layer unpresented on frames where it matters. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-695/solution/patch.diff b/tasks/sp00nznet__ps3recomp-695/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..406c14774aec4c80ddd9100c7ee13b730b2d4668 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-695/solution/patch.diff @@ -0,0 +1,165 @@ +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..ce7b53ab 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -3033,6 +3033,23 @@ int cellGcmOffsetIsDisplay(u32 offset) + return 0; + } + ++/* Backend query (not a guest API): the display buffer the current flip names, ++ * as offset/pitch/size in RSX local memory. Backs the CPU-blit scanout ++ * fallback -- a software-rendered title writes its display buffer straight ++ * into guest VRAM and never records RSX work, so the D3D12 backend presents ++ * the guest bytes directly. Returns 1 when a buffer is registered. */ ++int cellGcm_current_scanout(u32* offset, u32* pitch, u32* width, u32* height) ++{ ++ const u32 id = s_current_display_buffer_id & 7u; ++ if (!s_display_buffer_set[id]) ++ return 0; ++ if (offset) *offset = s_display_buffers[id].offset; ++ if (pitch) *pitch = s_display_buffers[id].pitch; ++ if (width) *width = s_display_buffers[id].width; ++ if (height) *height = s_display_buffers[id].height; ++ return 1; ++} ++ + /* NID: 0xEAA52F23 */ + /* How many display buffers the title has actually registered. cellResc needs + * it to know how far to rotate its flip target; nothing else about the set is +diff --git a/libs/video/rsx_d3d12_backend.c b/libs/video/rsx_d3d12_backend.c +index bc05a308..ecbe21bd 100644 +--- a/libs/video/rsx_d3d12_backend.c ++++ b/libs/video/rsx_d3d12_backend.c +@@ -297,6 +297,8 @@ typedef struct { + HANDLE fence_event; + u64 fence_values[FRAME_COUNT]; + u32 frame_index; ++ u32 present_buffer_id; /* buffer the current flip names (for ++ * the CPU-blit scanout fallback) */ + + /* Pipeline */ + ID3D12RootSignature* root_signature; +@@ -4417,6 +4419,106 @@ static void guest_fb_present(u32 fi) + s_d3d.cmd_list->lpVtbl->ResourceBarrier(s_d3d.cmd_list, 1, &gb); + } + ++/* SCANOUT_FB=0 disables. Automatic CPU-blit scanout fallback: when the frame ++ * recorded no RSX work at all (s_dbg_last_draws == 0) but the flip names a ++ * registered VRAM display buffer, the title renders on the CPU and writes its ++ * display buffer straight into guest VRAM (TanakaDOOM-cGcm: software 320x200 ++ * renderer, zero RSX commands, ever). The normal path presents a never-rendered ++ * surface = black. Copy the guest bytes to the backbuffer instead, ++ * A,R,G,B -> R,G,B,A (the guest is big-endian; its 32-bit pixels land as ++ * A,R,G,B bytes -- verified against RPCS3 on TanakaDOOM: byte-as-is reads ++ * alpha as red, R/B swap reads blue as red). Skipped when ++ * GCM_GUEST_FB is set (that debug path pins its own fixed offset). */ ++static void scanout_auto_present(u32 fi) ++{ ++ static int on = -1; ++ if (on < 0) { ++ const char* e = getenv("SCANOUT_FB"); ++ on = !(e && e[0] == '0') && !getenv("GCM_GUEST_FB"); ++ } ++ if (!on || s_dbg_last_draws != 0) return; ++ /* The display-buffer registry that matters is cellGcmSys's own: the ++ * ticker-driven backend path never brings the draw engine up, so the ++ * engine's table stays empty. cellGcm tracks the buffer the current flip ++ * names (updated on every SetFlip path). */ ++ extern int cellGcm_current_scanout(u32*, u32*, u32*, u32*); ++ u32 off = 0, gpitch = 0, gw = 0, gh = 0; ++ const int got = cellGcm_current_scanout(&off, &gpitch, &gw, &gh); ++ { static int dbg = -1; ++ if (dbg < 0) dbg = getenv("SCANOUT_FB_DBG") ? 1 : 0; ++ if (dbg) { static int n = 0; ++ if (n < 12) { n++; ++ fprintf(stderr, "[scanout-fb] last_draws=%u got=%d " ++ "off=0x%X pitch=%u %ux%u\n", ++ s_dbg_last_draws, got, off, gpitch, gw, gh); } } } ++ if (!got || !gpitch || !gw || !gh) ++ return; ++ extern u8* vm_base; ++ if (!vm_base) return; ++ const u32 up_pitch = (gw * 4u + 255u) & ~255u; /* 256-byte rows */ ++ static ID3D12Resource* up = NULL; ++ static u32 up_w = 0, up_h = 0; ++ if (!up || up_w != gw || up_h != gh) { ++ if (up) { up->lpVtbl->Release(up); up = NULL; } ++ D3D12_HEAP_PROPERTIES hp = {0}; hp.Type = D3D12_HEAP_TYPE_UPLOAD; ++ D3D12_RESOURCE_DESC bd = {0}; ++ bd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; ++ bd.Width = (u64)up_pitch * gh; bd.Height = 1; ++ bd.DepthOrArraySize = 1; bd.MipLevels = 1; ++ bd.Format = DXGI_FORMAT_UNKNOWN; bd.SampleDesc.Count = 1; ++ bd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; ++ if (FAILED(s_d3d.device->lpVtbl->CreateCommittedResource( ++ s_d3d.device, &hp, D3D12_HEAP_FLAG_NONE, &bd, ++ D3D12_RESOURCE_STATE_GENERIC_READ, NULL, ++ &IID_ID3D12Resource, (void**)&up))) ++ return; ++ up_w = gw; up_h = gh; ++ } ++ /* RSX local memory is mapped at guest 0xC0000000. The guest is a ++ * big-endian PPC title: its 32-bit pixels land as A,R,G,B bytes, so ++ * route R,G,B to the backbuffer and force alpha (verified against ++ * RPCS3: byte-as-is copy reads alpha as red; a R/B swap reads blue ++ * as red -- TanakaDOOM title screen). */ ++ { const u8* srow = vm_base + 0xC0000000u + off; ++ void* m = NULL; D3D12_RANGE nr = {0, 0}; ++ if (FAILED(up->lpVtbl->Map(up, 0, &nr, &m)) || !m) return; ++ for (u32 y = 0; y < gh; y++) { ++ const u8* s = srow + (size_t)y * gpitch; ++ u8* dp = (u8*)m + (size_t)y * up_pitch; ++ for (u32 x = 0; x < gw; x++) { ++ dp[x*4+0] = s[x*4+1]; ++ dp[x*4+1] = s[x*4+2]; ++ dp[x*4+2] = s[x*4+3]; ++ dp[x*4+3] = 0xFF; ++ } ++ } ++ D3D12_RANGE wr = {0, (SIZE_T)up_pitch * gh}; ++ up->lpVtbl->Unmap(up, 0, &wr); } ++ ++ D3D12_RESOURCE_BARRIER gb = {0}; ++ gb.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; ++ gb.Transition.pResource = s_d3d.render_targets[fi]; ++ gb.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; ++ gb.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; ++ gb.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; ++ s_d3d.cmd_list->lpVtbl->ResourceBarrier(s_d3d.cmd_list, 1, &gb); ++ ++ D3D12_TEXTURE_COPY_LOCATION dl = {0}, sl = {0}; ++ dl.pResource = s_d3d.render_targets[fi]; ++ dl.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; dl.SubresourceIndex = 0; ++ sl.pResource = up; sl.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; ++ sl.PlacedFootprint.Offset = 0; ++ sl.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; ++ sl.PlacedFootprint.Footprint.Width = gw; ++ sl.PlacedFootprint.Footprint.Height = gh; ++ sl.PlacedFootprint.Footprint.Depth = 1; ++ sl.PlacedFootprint.Footprint.RowPitch = up_pitch; ++ s_d3d.cmd_list->lpVtbl->CopyTextureRegion(s_d3d.cmd_list, &dl, 0, 0, 0, &sl, NULL); ++ ++ gb.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; ++ gb.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; ++ s_d3d.cmd_list->lpVtbl->ResourceBarrier(s_d3d.cmd_list, 1, &gb); ++} + + static void render_frame(void) + { +@@ -5634,6 +5736,7 @@ static void render_frame(void) + if (s_d3d.dump_skip_left > 0 && s_d3d.dump_frames_left > 0) s_d3d.dump_skip_left--; + skip_dump_consider: ; + guest_fb_present(fi); ++ scanout_auto_present(fi); + composite_present(fi); + int dumping = (s_d3d.dump_frames_left > 0 && s_d3d.readback_buf + && s_d3d.dump_skip_left == 0); +@@ -5923,7 +6026,7 @@ static int blink_dbg(void) + static void d3d12_present(void* ud, u32 buffer_id) + { + (void)ud; +- (void)buffer_id; ++ s_d3d.present_buffer_id = buffer_id & 7u; + + if (blink_dbg()) + printf("[PRESENT] draws=%u clears_since_last=%u\n", diff --git a/tasks/sp00nznet__ps3recomp-695/solution/solve.sh b/tasks/sp00nznet__ps3recomp-695/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-695/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/sp00nznet__ps3recomp-695/task.toml b/tasks/sp00nznet__ps3recomp-695/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7b06283ef8e4c435ba2c2b85e189862b444bfad6 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-695/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/sp00nznet__ps3recomp-695" +description = "D3D12: present the CPU-blit scanout when a frame has zero RSX commands" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ps3recomp", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "sp00nznet/ps3recomp" +ref = "4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514" +reference = "https://github.com/sp00nznet/ps3recomp/pull/695" +source_access = "auto" +built_at = "2026-11-16T16:09:59.703657+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8300abb13033692c5f23108e51e222659b48f7aff4debc0d14d534ba34267017" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T09:35:41Z" +diff_format = "unified" +context_files = [ + "libs/video/cellGcmSys.c", + "libs/video/rsx_d3d12_backend.c", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 122 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.159178+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:38e693e623d3cac3b99e2aab47c2a3f0d92a00cd18c78a40087a3c9d3f3bc160" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/sp00nznet__ps3recomp-695/tests/capture.py b/tasks/sp00nznet__ps3recomp-695/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-695/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sp00nznet__ps3recomp-695/tests/instruction.md b/tasks/sp00nznet__ps3recomp-695/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d6f4228c39f27882ca635f6c5e3d6fc5af3e381e --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-695/tests/instruction.md @@ -0,0 +1,57 @@ +# Issue + +**Title:** D3D12: present the CPU-blit scanout when a frame has zero RSX commands + +## Description + +## Problem + +Some games render entirely on the PPU and only memcpy finished frames into +the GCM VRAM mapping, never emitting any RSX commands. One example is +TanakaDOOM-cGcm v0.3, a Chocolate Doom port whose software renderer writes +directly to the display buffers. + +On such games the D3D12 backend shows a black window: game logic, audio and +flip tracking all run correctly (the title music plays, the demo loop +advances), but because no draw records are ever recorded, the backend keeps +presenting its "never rendered" surface. + +## Fix + +- `libs/video/cellGcmSys.c`: add `cellGcm_current_scanout()`, exposing the + current display buffer offset/pitch/size from the module's own + `s_display_buffers` table. cellGcmSys is the authoritative source here — + in this mode the draw engine may never have been started, so its tables + can be empty. +- `libs/video/rsx_d3d12_backend.c`: add `scanout_auto_present()`, called from + `render_frame()` right after `guest_fb_present()`. It fires only when the + frame had zero draw records, reads the current scanout via + `cellGcm_current_scanout()`, and blits the guest buffer from + `vm_base + 0xC0000000 + offset` into the backbuffer with A,R,G,B -> + R,G,B,A byte-order swap (guest pixels are big-endian 32-bit) and alpha + forced to 0xFF. + +No behaviour change for games that do emit RSX commands: the fallback is +skipped whenever `s_dbg_last_draws != 0`, and skipped entirely when the +`GCM_GUEST_FB` debug override is in use. + +## Env knobs + +- `SCANOUT_FB=0` — disable the fallback +- `SCANOUT_FB_DBG=1` — log got offset/pitch each present + +## Verification + +Recompiled [TanakaDOOM-cGcm v0.3](https://github.com/kan8223-dotcom) with the +patched lifter: TTY output matches RPCS3 line for line, and the D3D12 window +now renders the title screen, menus and E1M1 gameplay with correct colours. + +## Scope + +This covers fully CPU-rendered (zero-RSX-command) frames only. Games that mix +CPU blits with RSX-drawn overlays are untested; the fallback would leave the +RSX layer unpresented on frames where it matters. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4e8f3ca87a3e`. 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. \ No newline at end of file diff --git a/tasks/sp00nznet__ps3recomp-695/tests/oracle.patch b/tasks/sp00nznet__ps3recomp-695/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..406c14774aec4c80ddd9100c7ee13b730b2d4668 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-695/tests/oracle.patch @@ -0,0 +1,165 @@ +diff --git a/libs/video/cellGcmSys.c b/libs/video/cellGcmSys.c +index 298ee7de..ce7b53ab 100644 +--- a/libs/video/cellGcmSys.c ++++ b/libs/video/cellGcmSys.c +@@ -3033,6 +3033,23 @@ int cellGcmOffsetIsDisplay(u32 offset) + return 0; + } + ++/* Backend query (not a guest API): the display buffer the current flip names, ++ * as offset/pitch/size in RSX local memory. Backs the CPU-blit scanout ++ * fallback -- a software-rendered title writes its display buffer straight ++ * into guest VRAM and never records RSX work, so the D3D12 backend presents ++ * the guest bytes directly. Returns 1 when a buffer is registered. */ ++int cellGcm_current_scanout(u32* offset, u32* pitch, u32* width, u32* height) ++{ ++ const u32 id = s_current_display_buffer_id & 7u; ++ if (!s_display_buffer_set[id]) ++ return 0; ++ if (offset) *offset = s_display_buffers[id].offset; ++ if (pitch) *pitch = s_display_buffers[id].pitch; ++ if (width) *width = s_display_buffers[id].width; ++ if (height) *height = s_display_buffers[id].height; ++ return 1; ++} ++ + /* NID: 0xEAA52F23 */ + /* How many display buffers the title has actually registered. cellResc needs + * it to know how far to rotate its flip target; nothing else about the set is +diff --git a/libs/video/rsx_d3d12_backend.c b/libs/video/rsx_d3d12_backend.c +index bc05a308..ecbe21bd 100644 +--- a/libs/video/rsx_d3d12_backend.c ++++ b/libs/video/rsx_d3d12_backend.c +@@ -297,6 +297,8 @@ typedef struct { + HANDLE fence_event; + u64 fence_values[FRAME_COUNT]; + u32 frame_index; ++ u32 present_buffer_id; /* buffer the current flip names (for ++ * the CPU-blit scanout fallback) */ + + /* Pipeline */ + ID3D12RootSignature* root_signature; +@@ -4417,6 +4419,106 @@ static void guest_fb_present(u32 fi) + s_d3d.cmd_list->lpVtbl->ResourceBarrier(s_d3d.cmd_list, 1, &gb); + } + ++/* SCANOUT_FB=0 disables. Automatic CPU-blit scanout fallback: when the frame ++ * recorded no RSX work at all (s_dbg_last_draws == 0) but the flip names a ++ * registered VRAM display buffer, the title renders on the CPU and writes its ++ * display buffer straight into guest VRAM (TanakaDOOM-cGcm: software 320x200 ++ * renderer, zero RSX commands, ever). The normal path presents a never-rendered ++ * surface = black. Copy the guest bytes to the backbuffer instead, ++ * A,R,G,B -> R,G,B,A (the guest is big-endian; its 32-bit pixels land as ++ * A,R,G,B bytes -- verified against RPCS3 on TanakaDOOM: byte-as-is reads ++ * alpha as red, R/B swap reads blue as red). Skipped when ++ * GCM_GUEST_FB is set (that debug path pins its own fixed offset). */ ++static void scanout_auto_present(u32 fi) ++{ ++ static int on = -1; ++ if (on < 0) { ++ const char* e = getenv("SCANOUT_FB"); ++ on = !(e && e[0] == '0') && !getenv("GCM_GUEST_FB"); ++ } ++ if (!on || s_dbg_last_draws != 0) return; ++ /* The display-buffer registry that matters is cellGcmSys's own: the ++ * ticker-driven backend path never brings the draw engine up, so the ++ * engine's table stays empty. cellGcm tracks the buffer the current flip ++ * names (updated on every SetFlip path). */ ++ extern int cellGcm_current_scanout(u32*, u32*, u32*, u32*); ++ u32 off = 0, gpitch = 0, gw = 0, gh = 0; ++ const int got = cellGcm_current_scanout(&off, &gpitch, &gw, &gh); ++ { static int dbg = -1; ++ if (dbg < 0) dbg = getenv("SCANOUT_FB_DBG") ? 1 : 0; ++ if (dbg) { static int n = 0; ++ if (n < 12) { n++; ++ fprintf(stderr, "[scanout-fb] last_draws=%u got=%d " ++ "off=0x%X pitch=%u %ux%u\n", ++ s_dbg_last_draws, got, off, gpitch, gw, gh); } } } ++ if (!got || !gpitch || !gw || !gh) ++ return; ++ extern u8* vm_base; ++ if (!vm_base) return; ++ const u32 up_pitch = (gw * 4u + 255u) & ~255u; /* 256-byte rows */ ++ static ID3D12Resource* up = NULL; ++ static u32 up_w = 0, up_h = 0; ++ if (!up || up_w != gw || up_h != gh) { ++ if (up) { up->lpVtbl->Release(up); up = NULL; } ++ D3D12_HEAP_PROPERTIES hp = {0}; hp.Type = D3D12_HEAP_TYPE_UPLOAD; ++ D3D12_RESOURCE_DESC bd = {0}; ++ bd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; ++ bd.Width = (u64)up_pitch * gh; bd.Height = 1; ++ bd.DepthOrArraySize = 1; bd.MipLevels = 1; ++ bd.Format = DXGI_FORMAT_UNKNOWN; bd.SampleDesc.Count = 1; ++ bd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; ++ if (FAILED(s_d3d.device->lpVtbl->CreateCommittedResource( ++ s_d3d.device, &hp, D3D12_HEAP_FLAG_NONE, &bd, ++ D3D12_RESOURCE_STATE_GENERIC_READ, NULL, ++ &IID_ID3D12Resource, (void**)&up))) ++ return; ++ up_w = gw; up_h = gh; ++ } ++ /* RSX local memory is mapped at guest 0xC0000000. The guest is a ++ * big-endian PPC title: its 32-bit pixels land as A,R,G,B bytes, so ++ * route R,G,B to the backbuffer and force alpha (verified against ++ * RPCS3: byte-as-is copy reads alpha as red; a R/B swap reads blue ++ * as red -- TanakaDOOM title screen). */ ++ { const u8* srow = vm_base + 0xC0000000u + off; ++ void* m = NULL; D3D12_RANGE nr = {0, 0}; ++ if (FAILED(up->lpVtbl->Map(up, 0, &nr, &m)) || !m) return; ++ for (u32 y = 0; y < gh; y++) { ++ const u8* s = srow + (size_t)y * gpitch; ++ u8* dp = (u8*)m + (size_t)y * up_pitch; ++ for (u32 x = 0; x < gw; x++) { ++ dp[x*4+0] = s[x*4+1]; ++ dp[x*4+1] = s[x*4+2]; ++ dp[x*4+2] = s[x*4+3]; ++ dp[x*4+3] = 0xFF; ++ } ++ } ++ D3D12_RANGE wr = {0, (SIZE_T)up_pitch * gh}; ++ up->lpVtbl->Unmap(up, 0, &wr); } ++ ++ D3D12_RESOURCE_BARRIER gb = {0}; ++ gb.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; ++ gb.Transition.pResource = s_d3d.render_targets[fi]; ++ gb.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; ++ gb.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET; ++ gb.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; ++ s_d3d.cmd_list->lpVtbl->ResourceBarrier(s_d3d.cmd_list, 1, &gb); ++ ++ D3D12_TEXTURE_COPY_LOCATION dl = {0}, sl = {0}; ++ dl.pResource = s_d3d.render_targets[fi]; ++ dl.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; dl.SubresourceIndex = 0; ++ sl.pResource = up; sl.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; ++ sl.PlacedFootprint.Offset = 0; ++ sl.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM; ++ sl.PlacedFootprint.Footprint.Width = gw; ++ sl.PlacedFootprint.Footprint.Height = gh; ++ sl.PlacedFootprint.Footprint.Depth = 1; ++ sl.PlacedFootprint.Footprint.RowPitch = up_pitch; ++ s_d3d.cmd_list->lpVtbl->CopyTextureRegion(s_d3d.cmd_list, &dl, 0, 0, 0, &sl, NULL); ++ ++ gb.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; ++ gb.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET; ++ s_d3d.cmd_list->lpVtbl->ResourceBarrier(s_d3d.cmd_list, 1, &gb); ++} + + static void render_frame(void) + { +@@ -5634,6 +5736,7 @@ static void render_frame(void) + if (s_d3d.dump_skip_left > 0 && s_d3d.dump_frames_left > 0) s_d3d.dump_skip_left--; + skip_dump_consider: ; + guest_fb_present(fi); ++ scanout_auto_present(fi); + composite_present(fi); + int dumping = (s_d3d.dump_frames_left > 0 && s_d3d.readback_buf + && s_d3d.dump_skip_left == 0); +@@ -5923,7 +6026,7 @@ static int blink_dbg(void) + static void d3d12_present(void* ud, u32 buffer_id) + { + (void)ud; +- (void)buffer_id; ++ s_d3d.present_buffer_id = buffer_id & 7u; + + if (blink_dbg()) + printf("[PRESENT] draws=%u clears_since_last=%u\n", diff --git a/tasks/sp00nznet__ps3recomp-695/tests/test.sh b/tasks/sp00nznet__ps3recomp-695/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b46559e24bf678a347f7cb070fa9000473c51ab8 --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-695/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4e8f3ca87a3e1d87bb83b8b7e9348fe2685cd514 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/sp00nznet__ps3recomp-695/tests/verifier.py b/tasks/sp00nznet__ps3recomp-695/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/sp00nznet__ps3recomp-695/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-50256/environment/Dockerfile b/tasks/spring-projects__spring-boot-50256/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bad40d8c0b8e4e16463a09dd0cb0b5e48ceb690f --- /dev/null +++ b/tasks/spring-projects__spring-boot-50256/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4307353d6abbd1ffceec0433245b927af7cb2d83 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4307353d6abbd1ffceec0433245b927af7cb2d83 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4307353d6abbd1ffceec0433245b927af7cb2d83 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-50256/instruction.md b/tasks/spring-projects__spring-boot-50256/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6444a6affc0dd147f611c21bb185faf4fe220a7c --- /dev/null +++ b/tasks/spring-projects__spring-boot-50256/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Include security error body in WebFlux Cloud Foundry endpoint responses + +## Description + +## Problem + +When a Cloud Foundry security check fails in a WebFlux application, +`SecureReactiveWebOperation` and `CloudFoundryLinksHandler` return only +the HTTP status code with no response body. The servlet counterpart +includes a `{"security_error":"<reason>"}` body, so the reactive path +silently discards the diagnostic information that `SecurityInterceptor` +already computes. + +## Change + +Updated `CloudFoundryWebFluxEndpointHandlerMapping` to include +`securityResponse.getMessage()` as the response body in both +`CloudFoundryLinksHandler.links()` and +`SecureReactiveWebOperation.flatMapResponse()`, consistent with the +servlet implementation. + +## Tests + +Updated `operationWithSecurityInterceptorForbidden` and +`linksToOtherEndpointsForbidden` in +`CloudFoundryWebFluxEndpointIntegrationTests` to assert that the +security error body is present in the response. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4307353d6abb`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-50256/solution/patch.diff b/tasks/spring-projects__spring-boot-50256/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4e8363480f45c65b7b49847f323297b8e7d9afb1 --- /dev/null +++ b/tasks/spring-projects__spring-boot-50256/solution/patch.diff @@ -0,0 +1,48 @@ +diff --git a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java +index 2c269ca3207..748c59deb5d 100644 +--- a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java ++++ b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java +@@ -109,7 +109,7 @@ class CloudFoundryWebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointH + return CloudFoundryWebFluxEndpointHandlerMapping.this.securityInterceptor.preHandle(exchange, "") + .map((securityResponse) -> { + if (!securityResponse.getStatus().equals(HttpStatus.OK)) { +- return new ResponseEntity<>(securityResponse.getStatus()); ++ return new ResponseEntity<>(securityResponse.getMessage(), securityResponse.getStatus()); + } + AccessLevel accessLevel = exchange.getAttribute(AccessLevel.REQUEST_ATTRIBUTE); + String requestUri = UriComponentsBuilder.fromUri(request.getURI()).replaceQuery(null).toUriString(); +@@ -164,7 +164,7 @@ class CloudFoundryWebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointH + private Mono<ResponseEntity<Object>> flatMapResponse(ServerWebExchange exchange, + @Nullable Map<String, String> body, SecurityResponse securityResponse) { + if (!securityResponse.getStatus().equals(HttpStatus.OK)) { +- return Mono.just(new ResponseEntity<>(securityResponse.getStatus())); ++ return Mono.just(new ResponseEntity<>(securityResponse.getMessage(), securityResponse.getStatus())); + } + return this.delegate.handle(exchange, body); + } +diff --git a/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java b/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java +index b8798915a92..d15c60940ed 100644 +--- a/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java ++++ b/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java +@@ -100,7 +100,9 @@ class CloudFoundryWebFluxEndpointIntegrationTests { + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() +- .isEqualTo(HttpStatus.FORBIDDEN))); ++ .isEqualTo(HttpStatus.FORBIDDEN) ++ .expectBody(String.class) ++ .isEqualTo("{\"security_error\":\"Access denied\"}"))); + } + + @Test +@@ -179,7 +181,9 @@ class CloudFoundryWebFluxEndpointIntegrationTests { + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() +- .isUnauthorized())); ++ .isUnauthorized() ++ .expectBody(String.class) ++ .isEqualTo("{\"security_error\":\"invalid-token\"}"))); + } + + @Test diff --git a/tasks/spring-projects__spring-boot-50256/solution/solve.sh b/tasks/spring-projects__spring-boot-50256/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-50256/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-50256/task.toml b/tasks/spring-projects__spring-boot-50256/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3e025cf0de0bec0a767efbde25d73c5377986e42 --- /dev/null +++ b/tasks/spring-projects__spring-boot-50256/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-50256" +description = "Include security error body in WebFlux Cloud Foundry endpoint responses" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "4307353d6abbd1ffceec0433245b927af7cb2d83" +reference = "https://github.com/spring-projects/spring-boot/pull/50256" +source_access = "auto" +built_at = "2026-11-16T16:09:44.761210+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:82642818843075186ea228ba4b7ae9011b014fe8715d0b56c5283728c9857b95" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-09T12:53:02Z" +diff_format = "unified" +context_files = [ + "module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java", + "module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.159738+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:20ee173229341842f18b2b583cdfa281d61fbc46df1e37c8313969e182082e31" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-50256/tests/capture.py b/tasks/spring-projects__spring-boot-50256/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-50256/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-50256/tests/instruction.md b/tasks/spring-projects__spring-boot-50256/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6444a6affc0dd147f611c21bb185faf4fe220a7c --- /dev/null +++ b/tasks/spring-projects__spring-boot-50256/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** Include security error body in WebFlux Cloud Foundry endpoint responses + +## Description + +## Problem + +When a Cloud Foundry security check fails in a WebFlux application, +`SecureReactiveWebOperation` and `CloudFoundryLinksHandler` return only +the HTTP status code with no response body. The servlet counterpart +includes a `{"security_error":"<reason>"}` body, so the reactive path +silently discards the diagnostic information that `SecurityInterceptor` +already computes. + +## Change + +Updated `CloudFoundryWebFluxEndpointHandlerMapping` to include +`securityResponse.getMessage()` as the response body in both +`CloudFoundryLinksHandler.links()` and +`SecureReactiveWebOperation.flatMapResponse()`, consistent with the +servlet implementation. + +## Tests + +Updated `operationWithSecurityInterceptorForbidden` and +`linksToOtherEndpointsForbidden` in +`CloudFoundryWebFluxEndpointIntegrationTests` to assert that the +security error body is present in the response. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4307353d6abb`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-50256/tests/oracle.patch b/tasks/spring-projects__spring-boot-50256/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4e8363480f45c65b7b49847f323297b8e7d9afb1 --- /dev/null +++ b/tasks/spring-projects__spring-boot-50256/tests/oracle.patch @@ -0,0 +1,48 @@ +diff --git a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java +index 2c269ca3207..748c59deb5d 100644 +--- a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java ++++ b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointHandlerMapping.java +@@ -109,7 +109,7 @@ class CloudFoundryWebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointH + return CloudFoundryWebFluxEndpointHandlerMapping.this.securityInterceptor.preHandle(exchange, "") + .map((securityResponse) -> { + if (!securityResponse.getStatus().equals(HttpStatus.OK)) { +- return new ResponseEntity<>(securityResponse.getStatus()); ++ return new ResponseEntity<>(securityResponse.getMessage(), securityResponse.getStatus()); + } + AccessLevel accessLevel = exchange.getAttribute(AccessLevel.REQUEST_ATTRIBUTE); + String requestUri = UriComponentsBuilder.fromUri(request.getURI()).replaceQuery(null).toUriString(); +@@ -164,7 +164,7 @@ class CloudFoundryWebFluxEndpointHandlerMapping extends AbstractWebFluxEndpointH + private Mono<ResponseEntity<Object>> flatMapResponse(ServerWebExchange exchange, + @Nullable Map<String, String> body, SecurityResponse securityResponse) { + if (!securityResponse.getStatus().equals(HttpStatus.OK)) { +- return Mono.just(new ResponseEntity<>(securityResponse.getStatus())); ++ return Mono.just(new ResponseEntity<>(securityResponse.getMessage(), securityResponse.getStatus())); + } + return this.delegate.handle(exchange, body); + } +diff --git a/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java b/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java +index b8798915a92..d15c60940ed 100644 +--- a/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java ++++ b/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryWebFluxEndpointIntegrationTests.java +@@ -100,7 +100,9 @@ class CloudFoundryWebFluxEndpointIntegrationTests { + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() +- .isEqualTo(HttpStatus.FORBIDDEN))); ++ .isEqualTo(HttpStatus.FORBIDDEN) ++ .expectBody(String.class) ++ .isEqualTo("{\"security_error\":\"Access denied\"}"))); + } + + @Test +@@ -179,7 +181,9 @@ class CloudFoundryWebFluxEndpointIntegrationTests { + .header("Authorization", "bearer " + mockAccessToken()) + .exchange() + .expectStatus() +- .isUnauthorized())); ++ .isUnauthorized() ++ .expectBody(String.class) ++ .isEqualTo("{\"security_error\":\"invalid-token\"}"))); + } + + @Test diff --git a/tasks/spring-projects__spring-boot-50256/tests/test.sh b/tasks/spring-projects__spring-boot-50256/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b79e7770430a3c9ab05e00f70e50e189963c8e28 --- /dev/null +++ b/tasks/spring-projects__spring-boot-50256/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4307353d6abbd1ffceec0433245b927af7cb2d83 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-50256/tests/verifier.py b/tasks/spring-projects__spring-boot-50256/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-50256/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-50963/environment/Dockerfile b/tasks/spring-projects__spring-boot-50963/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..536814f7f36b597b0ab20ad1285d2ce996fbaee4 --- /dev/null +++ b/tasks/spring-projects__spring-boot-50963/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin efd6f2b547036a27cbb4cd5b218f35c47466e9c0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard efd6f2b547036a27cbb4cd5b218f35c47466e9c0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base efd6f2b547036a27cbb4cd5b218f35c47466e9c0 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-50963/instruction.md b/tasks/spring-projects__spring-boot-50963/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4445992aa00e5929dba71179deff6f50586a0476 --- /dev/null +++ b/tasks/spring-projects__spring-boot-50963/instruction.md @@ -0,0 +1,50 @@ +# Issue + +**Title:** Docker Compose ProcessRunner can hang or leave orphan processes + +## Description + +## Summary + +ProcessRunner can hang forever if a stream reader fails, and can leave orphan Docker Compose child processes when waitFor is interrupted. + +## Problem + +`ReaderThread` only calls `CountDownLatch.countDown()` on the success path. If reading fails with `IOException`, or if the optional `outputConsumer` throws, the latch is never released. After the child process exits, `ProcessRunner.run` blocks forever on `latch.await()` in `ReaderThread.toString()`. + +Separately, when `process.waitFor()` is interrupted, the interrupt flag is restored and an exception is thrown (fixed in #50451), but the child process is not destroyed. Docker Compose commands can remain as orphans. + +## Change + +- Move `latch.countDown()` into a `finally` block in `ReaderThread.run()`. +- Call `process.destroy()` after restoring the interrupt flag when `waitFor` is interrupted. + +## Failure scenario + +1. Docker Compose support runs a process via `ProcessRunner.run(consumer, command...)`. +2. The consumer throws (or stream read fails) after partial output. +3. The process exits, but the reader never counts down the latch. +4. The calling thread blocks indefinitely on `toString()` / `await()`. + +For interrupt: a long-running compose command is interrupted during `waitFor`; without `destroy()`, the child keeps running after the Spring Boot thread has aborted. + +## Origin + +Introduced with Docker Compose support in (2023-04-07, Moritz Halbritter). Present for ~3 years. Related prior fix: #50451 (interrupt flag restore only). + +## Validation + +- Red/green: + - `runWhenOutputConsumerThrowsDoesNotHang`: timed out without the latch fix; passes with it. + - `runWhenInterruptedDestroysChildProcess`: child `sleep` stayed alive without destroy; process is dead with the fix. +- `./gradlew :core:spring-boot-docker-compose:test --tests ProcessRunnerTests` +- `checkFormatMain` / `checkFormatTest` / `checkstyleMain` / `checkstyleTest` + +## Related + +- #50451 Restore interrupt flag in ProcessRunner +- Sibling kill pattern: `RunProcess.destroy()` in loader-tools + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `efd6f2b54703`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-50963/solution/patch.diff b/tasks/spring-projects__spring-boot-50963/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d91bcd813504559c38c2e44cbcea2b213b8b0147 --- /dev/null +++ b/tasks/spring-projects__spring-boot-50963/solution/patch.diff @@ -0,0 +1,153 @@ +diff --git a/core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/core/ProcessRunner.java b/core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/core/ProcessRunner.java +index b0491330f59..6a6694f3daf 100644 +--- a/core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/core/ProcessRunner.java ++++ b/core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/core/ProcessRunner.java +@@ -124,6 +124,7 @@ class ProcessRunner { + } + catch (InterruptedException ex) { + Thread.currentThread().interrupt(); ++ process.destroy(); + throw new IllegalStateException("Interrupted waiting for %s".formatted(process), ex); + } + } +@@ -162,11 +163,13 @@ class ProcessRunner { + } + line = reader.readLine(); + } +- this.latch.countDown(); + } + catch (IOException ex) { + throw new UncheckedIOException("Failed to read process stream", ex); + } ++ finally { ++ this.latch.countDown(); ++ } + } + + @Override +diff --git a/core/spring-boot-docker-compose/src/test/java/org/springframework/boot/docker/compose/core/ProcessRunnerTests.java b/core/spring-boot-docker-compose/src/test/java/org/springframework/boot/docker/compose/core/ProcessRunnerTests.java +index 5fc96511bd3..370bb88551c 100644 +--- a/core/spring-boot-docker-compose/src/test/java/org/springframework/boot/docker/compose/core/ProcessRunnerTests.java ++++ b/core/spring-boot-docker-compose/src/test/java/org/springframework/boot/docker/compose/core/ProcessRunnerTests.java +@@ -16,7 +16,17 @@ + + package org.springframework.boot.docker.compose.core; + ++import java.nio.file.Files; ++import java.nio.file.LinkOption; ++import java.nio.file.Path; ++import java.time.Duration; ++import java.util.concurrent.atomic.AtomicReference; ++ ++import org.awaitility.Awaitility; ++import org.junit.jupiter.api.Nested; + import org.junit.jupiter.api.Test; ++import org.junit.jupiter.api.condition.DisabledOnOs; ++import org.junit.jupiter.api.condition.OS; + + import org.springframework.boot.testsupport.process.DisabledIfProcessUnavailable; + +@@ -29,40 +39,82 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + * @author Moritz Halbritter + * @author Andy Wilkinson + * @author Phillip Webb ++ * @author Sebastien Tardif + */ +-@DisabledIfProcessUnavailable("docker") + class ProcessRunnerTests { + +- private ProcessRunner processRunner = new ProcessRunner(); ++ private final ProcessRunner processRunner = new ProcessRunner(); + + @Test +- void run() { +- String out = this.processRunner.run("docker", "--version"); +- assertThat(out).isNotEmpty(); ++ void runWhenProcessDoesNotStart() { ++ assertThatExceptionOfType(ProcessStartException.class) ++ .isThrownBy(() -> this.processRunner.run("iverymuchdontexist", "--version")); + } + + @Test +- void runWhenHasOutputConsumer() { +- StringBuilder output = new StringBuilder(); +- this.processRunner.run(output::append, "docker", "--version"); +- assertThat(output.toString()).isNotEmpty(); ++ @DisabledOnOs(OS.WINDOWS) ++ void runWhenOutputConsumerThrowsDoesNotHang() throws InterruptedException { ++ Thread runner = new Thread(() -> this.processRunner.run((line) -> { ++ throw new IllegalStateException("boom"); ++ }, "echo", "hello"), "process-runner-consumer-throw-test"); ++ runner.start(); ++ runner.join(Duration.ofSeconds(5).toMillis()); ++ assertThat(runner.isAlive()).isFalse(); + } + + @Test +- void runWhenProcessDoesNotStart() { +- assertThatExceptionOfType(ProcessStartException.class) +- .isThrownBy(() -> this.processRunner.run("iverymuchdontexist", "--version")); ++ @DisabledOnOs(OS.WINDOWS) ++ void runWhenInterruptedDestroysChildProcess() throws Exception { ++ Path pidFile = Files.createTempFile("process-runner-", ".pid"); ++ Files.delete(pidFile); ++ AtomicReference<Throwable> error = new AtomicReference<>(); ++ Thread runner = new Thread(() -> { ++ try { ++ this.processRunner.run("sh", "-c", "echo $$ > '" + pidFile + "'; exec sleep 60"); ++ } ++ catch (Throwable ex) { ++ error.set(ex); ++ } ++ }, "process-runner-interrupt-test"); ++ runner.start(); ++ Awaitility.await().until(() -> Files.exists(pidFile, LinkOption.NOFOLLOW_LINKS)); ++ long pid = Long.parseLong(Files.readString(pidFile).trim()); ++ assertThat(ProcessHandle.of(pid)).isPresent().get().matches(ProcessHandle::isAlive); ++ runner.interrupt(); ++ runner.join(Duration.ofSeconds(5).toMillis()); ++ assertThat(runner.isAlive()).isFalse(); ++ assertThat(error.get()).isInstanceOf(IllegalStateException.class); ++ assertThat(ProcessHandle.of(pid).map(ProcessHandle::isAlive).orElse(false)).isFalse(); + } + +- @Test +- void runWhenProcessReturnsNonZeroExitCode() { +- assertThatExceptionOfType(ProcessExitException.class) +- .isThrownBy(() -> this.processRunner.run("docker", "-thisdoesntwork")) +- .satisfies((ex) -> { +- assertThat(ex.getExitCode()).isGreaterThan(0); +- assertThat(ex.getStdOut()).isEmpty(); +- assertThat(ex.getStdErr()).isNotEmpty(); +- }); ++ @Nested ++ @DisabledIfProcessUnavailable("docker") ++ class WhenDockerIsAvailable { ++ ++ @Test ++ void run() { ++ String out = ProcessRunnerTests.this.processRunner.run("docker", "--version"); ++ assertThat(out).isNotEmpty(); ++ } ++ ++ @Test ++ void runWhenHasOutputConsumer() { ++ StringBuilder output = new StringBuilder(); ++ ProcessRunnerTests.this.processRunner.run(output::append, "docker", "--version"); ++ assertThat(output.toString()).isNotEmpty(); ++ } ++ ++ @Test ++ void runWhenProcessReturnsNonZeroExitCode() { ++ assertThatExceptionOfType(ProcessExitException.class) ++ .isThrownBy(() -> ProcessRunnerTests.this.processRunner.run("docker", "-thisdoesntwork")) ++ .satisfies((ex) -> { ++ assertThat(ex.getExitCode()).isGreaterThan(0); ++ assertThat(ex.getStdOut()).isEmpty(); ++ assertThat(ex.getStdErr()).isNotEmpty(); ++ }); ++ } ++ + } + + } diff --git a/tasks/spring-projects__spring-boot-50963/solution/solve.sh b/tasks/spring-projects__spring-boot-50963/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-50963/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-50963/task.toml b/tasks/spring-projects__spring-boot-50963/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cad6e50317ff6433d89767a53aeb79dd56c7aba9 --- /dev/null +++ b/tasks/spring-projects__spring-boot-50963/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-50963" +description = "Docker Compose ProcessRunner can hang or leave orphan processes" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "efd6f2b547036a27cbb4cd5b218f35c47466e9c0" +reference = "https://github.com/spring-projects/spring-boot/pull/50963" +source_access = "auto" +built_at = "2026-11-16T16:09:44.792009+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1e0343395b0b350f973354c779ac05c89c854aaa7df9e5bb13df72f4aa117b3b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-02T08:13:31Z" +diff_format = "unified" +context_files = [ + "core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/core/ProcessRunner.java", + "core/spring-boot-docker-compose/src/test/java/org/springframework/boot/docker/compose/core/ProcessRunnerTests.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 99 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.160301+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:5121036ca2edcfe40eaca36eba6b049b9f446ea3c77567244575a4d19db327b3" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-50963/tests/capture.py b/tasks/spring-projects__spring-boot-50963/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-50963/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-50963/tests/instruction.md b/tasks/spring-projects__spring-boot-50963/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4445992aa00e5929dba71179deff6f50586a0476 --- /dev/null +++ b/tasks/spring-projects__spring-boot-50963/tests/instruction.md @@ -0,0 +1,50 @@ +# Issue + +**Title:** Docker Compose ProcessRunner can hang or leave orphan processes + +## Description + +## Summary + +ProcessRunner can hang forever if a stream reader fails, and can leave orphan Docker Compose child processes when waitFor is interrupted. + +## Problem + +`ReaderThread` only calls `CountDownLatch.countDown()` on the success path. If reading fails with `IOException`, or if the optional `outputConsumer` throws, the latch is never released. After the child process exits, `ProcessRunner.run` blocks forever on `latch.await()` in `ReaderThread.toString()`. + +Separately, when `process.waitFor()` is interrupted, the interrupt flag is restored and an exception is thrown (fixed in #50451), but the child process is not destroyed. Docker Compose commands can remain as orphans. + +## Change + +- Move `latch.countDown()` into a `finally` block in `ReaderThread.run()`. +- Call `process.destroy()` after restoring the interrupt flag when `waitFor` is interrupted. + +## Failure scenario + +1. Docker Compose support runs a process via `ProcessRunner.run(consumer, command...)`. +2. The consumer throws (or stream read fails) after partial output. +3. The process exits, but the reader never counts down the latch. +4. The calling thread blocks indefinitely on `toString()` / `await()`. + +For interrupt: a long-running compose command is interrupted during `waitFor`; without `destroy()`, the child keeps running after the Spring Boot thread has aborted. + +## Origin + +Introduced with Docker Compose support in (2023-04-07, Moritz Halbritter). Present for ~3 years. Related prior fix: #50451 (interrupt flag restore only). + +## Validation + +- Red/green: + - `runWhenOutputConsumerThrowsDoesNotHang`: timed out without the latch fix; passes with it. + - `runWhenInterruptedDestroysChildProcess`: child `sleep` stayed alive without destroy; process is dead with the fix. +- `./gradlew :core:spring-boot-docker-compose:test --tests ProcessRunnerTests` +- `checkFormatMain` / `checkFormatTest` / `checkstyleMain` / `checkstyleTest` + +## Related + +- #50451 Restore interrupt flag in ProcessRunner +- Sibling kill pattern: `RunProcess.destroy()` in loader-tools + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `efd6f2b54703`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-50963/tests/oracle.patch b/tasks/spring-projects__spring-boot-50963/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d91bcd813504559c38c2e44cbcea2b213b8b0147 --- /dev/null +++ b/tasks/spring-projects__spring-boot-50963/tests/oracle.patch @@ -0,0 +1,153 @@ +diff --git a/core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/core/ProcessRunner.java b/core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/core/ProcessRunner.java +index b0491330f59..6a6694f3daf 100644 +--- a/core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/core/ProcessRunner.java ++++ b/core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/core/ProcessRunner.java +@@ -124,6 +124,7 @@ class ProcessRunner { + } + catch (InterruptedException ex) { + Thread.currentThread().interrupt(); ++ process.destroy(); + throw new IllegalStateException("Interrupted waiting for %s".formatted(process), ex); + } + } +@@ -162,11 +163,13 @@ class ProcessRunner { + } + line = reader.readLine(); + } +- this.latch.countDown(); + } + catch (IOException ex) { + throw new UncheckedIOException("Failed to read process stream", ex); + } ++ finally { ++ this.latch.countDown(); ++ } + } + + @Override +diff --git a/core/spring-boot-docker-compose/src/test/java/org/springframework/boot/docker/compose/core/ProcessRunnerTests.java b/core/spring-boot-docker-compose/src/test/java/org/springframework/boot/docker/compose/core/ProcessRunnerTests.java +index 5fc96511bd3..370bb88551c 100644 +--- a/core/spring-boot-docker-compose/src/test/java/org/springframework/boot/docker/compose/core/ProcessRunnerTests.java ++++ b/core/spring-boot-docker-compose/src/test/java/org/springframework/boot/docker/compose/core/ProcessRunnerTests.java +@@ -16,7 +16,17 @@ + + package org.springframework.boot.docker.compose.core; + ++import java.nio.file.Files; ++import java.nio.file.LinkOption; ++import java.nio.file.Path; ++import java.time.Duration; ++import java.util.concurrent.atomic.AtomicReference; ++ ++import org.awaitility.Awaitility; ++import org.junit.jupiter.api.Nested; + import org.junit.jupiter.api.Test; ++import org.junit.jupiter.api.condition.DisabledOnOs; ++import org.junit.jupiter.api.condition.OS; + + import org.springframework.boot.testsupport.process.DisabledIfProcessUnavailable; + +@@ -29,40 +39,82 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + * @author Moritz Halbritter + * @author Andy Wilkinson + * @author Phillip Webb ++ * @author Sebastien Tardif + */ +-@DisabledIfProcessUnavailable("docker") + class ProcessRunnerTests { + +- private ProcessRunner processRunner = new ProcessRunner(); ++ private final ProcessRunner processRunner = new ProcessRunner(); + + @Test +- void run() { +- String out = this.processRunner.run("docker", "--version"); +- assertThat(out).isNotEmpty(); ++ void runWhenProcessDoesNotStart() { ++ assertThatExceptionOfType(ProcessStartException.class) ++ .isThrownBy(() -> this.processRunner.run("iverymuchdontexist", "--version")); + } + + @Test +- void runWhenHasOutputConsumer() { +- StringBuilder output = new StringBuilder(); +- this.processRunner.run(output::append, "docker", "--version"); +- assertThat(output.toString()).isNotEmpty(); ++ @DisabledOnOs(OS.WINDOWS) ++ void runWhenOutputConsumerThrowsDoesNotHang() throws InterruptedException { ++ Thread runner = new Thread(() -> this.processRunner.run((line) -> { ++ throw new IllegalStateException("boom"); ++ }, "echo", "hello"), "process-runner-consumer-throw-test"); ++ runner.start(); ++ runner.join(Duration.ofSeconds(5).toMillis()); ++ assertThat(runner.isAlive()).isFalse(); + } + + @Test +- void runWhenProcessDoesNotStart() { +- assertThatExceptionOfType(ProcessStartException.class) +- .isThrownBy(() -> this.processRunner.run("iverymuchdontexist", "--version")); ++ @DisabledOnOs(OS.WINDOWS) ++ void runWhenInterruptedDestroysChildProcess() throws Exception { ++ Path pidFile = Files.createTempFile("process-runner-", ".pid"); ++ Files.delete(pidFile); ++ AtomicReference<Throwable> error = new AtomicReference<>(); ++ Thread runner = new Thread(() -> { ++ try { ++ this.processRunner.run("sh", "-c", "echo $$ > '" + pidFile + "'; exec sleep 60"); ++ } ++ catch (Throwable ex) { ++ error.set(ex); ++ } ++ }, "process-runner-interrupt-test"); ++ runner.start(); ++ Awaitility.await().until(() -> Files.exists(pidFile, LinkOption.NOFOLLOW_LINKS)); ++ long pid = Long.parseLong(Files.readString(pidFile).trim()); ++ assertThat(ProcessHandle.of(pid)).isPresent().get().matches(ProcessHandle::isAlive); ++ runner.interrupt(); ++ runner.join(Duration.ofSeconds(5).toMillis()); ++ assertThat(runner.isAlive()).isFalse(); ++ assertThat(error.get()).isInstanceOf(IllegalStateException.class); ++ assertThat(ProcessHandle.of(pid).map(ProcessHandle::isAlive).orElse(false)).isFalse(); + } + +- @Test +- void runWhenProcessReturnsNonZeroExitCode() { +- assertThatExceptionOfType(ProcessExitException.class) +- .isThrownBy(() -> this.processRunner.run("docker", "-thisdoesntwork")) +- .satisfies((ex) -> { +- assertThat(ex.getExitCode()).isGreaterThan(0); +- assertThat(ex.getStdOut()).isEmpty(); +- assertThat(ex.getStdErr()).isNotEmpty(); +- }); ++ @Nested ++ @DisabledIfProcessUnavailable("docker") ++ class WhenDockerIsAvailable { ++ ++ @Test ++ void run() { ++ String out = ProcessRunnerTests.this.processRunner.run("docker", "--version"); ++ assertThat(out).isNotEmpty(); ++ } ++ ++ @Test ++ void runWhenHasOutputConsumer() { ++ StringBuilder output = new StringBuilder(); ++ ProcessRunnerTests.this.processRunner.run(output::append, "docker", "--version"); ++ assertThat(output.toString()).isNotEmpty(); ++ } ++ ++ @Test ++ void runWhenProcessReturnsNonZeroExitCode() { ++ assertThatExceptionOfType(ProcessExitException.class) ++ .isThrownBy(() -> ProcessRunnerTests.this.processRunner.run("docker", "-thisdoesntwork")) ++ .satisfies((ex) -> { ++ assertThat(ex.getExitCode()).isGreaterThan(0); ++ assertThat(ex.getStdOut()).isEmpty(); ++ assertThat(ex.getStdErr()).isNotEmpty(); ++ }); ++ } ++ + } + + } diff --git a/tasks/spring-projects__spring-boot-50963/tests/test.sh b/tasks/spring-projects__spring-boot-50963/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4e1d16f08a61719628fb67ff58080ff74a983616 --- /dev/null +++ b/tasks/spring-projects__spring-boot-50963/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace efd6f2b547036a27cbb4cd5b218f35c47466e9c0 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-50963/tests/verifier.py b/tasks/spring-projects__spring-boot-50963/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-50963/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51386/environment/Dockerfile b/tasks/spring-projects__spring-boot-51386/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..154823d5f6181e9f7b28e85811aadb80a4e51469 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51386/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3a869d06454609daf28736336705d4a49d428b1f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3a869d06454609daf28736336705d4a49d428b1f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3a869d06454609daf28736336705d4a49d428b1f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51386/instruction.md b/tasks/spring-projects__spring-boot-51386/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ce500ede0ea8ca6ce7c100735599bf6a308067d9 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51386/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Automatically filter additional configuration metadata from Spring Boot-built archives + +## Description + +This updates Spring Boot's Maven and Gradle packaging support to exclude `META-INF/additional-spring-configuration-metadata.json` from built archives. The additional metadata has already been merged into `spring-configuration-metadata.json` by the annotation processor. + +The loader tools filter the metadata relative to the layout's classes location, covering both jars and wars. Gradle boot archives apply the equivalent default exclusion. The documentation also shows how to configure the exclusion when building a library without either Spring Boot plugin. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3a869d064546`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51386/solution/patch.diff b/tasks/spring-projects__spring-boot-51386/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9bdaaaffa5cbe9c85bce5c88bff6d06cc1d7c55e --- /dev/null +++ b/tasks/spring-projects__spring-boot-51386/solution/patch.diff @@ -0,0 +1,165 @@ +diff --git a/build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java b/build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java +index 12b68384e91..0d9e6d702c8 100644 +--- a/build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java ++++ b/build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java +@@ -46,6 +46,7 @@ import org.jspecify.annotations.Nullable; + * @author Andy Wilkinson + * @author Phillip Webb + * @author Scott Frederick ++ * @author Wan bin yu + * @see BootJar + * @see BootWar + */ +@@ -81,6 +82,7 @@ class BootArchiveSupport { + this.librarySpec = librarySpec; + this.compressionResolver = compressionResolver; + this.requiresUnpack.include(Specs.satisfyNone()); ++ this.exclusions.exclude("**/META-INF/additional-spring-configuration-metadata.json"); + } + + void configureManifest(Manifest manifest, String mainClass, String classes, String lib, +diff --git a/build-plugin/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java b/build-plugin/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java +index ad1c00e2221..ee7a73ecf1e 100644 +--- a/build-plugin/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java ++++ b/build-plugin/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java +@@ -247,6 +247,25 @@ abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> { + } + } + ++ @Test ++ void additionalConfigurationMetadataIsExcluded() throws IOException { ++ this.task.getMainClass().set("com.example.Main"); ++ File classpathDirectory = new File(this.temp, "classes"); ++ File additionalMetadata = new File(classpathDirectory, ++ "META-INF/additional-spring-configuration-metadata.json"); ++ additionalMetadata.getParentFile().mkdirs(); ++ additionalMetadata.createNewFile(); ++ File metadata = new File(classpathDirectory, "META-INF/spring-configuration-metadata.json"); ++ metadata.createNewFile(); ++ this.task.classpath(classpathDirectory); ++ executeTask(); ++ try (JarFile jarFile = new JarFile(this.task.getArchiveFile().get().getAsFile())) { ++ assertThat(getEntryNames(jarFile)) ++ .noneMatch((name) -> name.endsWith("META-INF/additional-spring-configuration-metadata.json")) ++ .anyMatch((name) -> name.endsWith("META-INF/spring-configuration-metadata.json")); ++ } ++ } ++ + @Test + void loaderIsWrittenToTheRootOfTheJarAfterManifest() throws IOException { + this.task.getMainClass().set("com.example.Main"); +diff --git a/documentation/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/annotation-processor.adoc b/documentation/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/annotation-processor.adoc +index 1bd89fb429f..36d96313fa6 100644 +--- a/documentation/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/annotation-processor.adoc ++++ b/documentation/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/annotation-processor.adoc +@@ -192,3 +192,28 @@ The items contained in the "`ignored.properties`" section are removed from the " + + The additional properties file is optional. + If you do not have any additional properties, do not add the file. ++ ++The Spring Boot Maven and Gradle plugins exclude `additional-spring-configuration-metadata.json` from the packaged artifact. ++If you do not use either plugin to build your library, you should configure your build to exclude the file. ++With Maven, you can configure the `maven-jar-plugin` as follows: ++ ++[source,xml] ++---- ++<plugin> ++ <artifactId>maven-jar-plugin</artifactId> ++ <configuration> ++ <excludes> ++ <exclude>META-INF/additional-spring-configuration-metadata.json</exclude> ++ </excludes> ++ </configuration> ++</plugin> ++---- ++ ++With Gradle, you can configure the `jar` task as follows: ++ ++[source,gradle] ++---- ++tasks.named('jar') { ++ exclude('META-INF/additional-spring-configuration-metadata.json') ++} ++---- +diff --git a/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java b/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java +index 50754fa09c9..1de0a332714 100644 +--- a/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java ++++ b/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java +@@ -55,10 +55,13 @@ import org.springframework.util.StringUtils; + * @author Stephane Nicoll + * @author Madhura Bhave + * @author Scott Frederick ++ * @author Wan bin yu + * @since 2.3.0 + */ + public abstract class Packager { + ++ private static final String ADDITIONAL_CONFIGURATION_METADATA_PATH = "META-INF/additional-spring-configuration-metadata.json"; ++ + private static final String MAIN_CLASS_ATTRIBUTE = "Main-Class"; + + private static final String START_CLASS_ATTRIBUTE = "Start-Class"; +@@ -205,7 +208,7 @@ public abstract class Packager { + } + writer.writeManifest(buildManifest(sourceJar)); + writeLoaderClasses(writer); +- writer.writeEntries(sourceJar, getEntityTransformer(), libraries.getUnpackHandler(), ++ writer.writeEntries(sourceJar, getEntryTransformer(), libraries.getUnpackHandler(), + libraries.getLibraryLookup()); + Map<String, Library> writtenLibraries = libraries.write(writer); + writeNativeImageArgFile(writer, sourceJar, writtenLibraries); +@@ -272,11 +275,14 @@ public abstract class Packager { + throws IOException { + } + +- private EntryTransformer getEntityTransformer() { ++ private EntryTransformer getEntryTransformer() { ++ EntryTransformer transformer = EntryTransformer.NONE; + if (getLayout() instanceof RepackagingLayout repackagingLayout) { +- return new RepackagingEntryTransformer(repackagingLayout); ++ transformer = new RepackagingEntryTransformer(repackagingLayout); + } +- return EntryTransformer.NONE; ++ EntryTransformer delegate = transformer; ++ String additionalMetadataLocation = getLayout().getClassesLocation() + ADDITIONAL_CONFIGURATION_METADATA_PATH; ++ return (entry) -> (entry.getName().equals(additionalMetadataLocation)) ? null : delegate.transform(entry); + } + + private boolean isZip(InputStreamSupplier supplier) { +diff --git a/loader/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java b/loader/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java +index 02a02d1befa..57d05dc4229 100644 +--- a/loader/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java ++++ b/loader/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java +@@ -486,6 +486,32 @@ abstract class AbstractPackagerTests<P extends Packager> { + assertThat(getPackagedEntry("META-INF/INDEX.LIST")).isNull(); + } + ++ @Test ++ void additionalConfigurationMetadataIsRemovedFromRepackagedJar() throws Exception { ++ this.testJarFile.addClass("A.class", ClassWithMainMethod.class); ++ this.testJarFile.addFile("META-INF/additional-spring-configuration-metadata.json", ++ new ByteArrayInputStream(new byte[0])); ++ this.testJarFile.addFile("META-INF/spring-configuration-metadata.json", new ByteArrayInputStream(new byte[0])); ++ P packager = createPackager(); ++ execute(packager, NO_LIBRARIES); ++ assertThat(getPackagedEntry("META-INF/additional-spring-configuration-metadata.json")).isNull(); ++ assertThat(getPackagedEntry("META-INF/spring-configuration-metadata.json")).isNotNull(); ++ } ++ ++ @Test ++ void additionalConfigurationMetadataIsRemovedFromRepackagedWar() throws Exception { ++ this.testJarFile.addClass("WEB-INF/classes/com/example/Application.class", ClassWithMainMethod.class); ++ this.testJarFile.addFile("WEB-INF/classes/META-INF/additional-spring-configuration-metadata.json", ++ new ByteArrayInputStream(new byte[0])); ++ this.testJarFile.addFile("WEB-INF/classes/META-INF/spring-configuration-metadata.json", ++ new ByteArrayInputStream(new byte[0])); ++ P packager = createPackager(this.testJarFile.getFile("war")); ++ packager.setLayout(new Layouts.War()); ++ execute(packager, NO_LIBRARIES); ++ assertThat(getPackagedEntry("WEB-INF/classes/META-INF/additional-spring-configuration-metadata.json")).isNull(); ++ assertThat(getPackagedEntry("WEB-INF/classes/META-INF/spring-configuration-metadata.json")).isNotNull(); ++ } ++ + @Test + void customLayoutFactoryWithoutLayout() throws Exception { + this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); diff --git a/tasks/spring-projects__spring-boot-51386/solution/solve.sh b/tasks/spring-projects__spring-boot-51386/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51386/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51386/task.toml b/tasks/spring-projects__spring-boot-51386/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ae4ae6f81969398ec6ce1579d9c5c79552cefdf8 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51386/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51386" +description = "Automatically filter additional configuration metadata from Spring Boot-built archives" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "3a869d06454609daf28736336705d4a49d428b1f" +reference = "https://github.com/spring-projects/spring-boot/pull/51386" +source_access = "auto" +built_at = "2026-11-16T16:09:44.766015+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d3d0d13750d1e9dae1dfa2d9c605cfcba5508fa27ab84df8ade9591893583110" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-09T08:55:39Z" +diff_format = "unified" +context_files = [ + "build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java", + "build-plugin/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java", + "documentation/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/annotation-processor.adoc", + "loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java", + "loader/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 86 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.160866+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ad71a6c139e5b4b37ddc708f1a38b9b27919fc2345ccd0a71874eddf47bc8b1e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51386/tests/capture.py b/tasks/spring-projects__spring-boot-51386/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51386/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51386/tests/instruction.md b/tasks/spring-projects__spring-boot-51386/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ce500ede0ea8ca6ce7c100735599bf6a308067d9 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51386/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Automatically filter additional configuration metadata from Spring Boot-built archives + +## Description + +This updates Spring Boot's Maven and Gradle packaging support to exclude `META-INF/additional-spring-configuration-metadata.json` from built archives. The additional metadata has already been merged into `spring-configuration-metadata.json` by the annotation processor. + +The loader tools filter the metadata relative to the layout's classes location, covering both jars and wars. Gradle boot archives apply the equivalent default exclusion. The documentation also shows how to configure the exclusion when building a library without either Spring Boot plugin. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3a869d064546`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51386/tests/oracle.patch b/tasks/spring-projects__spring-boot-51386/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9bdaaaffa5cbe9c85bce5c88bff6d06cc1d7c55e --- /dev/null +++ b/tasks/spring-projects__spring-boot-51386/tests/oracle.patch @@ -0,0 +1,165 @@ +diff --git a/build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java b/build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java +index 12b68384e91..0d9e6d702c8 100644 +--- a/build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java ++++ b/build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/BootArchiveSupport.java +@@ -46,6 +46,7 @@ import org.jspecify.annotations.Nullable; + * @author Andy Wilkinson + * @author Phillip Webb + * @author Scott Frederick ++ * @author Wan bin yu + * @see BootJar + * @see BootWar + */ +@@ -81,6 +82,7 @@ class BootArchiveSupport { + this.librarySpec = librarySpec; + this.compressionResolver = compressionResolver; + this.requiresUnpack.include(Specs.satisfyNone()); ++ this.exclusions.exclude("**/META-INF/additional-spring-configuration-metadata.json"); + } + + void configureManifest(Manifest manifest, String mainClass, String classes, String lib, +diff --git a/build-plugin/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java b/build-plugin/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java +index ad1c00e2221..ee7a73ecf1e 100644 +--- a/build-plugin/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java ++++ b/build-plugin/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveTests.java +@@ -247,6 +247,25 @@ abstract class AbstractBootArchiveTests<T extends Jar & BootArchive> { + } + } + ++ @Test ++ void additionalConfigurationMetadataIsExcluded() throws IOException { ++ this.task.getMainClass().set("com.example.Main"); ++ File classpathDirectory = new File(this.temp, "classes"); ++ File additionalMetadata = new File(classpathDirectory, ++ "META-INF/additional-spring-configuration-metadata.json"); ++ additionalMetadata.getParentFile().mkdirs(); ++ additionalMetadata.createNewFile(); ++ File metadata = new File(classpathDirectory, "META-INF/spring-configuration-metadata.json"); ++ metadata.createNewFile(); ++ this.task.classpath(classpathDirectory); ++ executeTask(); ++ try (JarFile jarFile = new JarFile(this.task.getArchiveFile().get().getAsFile())) { ++ assertThat(getEntryNames(jarFile)) ++ .noneMatch((name) -> name.endsWith("META-INF/additional-spring-configuration-metadata.json")) ++ .anyMatch((name) -> name.endsWith("META-INF/spring-configuration-metadata.json")); ++ } ++ } ++ + @Test + void loaderIsWrittenToTheRootOfTheJarAfterManifest() throws IOException { + this.task.getMainClass().set("com.example.Main"); +diff --git a/documentation/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/annotation-processor.adoc b/documentation/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/annotation-processor.adoc +index 1bd89fb429f..36d96313fa6 100644 +--- a/documentation/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/annotation-processor.adoc ++++ b/documentation/spring-boot-docs/src/docs/antora/modules/specification/pages/configuration-metadata/annotation-processor.adoc +@@ -192,3 +192,28 @@ The items contained in the "`ignored.properties`" section are removed from the " + + The additional properties file is optional. + If you do not have any additional properties, do not add the file. ++ ++The Spring Boot Maven and Gradle plugins exclude `additional-spring-configuration-metadata.json` from the packaged artifact. ++If you do not use either plugin to build your library, you should configure your build to exclude the file. ++With Maven, you can configure the `maven-jar-plugin` as follows: ++ ++[source,xml] ++---- ++<plugin> ++ <artifactId>maven-jar-plugin</artifactId> ++ <configuration> ++ <excludes> ++ <exclude>META-INF/additional-spring-configuration-metadata.json</exclude> ++ </excludes> ++ </configuration> ++</plugin> ++---- ++ ++With Gradle, you can configure the `jar` task as follows: ++ ++[source,gradle] ++---- ++tasks.named('jar') { ++ exclude('META-INF/additional-spring-configuration-metadata.json') ++} ++---- +diff --git a/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java b/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java +index 50754fa09c9..1de0a332714 100644 +--- a/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java ++++ b/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/Packager.java +@@ -55,10 +55,13 @@ import org.springframework.util.StringUtils; + * @author Stephane Nicoll + * @author Madhura Bhave + * @author Scott Frederick ++ * @author Wan bin yu + * @since 2.3.0 + */ + public abstract class Packager { + ++ private static final String ADDITIONAL_CONFIGURATION_METADATA_PATH = "META-INF/additional-spring-configuration-metadata.json"; ++ + private static final String MAIN_CLASS_ATTRIBUTE = "Main-Class"; + + private static final String START_CLASS_ATTRIBUTE = "Start-Class"; +@@ -205,7 +208,7 @@ public abstract class Packager { + } + writer.writeManifest(buildManifest(sourceJar)); + writeLoaderClasses(writer); +- writer.writeEntries(sourceJar, getEntityTransformer(), libraries.getUnpackHandler(), ++ writer.writeEntries(sourceJar, getEntryTransformer(), libraries.getUnpackHandler(), + libraries.getLibraryLookup()); + Map<String, Library> writtenLibraries = libraries.write(writer); + writeNativeImageArgFile(writer, sourceJar, writtenLibraries); +@@ -272,11 +275,14 @@ public abstract class Packager { + throws IOException { + } + +- private EntryTransformer getEntityTransformer() { ++ private EntryTransformer getEntryTransformer() { ++ EntryTransformer transformer = EntryTransformer.NONE; + if (getLayout() instanceof RepackagingLayout repackagingLayout) { +- return new RepackagingEntryTransformer(repackagingLayout); ++ transformer = new RepackagingEntryTransformer(repackagingLayout); + } +- return EntryTransformer.NONE; ++ EntryTransformer delegate = transformer; ++ String additionalMetadataLocation = getLayout().getClassesLocation() + ADDITIONAL_CONFIGURATION_METADATA_PATH; ++ return (entry) -> (entry.getName().equals(additionalMetadataLocation)) ? null : delegate.transform(entry); + } + + private boolean isZip(InputStreamSupplier supplier) { +diff --git a/loader/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java b/loader/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java +index 02a02d1befa..57d05dc4229 100644 +--- a/loader/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java ++++ b/loader/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/AbstractPackagerTests.java +@@ -486,6 +486,32 @@ abstract class AbstractPackagerTests<P extends Packager> { + assertThat(getPackagedEntry("META-INF/INDEX.LIST")).isNull(); + } + ++ @Test ++ void additionalConfigurationMetadataIsRemovedFromRepackagedJar() throws Exception { ++ this.testJarFile.addClass("A.class", ClassWithMainMethod.class); ++ this.testJarFile.addFile("META-INF/additional-spring-configuration-metadata.json", ++ new ByteArrayInputStream(new byte[0])); ++ this.testJarFile.addFile("META-INF/spring-configuration-metadata.json", new ByteArrayInputStream(new byte[0])); ++ P packager = createPackager(); ++ execute(packager, NO_LIBRARIES); ++ assertThat(getPackagedEntry("META-INF/additional-spring-configuration-metadata.json")).isNull(); ++ assertThat(getPackagedEntry("META-INF/spring-configuration-metadata.json")).isNotNull(); ++ } ++ ++ @Test ++ void additionalConfigurationMetadataIsRemovedFromRepackagedWar() throws Exception { ++ this.testJarFile.addClass("WEB-INF/classes/com/example/Application.class", ClassWithMainMethod.class); ++ this.testJarFile.addFile("WEB-INF/classes/META-INF/additional-spring-configuration-metadata.json", ++ new ByteArrayInputStream(new byte[0])); ++ this.testJarFile.addFile("WEB-INF/classes/META-INF/spring-configuration-metadata.json", ++ new ByteArrayInputStream(new byte[0])); ++ P packager = createPackager(this.testJarFile.getFile("war")); ++ packager.setLayout(new Layouts.War()); ++ execute(packager, NO_LIBRARIES); ++ assertThat(getPackagedEntry("WEB-INF/classes/META-INF/additional-spring-configuration-metadata.json")).isNull(); ++ assertThat(getPackagedEntry("WEB-INF/classes/META-INF/spring-configuration-metadata.json")).isNotNull(); ++ } ++ + @Test + void customLayoutFactoryWithoutLayout() throws Exception { + this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class); diff --git a/tasks/spring-projects__spring-boot-51386/tests/test.sh b/tasks/spring-projects__spring-boot-51386/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..54dbd0aa84d317911c93bc00dde0004441e4d232 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51386/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 3a869d06454609daf28736336705d4a49d428b1f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51386/tests/verifier.py b/tasks/spring-projects__spring-boot-51386/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51386/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51461/environment/Dockerfile b/tasks/spring-projects__spring-boot-51461/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a87a14bd1301436967ecd8a1fc3effed0bc28abf --- /dev/null +++ b/tasks/spring-projects__spring-boot-51461/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 37a20a302b844a064abef670b0ba6a7ccda4cb7b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 37a20a302b844a064abef670b0ba6a7ccda4cb7b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 37a20a302b844a064abef670b0ba6a7ccda4cb7b \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51461/instruction.md b/tasks/spring-projects__spring-boot-51461/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0bea20e0a5564583d0909b355afebfed968c0537 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51461/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Add a configuration property for configuring embedded LDAP operation types that require authentication + +## Description + +## Summary + +- Add `spring.ldap.embedded.authentication-required-operation-types` for configuring which embedded LDAP operations require authentication. +- Apply the configured operation types to the UnboundID in-memory directory server. +- Verify that anonymous searches are rejected when configured and authenticated searches continue to work. + +## Validation + +- `./gradlew :module:spring-boot-ldap:check` (JDK 25) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `37a20a302b84`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51461/solution/patch.diff b/tasks/spring-projects__spring-boot-51461/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cff5b029b58fd171b1f944b077513699c2100347 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51461/solution/patch.diff @@ -0,0 +1,140 @@ +diff --git a/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfiguration.java b/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfiguration.java +index 50c7770f31f..d4184c53fb7 100644 +--- a/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfiguration.java ++++ b/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfiguration.java +@@ -21,6 +21,7 @@ import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; ++import java.util.Set; + + import javax.net.ssl.SSLContext; + import javax.net.ssl.SSLServerSocketFactory; +@@ -30,6 +31,7 @@ import com.unboundid.ldap.listener.InMemoryDirectoryServer; + import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig; + import com.unboundid.ldap.listener.InMemoryListenerConfig; + import com.unboundid.ldap.sdk.LDAPException; ++import com.unboundid.ldap.sdk.OperationType; + import com.unboundid.ldap.sdk.schema.Schema; + import com.unboundid.ldif.LDIFReader; + import org.jspecify.annotations.Nullable; +@@ -81,6 +83,7 @@ import org.springframework.util.StringUtils; + * @author Mathieu Ouellet + * @author Raja Kolli + * @author Moritz Halbritter ++ * @author Sean Xu + * @since 4.0.0 + */ + @AutoConfiguration(before = LdapAutoConfiguration.class) +@@ -110,6 +113,11 @@ public final class EmbeddedLdapAutoConfiguration implements DisposableBean { + if (StringUtils.hasText(username) && StringUtils.hasText(password)) { + config.addAdditionalBindCredentials(username, password); + } ++ Set<OperationType> authenticationRequiredOperationTypes = this.embeddedProperties ++ .getAuthenticationRequiredOperationTypes(); ++ if (!authenticationRequiredOperationTypes.isEmpty()) { ++ config.setAuthenticationRequiredOperationTypes(authenticationRequiredOperationTypes); ++ } + config.setListenerConfigs(createListenerConfig(sslBundles)); + setSchema(config); + this.server = new InMemoryDirectoryServer(config); +diff --git a/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapProperties.java b/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapProperties.java +index b7c4a381447..06ad07f4002 100644 +--- a/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapProperties.java ++++ b/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapProperties.java +@@ -17,8 +17,11 @@ + package org.springframework.boot.ldap.autoconfigure.embedded; + + import java.util.ArrayList; ++import java.util.LinkedHashSet; + import java.util.List; ++import java.util.Set; + ++import com.unboundid.ldap.sdk.OperationType; + import org.jspecify.annotations.Nullable; + + import org.springframework.boot.context.properties.ConfigurationProperties; +@@ -31,6 +34,7 @@ import org.springframework.util.StringUtils; + * + * @author Eddú Meléndez + * @author Mathieu Ouellet ++ * @author Sean Xu + * @since 4.0.0 + */ + @ConfigurationProperties("spring.ldap.embedded") +@@ -41,6 +45,11 @@ public class EmbeddedLdapProperties { + */ + private int port; + ++ /** ++ * LDAP operation types that require authentication. ++ */ ++ private Set<OperationType> authenticationRequiredOperationTypes = new LinkedHashSet<>(); ++ + /** + * Embedded LDAP credentials. + */ +@@ -75,6 +84,14 @@ public class EmbeddedLdapProperties { + this.port = port; + } + ++ public Set<OperationType> getAuthenticationRequiredOperationTypes() { ++ return this.authenticationRequiredOperationTypes; ++ } ++ ++ public void setAuthenticationRequiredOperationTypes(Set<OperationType> authenticationRequiredOperationTypes) { ++ this.authenticationRequiredOperationTypes = authenticationRequiredOperationTypes; ++ } ++ + public Credential getCredential() { + return this.credential; + } +diff --git a/module/spring-boot-ldap/src/test/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfigurationTests.java b/module/spring-boot-ldap/src/test/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfigurationTests.java +index 489039a2cc4..ba2cc00fd9b 100644 +--- a/module/spring-boot-ldap/src/test/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfigurationTests.java ++++ b/module/spring-boot-ldap/src/test/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfigurationTests.java +@@ -29,6 +29,9 @@ import com.unboundid.ldap.sdk.BindResult; + import com.unboundid.ldap.sdk.DN; + import com.unboundid.ldap.sdk.LDAPConnection; + import com.unboundid.ldap.sdk.LDAPException; ++import com.unboundid.ldap.sdk.ResultCode; ++import com.unboundid.ldap.sdk.SearchRequest; ++import com.unboundid.ldap.sdk.SearchScope; + import com.unboundid.ldap.sdk.schema.Schema; + import org.assertj.core.api.InstanceOfAssertFactories; + import org.junit.jupiter.api.Test; +@@ -53,6 +56,7 @@ import org.springframework.ldap.core.LdapTemplate; + import org.springframework.ldap.core.support.LdapContextSource; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + + /** + * Tests for {@link EmbeddedLdapAutoConfiguration} +@@ -498,6 +502,26 @@ class EmbeddedLdapAutoConfigurationTests { + assertThat(properties.getSsl().isEnabled()).isFalse(); + } + ++ @Test ++ @WithSchemaLdifResource ++ void authenticationRequiredOperationTypesAreApplied() { ++ this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn=dc=spring,dc=org", ++ "spring.ldap.embedded.credential.username=uid=root", "spring.ldap.embedded.credential.password=boot", ++ "spring.ldap.embedded.authentication-required-operation-types=search") ++ .run((context) -> { ++ InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); ++ try (LDAPConnection connection = new LDAPConnection("localhost", server.getListenPort())) { ++ SearchRequest searchRequest = new SearchRequest("dc=spring,dc=org", SearchScope.SUB, ++ "(objectClass=*)"); ++ assertThatExceptionOfType(LDAPException.class).isThrownBy(() -> connection.search(searchRequest)) ++ .extracting(LDAPException::getResultCode) ++ .isEqualTo(ResultCode.INSUFFICIENT_ACCESS_RIGHTS); ++ connection.bind("uid=root", "boot"); ++ assertThat(connection.search(searchRequest).getEntryCount()).isGreaterThan(0); ++ } ++ }); ++ } ++ + private String[] sslBundleProperties(String... additionalProperties) { + String location = "classpath:org/springframework/boot/ldap/autoconfigure/embedded/"; + List<String> propertyValues = new ArrayList<>(); diff --git a/tasks/spring-projects__spring-boot-51461/solution/solve.sh b/tasks/spring-projects__spring-boot-51461/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51461/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51461/task.toml b/tasks/spring-projects__spring-boot-51461/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..52451629a81ad523d001e2094826bbe080315174 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51461/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51461" +description = "Add a configuration property for configuring embedded LDAP operation types that require authentication" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "37a20a302b844a064abef670b0ba6a7ccda4cb7b" +reference = "https://github.com/spring-projects/spring-boot/pull/51461" +source_access = "auto" +built_at = "2026-11-16T16:09:44.771872+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:047b99760e30662d1899209e2ac09906fe61047d0179e87e9f975e6d408cac93" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-27T13:58:36Z" +diff_format = "unified" +context_files = [ + "module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfiguration.java", + "module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapProperties.java", + "module/spring-boot-ldap/src/test/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfigurationTests.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 49 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.161481+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:26408295b3b5e0b5b294879f3ada17c3a3c16e32d01fc7065c7371f8eade8a6c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51461/tests/capture.py b/tasks/spring-projects__spring-boot-51461/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51461/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51461/tests/instruction.md b/tasks/spring-projects__spring-boot-51461/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0bea20e0a5564583d0909b355afebfed968c0537 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51461/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Add a configuration property for configuring embedded LDAP operation types that require authentication + +## Description + +## Summary + +- Add `spring.ldap.embedded.authentication-required-operation-types` for configuring which embedded LDAP operations require authentication. +- Apply the configured operation types to the UnboundID in-memory directory server. +- Verify that anonymous searches are rejected when configured and authenticated searches continue to work. + +## Validation + +- `./gradlew :module:spring-boot-ldap:check` (JDK 25) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `37a20a302b84`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51461/tests/oracle.patch b/tasks/spring-projects__spring-boot-51461/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cff5b029b58fd171b1f944b077513699c2100347 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51461/tests/oracle.patch @@ -0,0 +1,140 @@ +diff --git a/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfiguration.java b/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfiguration.java +index 50c7770f31f..d4184c53fb7 100644 +--- a/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfiguration.java ++++ b/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfiguration.java +@@ -21,6 +21,7 @@ import java.util.Collections; + import java.util.HashMap; + import java.util.List; + import java.util.Map; ++import java.util.Set; + + import javax.net.ssl.SSLContext; + import javax.net.ssl.SSLServerSocketFactory; +@@ -30,6 +31,7 @@ import com.unboundid.ldap.listener.InMemoryDirectoryServer; + import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig; + import com.unboundid.ldap.listener.InMemoryListenerConfig; + import com.unboundid.ldap.sdk.LDAPException; ++import com.unboundid.ldap.sdk.OperationType; + import com.unboundid.ldap.sdk.schema.Schema; + import com.unboundid.ldif.LDIFReader; + import org.jspecify.annotations.Nullable; +@@ -81,6 +83,7 @@ import org.springframework.util.StringUtils; + * @author Mathieu Ouellet + * @author Raja Kolli + * @author Moritz Halbritter ++ * @author Sean Xu + * @since 4.0.0 + */ + @AutoConfiguration(before = LdapAutoConfiguration.class) +@@ -110,6 +113,11 @@ public final class EmbeddedLdapAutoConfiguration implements DisposableBean { + if (StringUtils.hasText(username) && StringUtils.hasText(password)) { + config.addAdditionalBindCredentials(username, password); + } ++ Set<OperationType> authenticationRequiredOperationTypes = this.embeddedProperties ++ .getAuthenticationRequiredOperationTypes(); ++ if (!authenticationRequiredOperationTypes.isEmpty()) { ++ config.setAuthenticationRequiredOperationTypes(authenticationRequiredOperationTypes); ++ } + config.setListenerConfigs(createListenerConfig(sslBundles)); + setSchema(config); + this.server = new InMemoryDirectoryServer(config); +diff --git a/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapProperties.java b/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapProperties.java +index b7c4a381447..06ad07f4002 100644 +--- a/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapProperties.java ++++ b/module/spring-boot-ldap/src/main/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapProperties.java +@@ -17,8 +17,11 @@ + package org.springframework.boot.ldap.autoconfigure.embedded; + + import java.util.ArrayList; ++import java.util.LinkedHashSet; + import java.util.List; ++import java.util.Set; + ++import com.unboundid.ldap.sdk.OperationType; + import org.jspecify.annotations.Nullable; + + import org.springframework.boot.context.properties.ConfigurationProperties; +@@ -31,6 +34,7 @@ import org.springframework.util.StringUtils; + * + * @author Eddú Meléndez + * @author Mathieu Ouellet ++ * @author Sean Xu + * @since 4.0.0 + */ + @ConfigurationProperties("spring.ldap.embedded") +@@ -41,6 +45,11 @@ public class EmbeddedLdapProperties { + */ + private int port; + ++ /** ++ * LDAP operation types that require authentication. ++ */ ++ private Set<OperationType> authenticationRequiredOperationTypes = new LinkedHashSet<>(); ++ + /** + * Embedded LDAP credentials. + */ +@@ -75,6 +84,14 @@ public class EmbeddedLdapProperties { + this.port = port; + } + ++ public Set<OperationType> getAuthenticationRequiredOperationTypes() { ++ return this.authenticationRequiredOperationTypes; ++ } ++ ++ public void setAuthenticationRequiredOperationTypes(Set<OperationType> authenticationRequiredOperationTypes) { ++ this.authenticationRequiredOperationTypes = authenticationRequiredOperationTypes; ++ } ++ + public Credential getCredential() { + return this.credential; + } +diff --git a/module/spring-boot-ldap/src/test/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfigurationTests.java b/module/spring-boot-ldap/src/test/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfigurationTests.java +index 489039a2cc4..ba2cc00fd9b 100644 +--- a/module/spring-boot-ldap/src/test/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfigurationTests.java ++++ b/module/spring-boot-ldap/src/test/java/org/springframework/boot/ldap/autoconfigure/embedded/EmbeddedLdapAutoConfigurationTests.java +@@ -29,6 +29,9 @@ import com.unboundid.ldap.sdk.BindResult; + import com.unboundid.ldap.sdk.DN; + import com.unboundid.ldap.sdk.LDAPConnection; + import com.unboundid.ldap.sdk.LDAPException; ++import com.unboundid.ldap.sdk.ResultCode; ++import com.unboundid.ldap.sdk.SearchRequest; ++import com.unboundid.ldap.sdk.SearchScope; + import com.unboundid.ldap.sdk.schema.Schema; + import org.assertj.core.api.InstanceOfAssertFactories; + import org.junit.jupiter.api.Test; +@@ -53,6 +56,7 @@ import org.springframework.ldap.core.LdapTemplate; + import org.springframework.ldap.core.support.LdapContextSource; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + + /** + * Tests for {@link EmbeddedLdapAutoConfiguration} +@@ -498,6 +502,26 @@ class EmbeddedLdapAutoConfigurationTests { + assertThat(properties.getSsl().isEnabled()).isFalse(); + } + ++ @Test ++ @WithSchemaLdifResource ++ void authenticationRequiredOperationTypesAreApplied() { ++ this.contextRunner.withPropertyValues("spring.ldap.embedded.base-dn=dc=spring,dc=org", ++ "spring.ldap.embedded.credential.username=uid=root", "spring.ldap.embedded.credential.password=boot", ++ "spring.ldap.embedded.authentication-required-operation-types=search") ++ .run((context) -> { ++ InMemoryDirectoryServer server = context.getBean(InMemoryDirectoryServer.class); ++ try (LDAPConnection connection = new LDAPConnection("localhost", server.getListenPort())) { ++ SearchRequest searchRequest = new SearchRequest("dc=spring,dc=org", SearchScope.SUB, ++ "(objectClass=*)"); ++ assertThatExceptionOfType(LDAPException.class).isThrownBy(() -> connection.search(searchRequest)) ++ .extracting(LDAPException::getResultCode) ++ .isEqualTo(ResultCode.INSUFFICIENT_ACCESS_RIGHTS); ++ connection.bind("uid=root", "boot"); ++ assertThat(connection.search(searchRequest).getEntryCount()).isGreaterThan(0); ++ } ++ }); ++ } ++ + private String[] sslBundleProperties(String... additionalProperties) { + String location = "classpath:org/springframework/boot/ldap/autoconfigure/embedded/"; + List<String> propertyValues = new ArrayList<>(); diff --git a/tasks/spring-projects__spring-boot-51461/tests/test.sh b/tasks/spring-projects__spring-boot-51461/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8429d310716ebb5b66582fd4ac0f5b8452aff727 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51461/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 37a20a302b844a064abef670b0ba6a7ccda4cb7b > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51461/tests/verifier.py b/tasks/spring-projects__spring-boot-51461/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51461/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51464/environment/Dockerfile b/tasks/spring-projects__spring-boot-51464/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3991b1b178f0154bf492e0b29ea286751cca37ea --- /dev/null +++ b/tasks/spring-projects__spring-boot-51464/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 61a62d56d8a59f45da2b6365246cfe2928c7cf67 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 61a62d56d8a59f45da2b6365246cfe2928c7cf67 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 61a62d56d8a59f45da2b6365246cfe2928c7cf67 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51464/instruction.md b/tasks/spring-projects__spring-boot-51464/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6a5859d79e2d842c69a2f79db6e150f73343d312 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51464/instruction.md @@ -0,0 +1,51 @@ +# Issue + +**Title:** WritableJson.toByteArray() may corrupt supplementary characters + +## Description + +## What happened? + +`AppendableByteArray` encodes each append call independently with `endOfInput` set to `false`. If the input ends with a high surrogate, `CharsetEncoder` returns `UNDERFLOW` without consuming it. Because that input buffer is then discarded, the high surrogate is lost. The low surrogate in the next append call is malformed on its own and is replaced with `?`. + +`JsonValueWriter` writes strings one UTF-16 code unit at a time, so this affects supplementary characters, including many emoji. For example: + +```java +String emoji = new String(Character.toChars(0x1F600)); +JsonWriter<Map<String, Object>> writer = JsonWriter.standard(); +WritableJson json = writer.write(Map.of("msg", "hello " + emoji)); + +json.toJsonString(); // {"msg":"hello 😀"} +new String(json.toByteArray(), StandardCharsets.UTF_8); // {"msg":"hello ?"} +``` + +Structured logging is also affected. `StructuredLogEncoder` for Logback and `StructuredLogLayout` for Log4j2 use `formatAsBytes`, which reaches `WritableJson.toByteArray(Charset)`. + +This regression was introduced by #49428 in 4.1.0. The previous implementation used an `OutputStreamWriter`, which retains a pending high surrogate across writes, so 4.0.x is not affected. + +## What does this PR change? + +`AppendableByteArray` now retains an unconsumed high surrogate and prepends it to the input from the next append call. + +If no further input arrives, `toByteArray()` encodes the pending surrogate with `endOfInput` set to `true`, so an unpaired high surrogate is replaced instead of being dropped. `reset()` also clears the pending state so it cannot carry over when the cached instance is reused. + +There are no public API changes. + +## Tests + +Added coverage for: + +- A surrogate pair appended as individual characters, using UTF-8 and UTF-16 +- A surrogate pair split across two appended strings +- An unpaired high surrogate +- Supplementary characters written character by character through `WritableJson` + +The `AppendableByteArray` tests compare the result with the output produced by `OutputStreamWriter`. All of these tests fail without this change. + +`:core:spring-boot:check` passes on Linux with JDK 25. + +Related: #51156 fixed a separate regression introduced by #49428. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `61a62d56d8a5`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51464/solution/patch.diff b/tasks/spring-projects__spring-boot-51464/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a9b6edcf4219bacb634f3dcbf7729f44527774d2 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51464/solution/patch.diff @@ -0,0 +1,112 @@ +diff --git a/core/spring-boot/src/main/java/org/springframework/boot/json/AppendableByteArray.java b/core/spring-boot/src/main/java/org/springframework/boot/json/AppendableByteArray.java +index e0274f6be61..430e15ad88e 100644 +--- a/core/spring-boot/src/main/java/org/springframework/boot/json/AppendableByteArray.java ++++ b/core/spring-boot/src/main/java/org/springframework/boot/json/AppendableByteArray.java +@@ -56,6 +56,8 @@ class AppendableByteArray implements Appendable { + + private ByteBuffer out; + ++ private char highSurrogate; ++ + AppendableByteArray(Charset charset) { + this(charset, DEFAULT_INITIAL_SIZE, DEFAULT_EXPANSION_SIZE); + } +@@ -89,8 +91,19 @@ class AppendableByteArray implements Appendable { + } + + private AppendableByteArray append(CharBuffer in) throws IOException { +- CoderResult result = this.encoder.encode(in, this.out, false); ++ if (this.highSurrogate != 0) { ++ CharBuffer pending = CharBuffer.allocate(in.remaining() + 1); ++ pending.put(this.highSurrogate).put(in).flip(); ++ this.highSurrogate = 0; ++ in = pending; ++ } ++ return append(in, false); ++ } ++ ++ private AppendableByteArray append(CharBuffer in, boolean endOfInput) throws IOException { ++ CoderResult result = this.encoder.encode(in, this.out, endOfInput); + if (result.isUnderflow()) { ++ this.highSurrogate = (in.hasRemaining()) ? in.get() : 0; + return this; + } + if (result.isOverflow()) { +@@ -98,13 +111,18 @@ class AppendableByteArray implements Appendable { + this.out = ByteBuffer.allocate(out.capacity() + this.expansionSize); + out.flip(); + this.out.put(out); +- return append(in); ++ return append(in, endOfInput); + } + result.throwException(); + return this; + } + +- byte[] toByteArray() { ++ byte[] toByteArray() throws IOException { ++ if (this.highSurrogate != 0) { ++ CharBuffer in = CharBuffer.wrap(new char[] { this.highSurrogate }); ++ this.highSurrogate = 0; ++ append(in, true); ++ } + this.out.flip(); + int limit = this.out.limit(); + int position = this.out.position(); +@@ -120,6 +138,7 @@ class AppendableByteArray implements Appendable { + private void reset() { + this.out.clear(); + this.encoder.reset(); ++ this.highSurrogate = 0; + } + + static byte[] toByteArray(Charset charset, ThrowingConsumer<Appendable> appendable) throws IOException { +diff --git a/core/spring-boot/src/test/java/org/springframework/boot/json/AppendableByteArrayTests.java b/core/spring-boot/src/test/java/org/springframework/boot/json/AppendableByteArrayTests.java +index 5746991f0a0..46e587128dd 100644 +--- a/core/spring-boot/src/test/java/org/springframework/boot/json/AppendableByteArrayTests.java ++++ b/core/spring-boot/src/test/java/org/springframework/boot/json/AppendableByteArrayTests.java +@@ -90,6 +90,22 @@ class AppendableByteArrayTests { + assertThat(reused).isEqualTo("clean".getBytes(StandardCharsets.UTF_8)); + } + ++ @Test ++ void writesSurrogatePairAppendedAsIndividualChars() throws Exception { ++ assertByteArray(StandardCharsets.UTF_8, (appendable) -> appendable.append('\uD83D').append('\uDE00')); ++ assertByteArray(StandardCharsets.UTF_16, (appendable) -> appendable.append('\uD83D').append('\uDE00')); ++ } ++ ++ @Test ++ void writesSurrogatePairSplitAcrossAppendedStrings() throws Exception { ++ assertByteArray(StandardCharsets.UTF_8, (appendable) -> appendable.append("a\uD83D").append("\uDE00b")); ++ } ++ ++ @Test ++ void writesUnpairedHighSurrogate() throws Exception { ++ assertByteArray(StandardCharsets.UTF_8, (appendable) -> appendable.append('\uD83D')); ++ } ++ + private void assertByteArray(Charset charset, ThrowingConsumer<Appendable> action) throws Exception { + assertByteArray(4, 4, charset, action); + } +diff --git a/core/spring-boot/src/test/java/org/springframework/boot/json/WritableJsonTests.java b/core/spring-boot/src/test/java/org/springframework/boot/json/WritableJsonTests.java +index aa3ea133f04..a9d176c93e3 100644 +--- a/core/spring-boot/src/test/java/org/springframework/boot/json/WritableJsonTests.java ++++ b/core/spring-boot/src/test/java/org/springframework/boot/json/WritableJsonTests.java +@@ -66,6 +66,17 @@ class WritableJsonTests { + assertThat(writable.toByteArray()).isEqualTo("{}".getBytes()); + } + ++ @Test ++ void toByteArrayWhenContentIsAppendedCharByCharWritesSupplementaryCharacters() { ++ String emoji = new String(Character.toChars(0x1F600)); ++ WritableJson writable = (out) -> { ++ for (int i = 0; i < emoji.length(); i++) { ++ out.append(emoji.charAt(i)); ++ } ++ }; ++ assertThat(writable.toByteArray(StandardCharsets.UTF_8)).isEqualTo(emoji.getBytes(StandardCharsets.UTF_8)); ++ } ++ + @Test + void toResourceWritesJson() throws Exception { + File file = new File(this.temp, "out.json"); diff --git a/tasks/spring-projects__spring-boot-51464/solution/solve.sh b/tasks/spring-projects__spring-boot-51464/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51464/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51464/task.toml b/tasks/spring-projects__spring-boot-51464/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..abb3d3f13132ce5f6768615d5c062b694991521e --- /dev/null +++ b/tasks/spring-projects__spring-boot-51464/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51464" +description = "WritableJson.toByteArray() may corrupt supplementary characters" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "61a62d56d8a59f45da2b6365246cfe2928c7cf67" +reference = "https://github.com/spring-projects/spring-boot/pull/51464" +source_access = "auto" +built_at = "2026-11-16T16:09:44.777448+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d88d4c3498421e325a184131f9ac4f5d57451279c6f1a1a326bc7c690996eb14" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-04T13:54:26Z" +diff_format = "unified" +context_files = [ + "core/spring-boot/src/main/java/org/springframework/boot/json/AppendableByteArray.java", + "core/spring-boot/src/test/java/org/springframework/boot/json/AppendableByteArrayTests.java", + "core/spring-boot/src/test/java/org/springframework/boot/json/WritableJsonTests.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 52 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.162030+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3048762893e59f364ca87cab51337b246833ab9bc87901e5dc945caafca788f7" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51464/tests/capture.py b/tasks/spring-projects__spring-boot-51464/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51464/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51464/tests/instruction.md b/tasks/spring-projects__spring-boot-51464/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6a5859d79e2d842c69a2f79db6e150f73343d312 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51464/tests/instruction.md @@ -0,0 +1,51 @@ +# Issue + +**Title:** WritableJson.toByteArray() may corrupt supplementary characters + +## Description + +## What happened? + +`AppendableByteArray` encodes each append call independently with `endOfInput` set to `false`. If the input ends with a high surrogate, `CharsetEncoder` returns `UNDERFLOW` without consuming it. Because that input buffer is then discarded, the high surrogate is lost. The low surrogate in the next append call is malformed on its own and is replaced with `?`. + +`JsonValueWriter` writes strings one UTF-16 code unit at a time, so this affects supplementary characters, including many emoji. For example: + +```java +String emoji = new String(Character.toChars(0x1F600)); +JsonWriter<Map<String, Object>> writer = JsonWriter.standard(); +WritableJson json = writer.write(Map.of("msg", "hello " + emoji)); + +json.toJsonString(); // {"msg":"hello 😀"} +new String(json.toByteArray(), StandardCharsets.UTF_8); // {"msg":"hello ?"} +``` + +Structured logging is also affected. `StructuredLogEncoder` for Logback and `StructuredLogLayout` for Log4j2 use `formatAsBytes`, which reaches `WritableJson.toByteArray(Charset)`. + +This regression was introduced by #49428 in 4.1.0. The previous implementation used an `OutputStreamWriter`, which retains a pending high surrogate across writes, so 4.0.x is not affected. + +## What does this PR change? + +`AppendableByteArray` now retains an unconsumed high surrogate and prepends it to the input from the next append call. + +If no further input arrives, `toByteArray()` encodes the pending surrogate with `endOfInput` set to `true`, so an unpaired high surrogate is replaced instead of being dropped. `reset()` also clears the pending state so it cannot carry over when the cached instance is reused. + +There are no public API changes. + +## Tests + +Added coverage for: + +- A surrogate pair appended as individual characters, using UTF-8 and UTF-16 +- A surrogate pair split across two appended strings +- An unpaired high surrogate +- Supplementary characters written character by character through `WritableJson` + +The `AppendableByteArray` tests compare the result with the output produced by `OutputStreamWriter`. All of these tests fail without this change. + +`:core:spring-boot:check` passes on Linux with JDK 25. + +Related: #51156 fixed a separate regression introduced by #49428. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `61a62d56d8a5`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51464/tests/oracle.patch b/tasks/spring-projects__spring-boot-51464/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a9b6edcf4219bacb634f3dcbf7729f44527774d2 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51464/tests/oracle.patch @@ -0,0 +1,112 @@ +diff --git a/core/spring-boot/src/main/java/org/springframework/boot/json/AppendableByteArray.java b/core/spring-boot/src/main/java/org/springframework/boot/json/AppendableByteArray.java +index e0274f6be61..430e15ad88e 100644 +--- a/core/spring-boot/src/main/java/org/springframework/boot/json/AppendableByteArray.java ++++ b/core/spring-boot/src/main/java/org/springframework/boot/json/AppendableByteArray.java +@@ -56,6 +56,8 @@ class AppendableByteArray implements Appendable { + + private ByteBuffer out; + ++ private char highSurrogate; ++ + AppendableByteArray(Charset charset) { + this(charset, DEFAULT_INITIAL_SIZE, DEFAULT_EXPANSION_SIZE); + } +@@ -89,8 +91,19 @@ class AppendableByteArray implements Appendable { + } + + private AppendableByteArray append(CharBuffer in) throws IOException { +- CoderResult result = this.encoder.encode(in, this.out, false); ++ if (this.highSurrogate != 0) { ++ CharBuffer pending = CharBuffer.allocate(in.remaining() + 1); ++ pending.put(this.highSurrogate).put(in).flip(); ++ this.highSurrogate = 0; ++ in = pending; ++ } ++ return append(in, false); ++ } ++ ++ private AppendableByteArray append(CharBuffer in, boolean endOfInput) throws IOException { ++ CoderResult result = this.encoder.encode(in, this.out, endOfInput); + if (result.isUnderflow()) { ++ this.highSurrogate = (in.hasRemaining()) ? in.get() : 0; + return this; + } + if (result.isOverflow()) { +@@ -98,13 +111,18 @@ class AppendableByteArray implements Appendable { + this.out = ByteBuffer.allocate(out.capacity() + this.expansionSize); + out.flip(); + this.out.put(out); +- return append(in); ++ return append(in, endOfInput); + } + result.throwException(); + return this; + } + +- byte[] toByteArray() { ++ byte[] toByteArray() throws IOException { ++ if (this.highSurrogate != 0) { ++ CharBuffer in = CharBuffer.wrap(new char[] { this.highSurrogate }); ++ this.highSurrogate = 0; ++ append(in, true); ++ } + this.out.flip(); + int limit = this.out.limit(); + int position = this.out.position(); +@@ -120,6 +138,7 @@ class AppendableByteArray implements Appendable { + private void reset() { + this.out.clear(); + this.encoder.reset(); ++ this.highSurrogate = 0; + } + + static byte[] toByteArray(Charset charset, ThrowingConsumer<Appendable> appendable) throws IOException { +diff --git a/core/spring-boot/src/test/java/org/springframework/boot/json/AppendableByteArrayTests.java b/core/spring-boot/src/test/java/org/springframework/boot/json/AppendableByteArrayTests.java +index 5746991f0a0..46e587128dd 100644 +--- a/core/spring-boot/src/test/java/org/springframework/boot/json/AppendableByteArrayTests.java ++++ b/core/spring-boot/src/test/java/org/springframework/boot/json/AppendableByteArrayTests.java +@@ -90,6 +90,22 @@ class AppendableByteArrayTests { + assertThat(reused).isEqualTo("clean".getBytes(StandardCharsets.UTF_8)); + } + ++ @Test ++ void writesSurrogatePairAppendedAsIndividualChars() throws Exception { ++ assertByteArray(StandardCharsets.UTF_8, (appendable) -> appendable.append('\uD83D').append('\uDE00')); ++ assertByteArray(StandardCharsets.UTF_16, (appendable) -> appendable.append('\uD83D').append('\uDE00')); ++ } ++ ++ @Test ++ void writesSurrogatePairSplitAcrossAppendedStrings() throws Exception { ++ assertByteArray(StandardCharsets.UTF_8, (appendable) -> appendable.append("a\uD83D").append("\uDE00b")); ++ } ++ ++ @Test ++ void writesUnpairedHighSurrogate() throws Exception { ++ assertByteArray(StandardCharsets.UTF_8, (appendable) -> appendable.append('\uD83D')); ++ } ++ + private void assertByteArray(Charset charset, ThrowingConsumer<Appendable> action) throws Exception { + assertByteArray(4, 4, charset, action); + } +diff --git a/core/spring-boot/src/test/java/org/springframework/boot/json/WritableJsonTests.java b/core/spring-boot/src/test/java/org/springframework/boot/json/WritableJsonTests.java +index aa3ea133f04..a9d176c93e3 100644 +--- a/core/spring-boot/src/test/java/org/springframework/boot/json/WritableJsonTests.java ++++ b/core/spring-boot/src/test/java/org/springframework/boot/json/WritableJsonTests.java +@@ -66,6 +66,17 @@ class WritableJsonTests { + assertThat(writable.toByteArray()).isEqualTo("{}".getBytes()); + } + ++ @Test ++ void toByteArrayWhenContentIsAppendedCharByCharWritesSupplementaryCharacters() { ++ String emoji = new String(Character.toChars(0x1F600)); ++ WritableJson writable = (out) -> { ++ for (int i = 0; i < emoji.length(); i++) { ++ out.append(emoji.charAt(i)); ++ } ++ }; ++ assertThat(writable.toByteArray(StandardCharsets.UTF_8)).isEqualTo(emoji.getBytes(StandardCharsets.UTF_8)); ++ } ++ + @Test + void toResourceWritesJson() throws Exception { + File file = new File(this.temp, "out.json"); diff --git a/tasks/spring-projects__spring-boot-51464/tests/test.sh b/tasks/spring-projects__spring-boot-51464/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e631417b718174935d2d663146b229d02f09dc28 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51464/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 61a62d56d8a59f45da2b6365246cfe2928c7cf67 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51464/tests/verifier.py b/tasks/spring-projects__spring-boot-51464/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51464/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51484/environment/Dockerfile b/tasks/spring-projects__spring-boot-51484/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4eec5da9e296428b3a976b6cabf68208f24e6cc6 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51484/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2772023050341e293af9fc38b53115e810aa5cfb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2772023050341e293af9fc38b53115e810aa5cfb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2772023050341e293af9fc38b53115e810aa5cfb \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51484/instruction.md b/tasks/spring-projects__spring-boot-51484/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d40b06e0031d70c5ac193aba3847d9aef32b554c --- /dev/null +++ b/tasks/spring-projects__spring-boot-51484/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Make it easier to map MessageSourceProperties onto a user-provided AbstractResourceBasedMessageSource + +## Description + +This adds a `ResourceBasedMessageSourceConfigurer` bean that applies `MessageSourceProperties` to any `AbstractResourceBasedMessageSource`. The auto-configured `ResourceBundleMessageSource` now uses the configurer, while the configurer remains available when no resource bundle is found or when an application defines its own message source. + +The conditions continue to use current-context lookup so parent/child context behavior is preserved. Tests cover configurer availability, configuring a user-defined `ReloadableResourceBundleMessageSource`, and using a user-provided configurer. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `277202305034`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51484/solution/patch.diff b/tasks/spring-projects__spring-boot-51484/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e72d5da1f2be622f084eddcadcef9d0aaf3306ad --- /dev/null +++ b/tasks/spring-projects__spring-boot-51484/solution/patch.diff @@ -0,0 +1,306 @@ +diff --git a/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java b/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java +index 942dffed95c..bf0d706849f 100644 +--- a/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java ++++ b/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java +@@ -16,12 +16,6 @@ + + package org.springframework.boot.autoconfigure.context; + +-import java.io.IOException; +-import java.io.UncheckedIOException; +-import java.time.Duration; +-import java.util.List; +-import java.util.Properties; +- + import org.jspecify.annotations.Nullable; + + import org.springframework.aot.hint.RuntimeHints; +@@ -35,7 +29,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean + import org.springframework.boot.autoconfigure.condition.SearchStrategy; + import org.springframework.boot.autoconfigure.condition.SpringBootCondition; + import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration.MessageSourceRuntimeHints; +-import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration.ResourceBundleCondition; + import org.springframework.boot.context.properties.EnableConfigurationProperties; + import org.springframework.context.MessageSource; + import org.springframework.context.annotation.Bean; +@@ -44,13 +37,10 @@ import org.springframework.context.annotation.Conditional; + import org.springframework.context.annotation.ImportRuntimeHints; + import org.springframework.context.support.AbstractApplicationContext; + import org.springframework.context.support.ResourceBundleMessageSource; +-import org.springframework.core.CollectionFactory; + import org.springframework.core.Ordered; + import org.springframework.core.io.Resource; + import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +-import org.springframework.core.io.support.PropertiesLoaderUtils; + import org.springframework.core.type.AnnotatedTypeMetadata; +-import org.springframework.util.CollectionUtils; + import org.springframework.util.ConcurrentReferenceHashMap; + import org.springframework.util.StringUtils; + +@@ -62,12 +52,11 @@ import org.springframework.util.StringUtils; + * @author Eddú Meléndez + * @author Marc Becker + * @author Misagh Moayyed ++ * @author Henrique (henriquejsza) + * @since 1.5.0 + */ + @AutoConfiguration +-@ConditionalOnMissingBean(name = AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, search = SearchStrategy.CURRENT) + @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) +-@Conditional(ResourceBundleCondition.class) + @EnableConfigurationProperties(MessageSourceProperties.class) + @ImportRuntimeHints(MessageSourceRuntimeHints.class) + public final class MessageSourceAutoConfiguration { +@@ -75,39 +64,19 @@ public final class MessageSourceAutoConfiguration { + private static final Resource[] NO_RESOURCES = {}; + + @Bean +- MessageSource messageSource(MessageSourceProperties properties) { +- ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); +- if (!CollectionUtils.isEmpty(properties.getBasename())) { +- messageSource.setBasenames(properties.getBasename().toArray(new String[0])); +- } +- if (properties.getEncoding() != null) { +- messageSource.setDefaultEncoding(properties.getEncoding().name()); +- } +- messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale()); +- Duration cacheDuration = properties.getCacheDuration(); +- if (cacheDuration != null) { +- messageSource.setCacheMillis(cacheDuration.toMillis()); +- } +- messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat()); +- messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage()); +- messageSource.setCommonMessages(loadCommonMessages(properties.getCommonMessages())); +- return messageSource; ++ @ConditionalOnMissingBean(search = SearchStrategy.CURRENT) ++ ResourceBasedMessageSourceConfigurer resourceBasedMessageSourceConfigurer(MessageSourceProperties properties) { ++ return new ResourceBasedMessageSourceConfigurer(properties); + } + +- private @Nullable Properties loadCommonMessages(@Nullable List<Resource> resources) { +- if (CollectionUtils.isEmpty(resources)) { +- return null; +- } +- Properties properties = CollectionFactory.createSortedProperties(false); +- for (Resource resource : resources) { +- try { +- PropertiesLoaderUtils.fillProperties(properties, resource); +- } +- catch (IOException ex) { +- throw new UncheckedIOException("Failed to load common messages from '%s'".formatted(resource), ex); +- } +- } +- return properties; ++ @Bean ++ @ConditionalOnMissingBean(name = AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, ++ search = SearchStrategy.CURRENT) ++ @Conditional(ResourceBundleCondition.class) ++ ResourceBundleMessageSource messageSource(ResourceBasedMessageSourceConfigurer configurer) { ++ ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); ++ configurer.configure(messageSource); ++ return messageSource; + } + + protected static class ResourceBundleCondition extends SpringBootCondition { +diff --git a/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/ResourceBasedMessageSourceConfigurer.java b/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/ResourceBasedMessageSourceConfigurer.java +new file mode 100644 +index 00000000000..f16d97c426f +--- /dev/null ++++ b/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/ResourceBasedMessageSourceConfigurer.java +@@ -0,0 +1,97 @@ ++/* ++ * Copyright 2012-present the original author or authors. ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * https://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++ ++package org.springframework.boot.autoconfigure.context; ++ ++import java.io.IOException; ++import java.io.UncheckedIOException; ++import java.time.Duration; ++import java.util.List; ++import java.util.Properties; ++ ++import org.jspecify.annotations.Nullable; ++ ++import org.springframework.context.support.AbstractResourceBasedMessageSource; ++import org.springframework.core.CollectionFactory; ++import org.springframework.core.io.Resource; ++import org.springframework.core.io.support.PropertiesLoaderUtils; ++import org.springframework.util.Assert; ++import org.springframework.util.CollectionUtils; ++ ++/** ++ * Configure an {@link AbstractResourceBasedMessageSource} with sensible defaults tuned ++ * using configuration properties. ++ * <p> ++ * Can be injected into application code and used to define a custom message source whose ++ * configuration is based upon that produced by auto-configuration. ++ * ++ * @author Henrique (henriquejsza) ++ * @since 4.2.0 ++ */ ++public class ResourceBasedMessageSourceConfigurer { ++ ++ private final MessageSourceProperties properties; ++ ++ /** ++ * Creates a new configurer that will use the given {@code properties}. ++ * @param properties properties to use ++ */ ++ public ResourceBasedMessageSourceConfigurer(MessageSourceProperties properties) { ++ Assert.notNull(properties, "'properties' must not be null"); ++ this.properties = properties; ++ } ++ ++ /** ++ * Configure the specified message source. The message source can be further tuned and ++ * default settings can be overridden. ++ * @param messageSource the {@link AbstractResourceBasedMessageSource} instance to ++ * configure ++ */ ++ public void configure(AbstractResourceBasedMessageSource messageSource) { ++ Assert.notNull(messageSource, "'messageSource' must not be null"); ++ if (!CollectionUtils.isEmpty(this.properties.getBasename())) { ++ messageSource.setBasenames(this.properties.getBasename().toArray(new String[0])); ++ } ++ if (this.properties.getEncoding() != null) { ++ messageSource.setDefaultEncoding(this.properties.getEncoding().name()); ++ } ++ messageSource.setFallbackToSystemLocale(this.properties.isFallbackToSystemLocale()); ++ Duration cacheDuration = this.properties.getCacheDuration(); ++ if (cacheDuration != null) { ++ messageSource.setCacheMillis(cacheDuration.toMillis()); ++ } ++ messageSource.setAlwaysUseMessageFormat(this.properties.isAlwaysUseMessageFormat()); ++ messageSource.setUseCodeAsDefaultMessage(this.properties.isUseCodeAsDefaultMessage()); ++ messageSource.setCommonMessages(loadCommonMessages(this.properties.getCommonMessages())); ++ } ++ ++ private @Nullable Properties loadCommonMessages(@Nullable List<Resource> resources) { ++ if (CollectionUtils.isEmpty(resources)) { ++ return null; ++ } ++ Properties properties = CollectionFactory.createSortedProperties(false); ++ for (Resource resource : resources) { ++ try { ++ PropertiesLoaderUtils.fillProperties(properties, resource); ++ } ++ catch (IOException ex) { ++ throw new UncheckedIOException("Failed to load common messages from '%s'".formatted(resource), ex); ++ } ++ } ++ return properties; ++ } ++ ++} +diff --git a/core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java b/core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java +index b3b3e9466ea..4b035cf35b5 100644 +--- a/core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java ++++ b/core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java +@@ -40,8 +40,12 @@ import org.springframework.context.NoSuchMessageException; + import org.springframework.context.annotation.Bean; + import org.springframework.context.annotation.Configuration; + import org.springframework.context.annotation.PropertySource; ++import org.springframework.context.support.ReloadableResourceBundleMessageSource; ++import org.springframework.context.support.ResourceBundleMessageSource; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.BDDMockito.then; ++import static org.mockito.Mockito.mock; + + /** + * Tests for {@link MessageSourceAutoConfiguration}. +@@ -53,6 +57,7 @@ import static org.assertj.core.api.Assertions.assertThat; + * @author Marc Becker + * @author Misagh Moayyed + * @author Phillip Webb ++ * @author Henrique (henriquejsza) + */ + class MessageSourceAutoConfigurationTests { + +@@ -65,6 +70,44 @@ class MessageSourceAutoConfigurationTests { + .isEqualTo("Foo message")); + } + ++ @Test ++ void resourceBasedMessageSourceConfigurerIsAvailableWithoutResourceBundle() { ++ this.contextRunner ++ .run((context) -> assertThat(context).hasSingleBean(ResourceBasedMessageSourceConfigurer.class) ++ .doesNotHaveBean(ResourceBundleMessageSource.class)); ++ } ++ ++ @Test ++ void resourceBasedMessageSourceConfigurerCanConfigureUserDefinedMessageSource() { ++ this.contextRunner.withUserConfiguration(CustomResourceBasedMessageSourceConfiguration.class) ++ .withPropertyValues("spring.messages.cache-duration=10s", "spring.messages.fallback-to-system-locale=false", ++ "spring.messages.always-use-message-format=true", ++ "spring.messages.use-code-as-default-message=true") ++ .run((context) -> { ++ assertThat(context).hasSingleBean(ResourceBasedMessageSourceConfigurer.class) ++ .hasSingleBean(ReloadableResourceBundleMessageSource.class); ++ assertThat(context.getBean(ReloadableResourceBundleMessageSource.class)) ++ .hasFieldOrPropertyWithValue("cacheMillis", 10_000L) ++ .hasFieldOrPropertyWithValue("fallbackToSystemLocale", false) ++ .hasFieldOrPropertyWithValue("alwaysUseMessageFormat", true) ++ .hasFieldOrPropertyWithValue("useCodeAsDefaultMessage", true); ++ }); ++ } ++ ++ @Test ++ @WithTestMessagesPropertiesResource ++ void autoConfiguredMessageSourceUsesUserDefinedConfigurer() { ++ ResourceBasedMessageSourceConfigurer configurer = mock(ResourceBasedMessageSourceConfigurer.class); ++ this.contextRunner.withBean(ResourceBasedMessageSourceConfigurer.class, () -> configurer) ++ .withPropertyValues("spring.messages.basename=test/messages") ++ .run((context) -> { ++ assertThat(context).hasSingleBean(ResourceBasedMessageSourceConfigurer.class) ++ .hasSingleBean(ResourceBundleMessageSource.class); ++ assertThat(context.getBean(ResourceBasedMessageSourceConfigurer.class)).isSameAs(configurer); ++ then(configurer).should().configure(context.getBean(ResourceBundleMessageSource.class)); ++ }); ++ } ++ + @Test + @WithTestMessagesPropertiesResource + void propertiesBundleWithSlashIsDetected() { +@@ -256,6 +299,18 @@ class MessageSourceAutoConfigurationTests { + + } + ++ @Configuration(proxyBeanMethods = false) ++ static class CustomResourceBasedMessageSourceConfiguration { ++ ++ @Bean ++ ReloadableResourceBundleMessageSource messageSource(ResourceBasedMessageSourceConfigurer configurer) { ++ ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); ++ configurer.configure(messageSource); ++ return messageSource; ++ } ++ ++ } ++ + @Configuration(proxyBeanMethods = false) + static class CustomBeanNameMessageSourceConfiguration { + +diff --git a/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/internationalization.adoc b/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/internationalization.adoc +index a0e15b4862c..79c0758298b 100644 +--- a/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/internationalization.adoc ++++ b/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/internationalization.adoc +@@ -23,3 +23,5 @@ TIP: The configprop:spring.messages.basename[] property supports a list of locat + The configprop:spring.messages.common-messages[] property supports a list of property file resources. + + See javadoc:org.springframework.boot.autoconfigure.context.MessageSourceProperties[] for more supported options. ++ ++If you need to use a different implementation of javadoc:org.springframework.context.support.AbstractResourceBasedMessageSource[], Spring Boot provides a javadoc:org.springframework.boot.autoconfigure.context.ResourceBasedMessageSourceConfigurer[] bean that you can use to apply the same settings as the auto-configured message source. diff --git a/tasks/spring-projects__spring-boot-51484/solution/solve.sh b/tasks/spring-projects__spring-boot-51484/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51484/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51484/task.toml b/tasks/spring-projects__spring-boot-51484/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..30614df155e0d3646d8dbfd8cbcc1d8ee8bfa57a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51484/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51484" +description = "Make it easier to map MessageSourceProperties onto a user-provided AbstractResourceBasedMessageSource" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "2772023050341e293af9fc38b53115e810aa5cfb" +reference = "https://github.com/spring-projects/spring-boot/pull/51484" +source_access = "auto" +built_at = "2026-11-16T16:09:44.790023+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8d35d711c85db119ead661bccee5bff634b55033a31bbc4b95f71d570a577dd8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-02T14:17:08Z" +diff_format = "unified" +context_files = [ + "core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java", + "core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/ResourceBasedMessageSourceConfigurer.java", + "core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java", + "documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/internationalization.adoc", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 209 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.162628+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3910782ee7ba26c93046dcc2a46570f2ce8154205cf27d9446b98f46dd489cf4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51484/tests/capture.py b/tasks/spring-projects__spring-boot-51484/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51484/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51484/tests/instruction.md b/tasks/spring-projects__spring-boot-51484/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d40b06e0031d70c5ac193aba3847d9aef32b554c --- /dev/null +++ b/tasks/spring-projects__spring-boot-51484/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Make it easier to map MessageSourceProperties onto a user-provided AbstractResourceBasedMessageSource + +## Description + +This adds a `ResourceBasedMessageSourceConfigurer` bean that applies `MessageSourceProperties` to any `AbstractResourceBasedMessageSource`. The auto-configured `ResourceBundleMessageSource` now uses the configurer, while the configurer remains available when no resource bundle is found or when an application defines its own message source. + +The conditions continue to use current-context lookup so parent/child context behavior is preserved. Tests cover configurer availability, configuring a user-defined `ReloadableResourceBundleMessageSource`, and using a user-provided configurer. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `277202305034`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51484/tests/oracle.patch b/tasks/spring-projects__spring-boot-51484/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e72d5da1f2be622f084eddcadcef9d0aaf3306ad --- /dev/null +++ b/tasks/spring-projects__spring-boot-51484/tests/oracle.patch @@ -0,0 +1,306 @@ +diff --git a/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java b/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java +index 942dffed95c..bf0d706849f 100644 +--- a/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java ++++ b/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfiguration.java +@@ -16,12 +16,6 @@ + + package org.springframework.boot.autoconfigure.context; + +-import java.io.IOException; +-import java.io.UncheckedIOException; +-import java.time.Duration; +-import java.util.List; +-import java.util.Properties; +- + import org.jspecify.annotations.Nullable; + + import org.springframework.aot.hint.RuntimeHints; +@@ -35,7 +29,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean + import org.springframework.boot.autoconfigure.condition.SearchStrategy; + import org.springframework.boot.autoconfigure.condition.SpringBootCondition; + import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration.MessageSourceRuntimeHints; +-import org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration.ResourceBundleCondition; + import org.springframework.boot.context.properties.EnableConfigurationProperties; + import org.springframework.context.MessageSource; + import org.springframework.context.annotation.Bean; +@@ -44,13 +37,10 @@ import org.springframework.context.annotation.Conditional; + import org.springframework.context.annotation.ImportRuntimeHints; + import org.springframework.context.support.AbstractApplicationContext; + import org.springframework.context.support.ResourceBundleMessageSource; +-import org.springframework.core.CollectionFactory; + import org.springframework.core.Ordered; + import org.springframework.core.io.Resource; + import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +-import org.springframework.core.io.support.PropertiesLoaderUtils; + import org.springframework.core.type.AnnotatedTypeMetadata; +-import org.springframework.util.CollectionUtils; + import org.springframework.util.ConcurrentReferenceHashMap; + import org.springframework.util.StringUtils; + +@@ -62,12 +52,11 @@ import org.springframework.util.StringUtils; + * @author Eddú Meléndez + * @author Marc Becker + * @author Misagh Moayyed ++ * @author Henrique (henriquejsza) + * @since 1.5.0 + */ + @AutoConfiguration +-@ConditionalOnMissingBean(name = AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, search = SearchStrategy.CURRENT) + @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) +-@Conditional(ResourceBundleCondition.class) + @EnableConfigurationProperties(MessageSourceProperties.class) + @ImportRuntimeHints(MessageSourceRuntimeHints.class) + public final class MessageSourceAutoConfiguration { +@@ -75,39 +64,19 @@ public final class MessageSourceAutoConfiguration { + private static final Resource[] NO_RESOURCES = {}; + + @Bean +- MessageSource messageSource(MessageSourceProperties properties) { +- ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); +- if (!CollectionUtils.isEmpty(properties.getBasename())) { +- messageSource.setBasenames(properties.getBasename().toArray(new String[0])); +- } +- if (properties.getEncoding() != null) { +- messageSource.setDefaultEncoding(properties.getEncoding().name()); +- } +- messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale()); +- Duration cacheDuration = properties.getCacheDuration(); +- if (cacheDuration != null) { +- messageSource.setCacheMillis(cacheDuration.toMillis()); +- } +- messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat()); +- messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage()); +- messageSource.setCommonMessages(loadCommonMessages(properties.getCommonMessages())); +- return messageSource; ++ @ConditionalOnMissingBean(search = SearchStrategy.CURRENT) ++ ResourceBasedMessageSourceConfigurer resourceBasedMessageSourceConfigurer(MessageSourceProperties properties) { ++ return new ResourceBasedMessageSourceConfigurer(properties); + } + +- private @Nullable Properties loadCommonMessages(@Nullable List<Resource> resources) { +- if (CollectionUtils.isEmpty(resources)) { +- return null; +- } +- Properties properties = CollectionFactory.createSortedProperties(false); +- for (Resource resource : resources) { +- try { +- PropertiesLoaderUtils.fillProperties(properties, resource); +- } +- catch (IOException ex) { +- throw new UncheckedIOException("Failed to load common messages from '%s'".formatted(resource), ex); +- } +- } +- return properties; ++ @Bean ++ @ConditionalOnMissingBean(name = AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, ++ search = SearchStrategy.CURRENT) ++ @Conditional(ResourceBundleCondition.class) ++ ResourceBundleMessageSource messageSource(ResourceBasedMessageSourceConfigurer configurer) { ++ ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); ++ configurer.configure(messageSource); ++ return messageSource; + } + + protected static class ResourceBundleCondition extends SpringBootCondition { +diff --git a/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/ResourceBasedMessageSourceConfigurer.java b/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/ResourceBasedMessageSourceConfigurer.java +new file mode 100644 +index 00000000000..f16d97c426f +--- /dev/null ++++ b/core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/ResourceBasedMessageSourceConfigurer.java +@@ -0,0 +1,97 @@ ++/* ++ * Copyright 2012-present the original author or authors. ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * https://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++ ++package org.springframework.boot.autoconfigure.context; ++ ++import java.io.IOException; ++import java.io.UncheckedIOException; ++import java.time.Duration; ++import java.util.List; ++import java.util.Properties; ++ ++import org.jspecify.annotations.Nullable; ++ ++import org.springframework.context.support.AbstractResourceBasedMessageSource; ++import org.springframework.core.CollectionFactory; ++import org.springframework.core.io.Resource; ++import org.springframework.core.io.support.PropertiesLoaderUtils; ++import org.springframework.util.Assert; ++import org.springframework.util.CollectionUtils; ++ ++/** ++ * Configure an {@link AbstractResourceBasedMessageSource} with sensible defaults tuned ++ * using configuration properties. ++ * <p> ++ * Can be injected into application code and used to define a custom message source whose ++ * configuration is based upon that produced by auto-configuration. ++ * ++ * @author Henrique (henriquejsza) ++ * @since 4.2.0 ++ */ ++public class ResourceBasedMessageSourceConfigurer { ++ ++ private final MessageSourceProperties properties; ++ ++ /** ++ * Creates a new configurer that will use the given {@code properties}. ++ * @param properties properties to use ++ */ ++ public ResourceBasedMessageSourceConfigurer(MessageSourceProperties properties) { ++ Assert.notNull(properties, "'properties' must not be null"); ++ this.properties = properties; ++ } ++ ++ /** ++ * Configure the specified message source. The message source can be further tuned and ++ * default settings can be overridden. ++ * @param messageSource the {@link AbstractResourceBasedMessageSource} instance to ++ * configure ++ */ ++ public void configure(AbstractResourceBasedMessageSource messageSource) { ++ Assert.notNull(messageSource, "'messageSource' must not be null"); ++ if (!CollectionUtils.isEmpty(this.properties.getBasename())) { ++ messageSource.setBasenames(this.properties.getBasename().toArray(new String[0])); ++ } ++ if (this.properties.getEncoding() != null) { ++ messageSource.setDefaultEncoding(this.properties.getEncoding().name()); ++ } ++ messageSource.setFallbackToSystemLocale(this.properties.isFallbackToSystemLocale()); ++ Duration cacheDuration = this.properties.getCacheDuration(); ++ if (cacheDuration != null) { ++ messageSource.setCacheMillis(cacheDuration.toMillis()); ++ } ++ messageSource.setAlwaysUseMessageFormat(this.properties.isAlwaysUseMessageFormat()); ++ messageSource.setUseCodeAsDefaultMessage(this.properties.isUseCodeAsDefaultMessage()); ++ messageSource.setCommonMessages(loadCommonMessages(this.properties.getCommonMessages())); ++ } ++ ++ private @Nullable Properties loadCommonMessages(@Nullable List<Resource> resources) { ++ if (CollectionUtils.isEmpty(resources)) { ++ return null; ++ } ++ Properties properties = CollectionFactory.createSortedProperties(false); ++ for (Resource resource : resources) { ++ try { ++ PropertiesLoaderUtils.fillProperties(properties, resource); ++ } ++ catch (IOException ex) { ++ throw new UncheckedIOException("Failed to load common messages from '%s'".formatted(resource), ex); ++ } ++ } ++ return properties; ++ } ++ ++} +diff --git a/core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java b/core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java +index b3b3e9466ea..4b035cf35b5 100644 +--- a/core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java ++++ b/core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/context/MessageSourceAutoConfigurationTests.java +@@ -40,8 +40,12 @@ import org.springframework.context.NoSuchMessageException; + import org.springframework.context.annotation.Bean; + import org.springframework.context.annotation.Configuration; + import org.springframework.context.annotation.PropertySource; ++import org.springframework.context.support.ReloadableResourceBundleMessageSource; ++import org.springframework.context.support.ResourceBundleMessageSource; + + import static org.assertj.core.api.Assertions.assertThat; ++import static org.mockito.BDDMockito.then; ++import static org.mockito.Mockito.mock; + + /** + * Tests for {@link MessageSourceAutoConfiguration}. +@@ -53,6 +57,7 @@ import static org.assertj.core.api.Assertions.assertThat; + * @author Marc Becker + * @author Misagh Moayyed + * @author Phillip Webb ++ * @author Henrique (henriquejsza) + */ + class MessageSourceAutoConfigurationTests { + +@@ -65,6 +70,44 @@ class MessageSourceAutoConfigurationTests { + .isEqualTo("Foo message")); + } + ++ @Test ++ void resourceBasedMessageSourceConfigurerIsAvailableWithoutResourceBundle() { ++ this.contextRunner ++ .run((context) -> assertThat(context).hasSingleBean(ResourceBasedMessageSourceConfigurer.class) ++ .doesNotHaveBean(ResourceBundleMessageSource.class)); ++ } ++ ++ @Test ++ void resourceBasedMessageSourceConfigurerCanConfigureUserDefinedMessageSource() { ++ this.contextRunner.withUserConfiguration(CustomResourceBasedMessageSourceConfiguration.class) ++ .withPropertyValues("spring.messages.cache-duration=10s", "spring.messages.fallback-to-system-locale=false", ++ "spring.messages.always-use-message-format=true", ++ "spring.messages.use-code-as-default-message=true") ++ .run((context) -> { ++ assertThat(context).hasSingleBean(ResourceBasedMessageSourceConfigurer.class) ++ .hasSingleBean(ReloadableResourceBundleMessageSource.class); ++ assertThat(context.getBean(ReloadableResourceBundleMessageSource.class)) ++ .hasFieldOrPropertyWithValue("cacheMillis", 10_000L) ++ .hasFieldOrPropertyWithValue("fallbackToSystemLocale", false) ++ .hasFieldOrPropertyWithValue("alwaysUseMessageFormat", true) ++ .hasFieldOrPropertyWithValue("useCodeAsDefaultMessage", true); ++ }); ++ } ++ ++ @Test ++ @WithTestMessagesPropertiesResource ++ void autoConfiguredMessageSourceUsesUserDefinedConfigurer() { ++ ResourceBasedMessageSourceConfigurer configurer = mock(ResourceBasedMessageSourceConfigurer.class); ++ this.contextRunner.withBean(ResourceBasedMessageSourceConfigurer.class, () -> configurer) ++ .withPropertyValues("spring.messages.basename=test/messages") ++ .run((context) -> { ++ assertThat(context).hasSingleBean(ResourceBasedMessageSourceConfigurer.class) ++ .hasSingleBean(ResourceBundleMessageSource.class); ++ assertThat(context.getBean(ResourceBasedMessageSourceConfigurer.class)).isSameAs(configurer); ++ then(configurer).should().configure(context.getBean(ResourceBundleMessageSource.class)); ++ }); ++ } ++ + @Test + @WithTestMessagesPropertiesResource + void propertiesBundleWithSlashIsDetected() { +@@ -256,6 +299,18 @@ class MessageSourceAutoConfigurationTests { + + } + ++ @Configuration(proxyBeanMethods = false) ++ static class CustomResourceBasedMessageSourceConfiguration { ++ ++ @Bean ++ ReloadableResourceBundleMessageSource messageSource(ResourceBasedMessageSourceConfigurer configurer) { ++ ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); ++ configurer.configure(messageSource); ++ return messageSource; ++ } ++ ++ } ++ + @Configuration(proxyBeanMethods = false) + static class CustomBeanNameMessageSourceConfiguration { + +diff --git a/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/internationalization.adoc b/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/internationalization.adoc +index a0e15b4862c..79c0758298b 100644 +--- a/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/internationalization.adoc ++++ b/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/internationalization.adoc +@@ -23,3 +23,5 @@ TIP: The configprop:spring.messages.basename[] property supports a list of locat + The configprop:spring.messages.common-messages[] property supports a list of property file resources. + + See javadoc:org.springframework.boot.autoconfigure.context.MessageSourceProperties[] for more supported options. ++ ++If you need to use a different implementation of javadoc:org.springframework.context.support.AbstractResourceBasedMessageSource[], Spring Boot provides a javadoc:org.springframework.boot.autoconfigure.context.ResourceBasedMessageSourceConfigurer[] bean that you can use to apply the same settings as the auto-configured message source. diff --git a/tasks/spring-projects__spring-boot-51484/tests/test.sh b/tasks/spring-projects__spring-boot-51484/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a04de2f5a829dae97764e057efbd846bacc82da6 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51484/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 2772023050341e293af9fc38b53115e810aa5cfb > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51484/tests/verifier.py b/tasks/spring-projects__spring-boot-51484/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51484/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51507/environment/Dockerfile b/tasks/spring-projects__spring-boot-51507/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6762b5a1200752148910e6583e7b11b8c5b969ae --- /dev/null +++ b/tasks/spring-projects__spring-boot-51507/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1eedb9c9694c66bd93cf7c61058adebb857f96ed 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1eedb9c9694c66bd93cf7c61058adebb857f96ed \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1eedb9c9694c66bd93cf7c61058adebb857f96ed \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51507/instruction.md b/tasks/spring-projects__spring-boot-51507/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..304ac453621ccbb6d843d202ce230cbb0ca6f935 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51507/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Fix new warnings from NullAway 0.14.1 + +## Description + +These changes address new warnings emitted by NullAway 0.14.1 (just released). I'm not 100% confident in them, and some were done with the assistance of AI, so they should be reviewed carefully. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1eedb9c9694c`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51507/solution/patch.diff b/tasks/spring-projects__spring-boot-51507/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..990cb3ca3fe1ee501932aaf1e398686576329212 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51507/solution/patch.diff @@ -0,0 +1,37 @@ +diff --git a/core/spring-boot/src/main/java/org/springframework/boot/support/SpringApplicationJsonEnvironmentPostProcessor.java b/core/spring-boot/src/main/java/org/springframework/boot/support/SpringApplicationJsonEnvironmentPostProcessor.java +index 16747285d2b..3d134be4907 100644 +--- a/core/spring-boot/src/main/java/org/springframework/boot/support/SpringApplicationJsonEnvironmentPostProcessor.java ++++ b/core/spring-boot/src/main/java/org/springframework/boot/support/SpringApplicationJsonEnvironmentPostProcessor.java +@@ -128,7 +128,7 @@ public class SpringApplicationJsonEnvironmentPostProcessor implements Environmen + } + + @SuppressWarnings("unchecked") +- private void extract(String name, Map<String, Object> result, Object value) { ++ private void extract(String name, Map<String, Object> result, @Nullable Object value) { + if (value instanceof Map<?, ?> map) { + if (CollectionUtils.isEmpty(map)) { + result.put(name, value); +diff --git a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/SecurityService.java b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/SecurityService.java +index cbcc94d792d..026971dbb99 100644 +--- a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/SecurityService.java ++++ b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/SecurityService.java +@@ -139,6 +139,7 @@ class SecurityService { + Assert.state(keys != null, "'keys' must not be null"); + for (Object key : keys) { + Map<?, ?> tokenKey = (Map<?, ?>) key; ++ Assert.state(tokenKey != null, "'tokenKey' must not be null"); + tokenKeys.put((String) tokenKey.get("kid"), (String) tokenKey.get("value")); + } + return tokenKeys; +diff --git a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/servlet/SecurityService.java b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/servlet/SecurityService.java +index 9078796dbef..6ec4cd96a8b 100644 +--- a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/servlet/SecurityService.java ++++ b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/servlet/SecurityService.java +@@ -118,6 +118,7 @@ class SecurityService { + Assert.state(keys != null, "'keys' must not be null"); + for (Object key : keys) { + Map<?, ?> tokenKey = (Map<?, ?>) key; ++ Assert.state(tokenKey != null, "'tokenKey' must not be null"); + tokenKeys.put((String) tokenKey.get("kid"), (String) tokenKey.get("value")); + } + return tokenKeys; diff --git a/tasks/spring-projects__spring-boot-51507/solution/solve.sh b/tasks/spring-projects__spring-boot-51507/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51507/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51507/task.toml b/tasks/spring-projects__spring-boot-51507/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..76fe906827608b887094132ee399152c0ab63c86 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51507/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51507" +description = "Fix new warnings from NullAway 0.14.1" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "1eedb9c9694c66bd93cf7c61058adebb857f96ed" +reference = "https://github.com/spring-projects/spring-boot/pull/51507" +source_access = "auto" +built_at = "2026-11-16T16:09:44.779214+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7e5ac091f39cfc54e424a364be46508a7d9e48645152001992891e748d91b6c3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-04T11:59:04Z" +diff_format = "unified" +context_files = [ + "core/spring-boot/src/main/java/org/springframework/boot/support/SpringApplicationJsonEnvironmentPostProcessor.java", + "module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/SecurityService.java", + "module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/servlet/SecurityService.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.163219+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ae84c14e9425eebde9a51108708f4405f10660341c6ecd7a9481a1a88b7ae3e3" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51507/tests/capture.py b/tasks/spring-projects__spring-boot-51507/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51507/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51507/tests/instruction.md b/tasks/spring-projects__spring-boot-51507/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..304ac453621ccbb6d843d202ce230cbb0ca6f935 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51507/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Fix new warnings from NullAway 0.14.1 + +## Description + +These changes address new warnings emitted by NullAway 0.14.1 (just released). I'm not 100% confident in them, and some were done with the assistance of AI, so they should be reviewed carefully. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1eedb9c9694c`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51507/tests/oracle.patch b/tasks/spring-projects__spring-boot-51507/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..990cb3ca3fe1ee501932aaf1e398686576329212 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51507/tests/oracle.patch @@ -0,0 +1,37 @@ +diff --git a/core/spring-boot/src/main/java/org/springframework/boot/support/SpringApplicationJsonEnvironmentPostProcessor.java b/core/spring-boot/src/main/java/org/springframework/boot/support/SpringApplicationJsonEnvironmentPostProcessor.java +index 16747285d2b..3d134be4907 100644 +--- a/core/spring-boot/src/main/java/org/springframework/boot/support/SpringApplicationJsonEnvironmentPostProcessor.java ++++ b/core/spring-boot/src/main/java/org/springframework/boot/support/SpringApplicationJsonEnvironmentPostProcessor.java +@@ -128,7 +128,7 @@ public class SpringApplicationJsonEnvironmentPostProcessor implements Environmen + } + + @SuppressWarnings("unchecked") +- private void extract(String name, Map<String, Object> result, Object value) { ++ private void extract(String name, Map<String, Object> result, @Nullable Object value) { + if (value instanceof Map<?, ?> map) { + if (CollectionUtils.isEmpty(map)) { + result.put(name, value); +diff --git a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/SecurityService.java b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/SecurityService.java +index cbcc94d792d..026971dbb99 100644 +--- a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/SecurityService.java ++++ b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/SecurityService.java +@@ -139,6 +139,7 @@ class SecurityService { + Assert.state(keys != null, "'keys' must not be null"); + for (Object key : keys) { + Map<?, ?> tokenKey = (Map<?, ?>) key; ++ Assert.state(tokenKey != null, "'tokenKey' must not be null"); + tokenKeys.put((String) tokenKey.get("kid"), (String) tokenKey.get("value")); + } + return tokenKeys; +diff --git a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/servlet/SecurityService.java b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/servlet/SecurityService.java +index 9078796dbef..6ec4cd96a8b 100644 +--- a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/servlet/SecurityService.java ++++ b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/servlet/SecurityService.java +@@ -118,6 +118,7 @@ class SecurityService { + Assert.state(keys != null, "'keys' must not be null"); + for (Object key : keys) { + Map<?, ?> tokenKey = (Map<?, ?>) key; ++ Assert.state(tokenKey != null, "'tokenKey' must not be null"); + tokenKeys.put((String) tokenKey.get("kid"), (String) tokenKey.get("value")); + } + return tokenKeys; diff --git a/tasks/spring-projects__spring-boot-51507/tests/test.sh b/tasks/spring-projects__spring-boot-51507/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c055de78491ad0390a84ccf1bbcc2ec3f5fac1a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51507/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 1eedb9c9694c66bd93cf7c61058adebb857f96ed > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51507/tests/verifier.py b/tasks/spring-projects__spring-boot-51507/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51507/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51519/environment/Dockerfile b/tasks/spring-projects__spring-boot-51519/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d210e066835e80f0e16bc8938072acee2724f358 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51519/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a833fe58f9fb10b7f4dc3051e80dcdae52870a20 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a833fe58f9fb10b7f4dc3051e80dcdae52870a20 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a833fe58f9fb10b7f4dc3051e80dcdae52870a20 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51519/instruction.md b/tasks/spring-projects__spring-boot-51519/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f161a822e0020ead80aeae14e197582127af1b39 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51519/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Layer temp file is not deleted when layer creation fails + +## Description + +`ImageBuildpack.ExportedLayers.createLayerFile` creates two temp files: the intermediate source tar (`create-builder-scratch-source-*`) and the layer file (`create-builder-scratch-*`). The source tar is deleted in a `finally` block, but the layer file is only deleted later, in `apply()`, on the success path. + +If the copy from the source tar into the layer file fails — for example when a malformed entry name is rejected by the `Assert.state` check, or on an I/O error — the exception propagates out of `createLayerFile` and the just-created layer file is never deleted. The existing test `resolveWhenEntryWouldWriteOutsideOfDestinationThrowsException` hits exactly this path and leaves an orphaned `create-builder-scratch-*` file behind in the temp directory on every run. + +This wraps the copy in a `try/catch (IOException | RuntimeException)` that deletes the layer file and rethrows, suppressing any secondary failure from the delete — the same approach used for `ExportedImageTar` in #51117. + +The new test reuses the malformed-entry scenario and asserts that no `create-builder-scratch-*` temp files remain after resolution fails. It fails without the production change and passes with it, and `checkFormat`, `checkstyleMain` and `checkstyleTest` for the module all pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a833fe58f9fb`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51519/solution/patch.diff b/tasks/spring-projects__spring-boot-51519/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..13a39d780ca1961cd97c4c84d7be27c3c36dfd33 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51519/solution/patch.diff @@ -0,0 +1,110 @@ +diff --git a/buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java b/buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java +index 4e943015525..c596ade2acd 100644 +--- a/buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java ++++ b/buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java +@@ -49,6 +49,7 @@ import org.springframework.util.StreamUtils; + * + * @author Scott Frederick + * @author Phillip Webb ++ * @author Junhwan Choi + */ + final class ImageBuildpack implements Buildpack { + +@@ -137,22 +138,17 @@ final class ImageBuildpack implements Buildpack { + tarArchive.writeTo(out); + } + Path layerFile = Files.createTempFile("create-builder-scratch-", null); +- try (TarArchiveOutputStream out = new TarArchiveOutputStream(Files.newOutputStream(layerFile))) { +- try (TarArchiveInputStream in = new TarArchiveInputStream(Files.newInputStream(sourceTarFile))) { +- out.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); +- TarArchiveEntry entry = in.getNextEntry(); +- while (entry != null) { +- String entryName = entry.getName(); +- Path entryPath = Path.of(entryName); +- Assert.state(entryPath.toAbsolutePath().equals(entryPath.toAbsolutePath().normalize()), +- () -> "Malformed zip entry name '%s'".formatted(entryName)); +- out.putArchiveEntry(entry); +- StreamUtils.copy(in, out); +- out.closeArchiveEntry(); +- entry = in.getNextEntry(); +- } +- out.finish(); ++ try { ++ writeLayerFile(layerFile, sourceTarFile); ++ } ++ catch (IOException | RuntimeException ex) { ++ try { ++ Files.deleteIfExists(layerFile); ++ } ++ catch (IOException suppressed) { ++ ex.addSuppressed(suppressed); + } ++ throw ex; + } + return layerFile; + } +@@ -161,6 +157,26 @@ final class ImageBuildpack implements Buildpack { + } + } + ++ private void writeLayerFile(Path layerFile, Path sourceTarFile) throws IOException { ++ try (TarArchiveOutputStream out = new TarArchiveOutputStream(Files.newOutputStream(layerFile))) { ++ try (TarArchiveInputStream in = new TarArchiveInputStream(Files.newInputStream(sourceTarFile))) { ++ out.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); ++ TarArchiveEntry entry = in.getNextEntry(); ++ while (entry != null) { ++ String entryName = entry.getName(); ++ Path entryPath = Path.of(entryName); ++ Assert.state(entryPath.toAbsolutePath().equals(entryPath.toAbsolutePath().normalize()), ++ () -> "Malformed zip entry name '%s'".formatted(entryName)); ++ out.putArchiveEntry(entry); ++ StreamUtils.copy(in, out); ++ out.closeArchiveEntry(); ++ entry = in.getNextEntry(); ++ } ++ out.finish(); ++ } ++ } ++ } ++ + void apply(IOConsumer<Layer> layers) throws IOException { + for (Path path : this.layerFiles) { + layers.accept(Layer.fromTarArchive((out) -> { +diff --git a/buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java b/buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java +index 4fcd192a3f3..fc61e9b33e5 100644 +--- a/buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java ++++ b/buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java +@@ -61,6 +61,7 @@ import static org.mockito.Mockito.mock; + * + * @author Scott Frederick + * @author Phillip Webb ++ * @author Junhwan Choi + */ + class ImageBuildpackTests extends AbstractJsonTests { + +@@ -200,6 +201,25 @@ class ImageBuildpackTests extends AbstractJsonTests { + .withMessage("Malformed zip entry name '../cnb/'"); + } + ++ @Test ++ void resolveWhenLayerCreationFailsDeletesLayerTempFiles() throws Exception { ++ File tempDir = new File(System.getProperty("java.io.tmpdir")); ++ Set<String> tempsBefore = listTempFileNames(tempDir, "create-builder-scratch-"); ++ Image image = Image.of(getContent("buildpack-image.json")); ++ ImageReference imageReference = ImageReference.of("example/buildpack1:latest"); ++ BuildpackResolverContext resolverContext = mock(BuildpackResolverContext.class); ++ given(resolverContext.getBuildpackLayersMetadata()).willReturn(BuildpackLayersMetadata.fromJson("{}")); ++ given(resolverContext.fetchImage(eq(imageReference), eq(ImageType.BUILDPACK))).willReturn(image); ++ willAnswer((invocation) -> withMockLayers(invocation, "..")).given(resolverContext) ++ .exportImageLayers(eq(imageReference), any()); ++ BuildpackReference reference = BuildpackReference.of("example/buildpack1"); ++ assertThatIllegalStateException().isThrownBy(() -> ImageBuildpack.resolve(resolverContext, reference)) ++ .withMessage("Malformed zip entry name '../cnb/'"); ++ Set<String> tempsAfter = new HashSet<>(listTempFileNames(tempDir, "create-builder-scratch-")); ++ tempsAfter.removeAll(tempsBefore); ++ assertThat(tempsAfter).as("layer temp files must be deleted when layer creation fails").isEmpty(); ++ } ++ + @Test + void resolveDeletesIntermediateSourceTarTempFiles() throws Exception { + File tempDir = new File(System.getProperty("java.io.tmpdir")); diff --git a/tasks/spring-projects__spring-boot-51519/solution/solve.sh b/tasks/spring-projects__spring-boot-51519/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51519/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51519/task.toml b/tasks/spring-projects__spring-boot-51519/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0e26fcac1965238dfecf281480ee280f4307dc66 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51519/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51519" +description = "Layer temp file is not deleted when layer creation fails" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "a833fe58f9fb10b7f4dc3051e80dcdae52870a20" +reference = "https://github.com/spring-projects/spring-boot/pull/51519" +source_access = "auto" +built_at = "2026-11-16T16:09:44.780633+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6808c5a94b64c1b9a38cdafc1cda46cbc49f1ce6bfe5df69970b9119e8d171f5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-04T10:47:26Z" +diff_format = "unified" +context_files = [ + "buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java", + "buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 66 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.163815+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:447e73c6f217cb8a64270b059b98ae33d64e2b1c19ed91b42a4c6f24ae0714ab" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51519/tests/capture.py b/tasks/spring-projects__spring-boot-51519/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51519/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51519/tests/instruction.md b/tasks/spring-projects__spring-boot-51519/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f161a822e0020ead80aeae14e197582127af1b39 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51519/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Layer temp file is not deleted when layer creation fails + +## Description + +`ImageBuildpack.ExportedLayers.createLayerFile` creates two temp files: the intermediate source tar (`create-builder-scratch-source-*`) and the layer file (`create-builder-scratch-*`). The source tar is deleted in a `finally` block, but the layer file is only deleted later, in `apply()`, on the success path. + +If the copy from the source tar into the layer file fails — for example when a malformed entry name is rejected by the `Assert.state` check, or on an I/O error — the exception propagates out of `createLayerFile` and the just-created layer file is never deleted. The existing test `resolveWhenEntryWouldWriteOutsideOfDestinationThrowsException` hits exactly this path and leaves an orphaned `create-builder-scratch-*` file behind in the temp directory on every run. + +This wraps the copy in a `try/catch (IOException | RuntimeException)` that deletes the layer file and rethrows, suppressing any secondary failure from the delete — the same approach used for `ExportedImageTar` in #51117. + +The new test reuses the malformed-entry scenario and asserts that no `create-builder-scratch-*` temp files remain after resolution fails. It fails without the production change and passes with it, and `checkFormat`, `checkstyleMain` and `checkstyleTest` for the module all pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a833fe58f9fb`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51519/tests/oracle.patch b/tasks/spring-projects__spring-boot-51519/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..13a39d780ca1961cd97c4c84d7be27c3c36dfd33 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51519/tests/oracle.patch @@ -0,0 +1,110 @@ +diff --git a/buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java b/buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java +index 4e943015525..c596ade2acd 100644 +--- a/buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java ++++ b/buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/ImageBuildpack.java +@@ -49,6 +49,7 @@ import org.springframework.util.StreamUtils; + * + * @author Scott Frederick + * @author Phillip Webb ++ * @author Junhwan Choi + */ + final class ImageBuildpack implements Buildpack { + +@@ -137,22 +138,17 @@ final class ImageBuildpack implements Buildpack { + tarArchive.writeTo(out); + } + Path layerFile = Files.createTempFile("create-builder-scratch-", null); +- try (TarArchiveOutputStream out = new TarArchiveOutputStream(Files.newOutputStream(layerFile))) { +- try (TarArchiveInputStream in = new TarArchiveInputStream(Files.newInputStream(sourceTarFile))) { +- out.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); +- TarArchiveEntry entry = in.getNextEntry(); +- while (entry != null) { +- String entryName = entry.getName(); +- Path entryPath = Path.of(entryName); +- Assert.state(entryPath.toAbsolutePath().equals(entryPath.toAbsolutePath().normalize()), +- () -> "Malformed zip entry name '%s'".formatted(entryName)); +- out.putArchiveEntry(entry); +- StreamUtils.copy(in, out); +- out.closeArchiveEntry(); +- entry = in.getNextEntry(); +- } +- out.finish(); ++ try { ++ writeLayerFile(layerFile, sourceTarFile); ++ } ++ catch (IOException | RuntimeException ex) { ++ try { ++ Files.deleteIfExists(layerFile); ++ } ++ catch (IOException suppressed) { ++ ex.addSuppressed(suppressed); + } ++ throw ex; + } + return layerFile; + } +@@ -161,6 +157,26 @@ final class ImageBuildpack implements Buildpack { + } + } + ++ private void writeLayerFile(Path layerFile, Path sourceTarFile) throws IOException { ++ try (TarArchiveOutputStream out = new TarArchiveOutputStream(Files.newOutputStream(layerFile))) { ++ try (TarArchiveInputStream in = new TarArchiveInputStream(Files.newInputStream(sourceTarFile))) { ++ out.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); ++ TarArchiveEntry entry = in.getNextEntry(); ++ while (entry != null) { ++ String entryName = entry.getName(); ++ Path entryPath = Path.of(entryName); ++ Assert.state(entryPath.toAbsolutePath().equals(entryPath.toAbsolutePath().normalize()), ++ () -> "Malformed zip entry name '%s'".formatted(entryName)); ++ out.putArchiveEntry(entry); ++ StreamUtils.copy(in, out); ++ out.closeArchiveEntry(); ++ entry = in.getNextEntry(); ++ } ++ out.finish(); ++ } ++ } ++ } ++ + void apply(IOConsumer<Layer> layers) throws IOException { + for (Path path : this.layerFiles) { + layers.accept(Layer.fromTarArchive((out) -> { +diff --git a/buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java b/buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java +index 4fcd192a3f3..fc61e9b33e5 100644 +--- a/buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java ++++ b/buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/ImageBuildpackTests.java +@@ -61,6 +61,7 @@ import static org.mockito.Mockito.mock; + * + * @author Scott Frederick + * @author Phillip Webb ++ * @author Junhwan Choi + */ + class ImageBuildpackTests extends AbstractJsonTests { + +@@ -200,6 +201,25 @@ class ImageBuildpackTests extends AbstractJsonTests { + .withMessage("Malformed zip entry name '../cnb/'"); + } + ++ @Test ++ void resolveWhenLayerCreationFailsDeletesLayerTempFiles() throws Exception { ++ File tempDir = new File(System.getProperty("java.io.tmpdir")); ++ Set<String> tempsBefore = listTempFileNames(tempDir, "create-builder-scratch-"); ++ Image image = Image.of(getContent("buildpack-image.json")); ++ ImageReference imageReference = ImageReference.of("example/buildpack1:latest"); ++ BuildpackResolverContext resolverContext = mock(BuildpackResolverContext.class); ++ given(resolverContext.getBuildpackLayersMetadata()).willReturn(BuildpackLayersMetadata.fromJson("{}")); ++ given(resolverContext.fetchImage(eq(imageReference), eq(ImageType.BUILDPACK))).willReturn(image); ++ willAnswer((invocation) -> withMockLayers(invocation, "..")).given(resolverContext) ++ .exportImageLayers(eq(imageReference), any()); ++ BuildpackReference reference = BuildpackReference.of("example/buildpack1"); ++ assertThatIllegalStateException().isThrownBy(() -> ImageBuildpack.resolve(resolverContext, reference)) ++ .withMessage("Malformed zip entry name '../cnb/'"); ++ Set<String> tempsAfter = new HashSet<>(listTempFileNames(tempDir, "create-builder-scratch-")); ++ tempsAfter.removeAll(tempsBefore); ++ assertThat(tempsAfter).as("layer temp files must be deleted when layer creation fails").isEmpty(); ++ } ++ + @Test + void resolveDeletesIntermediateSourceTarTempFiles() throws Exception { + File tempDir = new File(System.getProperty("java.io.tmpdir")); diff --git a/tasks/spring-projects__spring-boot-51519/tests/test.sh b/tasks/spring-projects__spring-boot-51519/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d536af4593c605ec148e890d5b1df966fad0c1d6 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51519/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a833fe58f9fb10b7f4dc3051e80dcdae52870a20 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51519/tests/verifier.py b/tasks/spring-projects__spring-boot-51519/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51519/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51523/environment/Dockerfile b/tasks/spring-projects__spring-boot-51523/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7e9358e0028fae08247aa3eda0a918abc6c71bec --- /dev/null +++ b/tasks/spring-projects__spring-boot-51523/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin eaaa8334bc89ac6bc640448950b82413062ba8be 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard eaaa8334bc89ac6bc640448950b82413062ba8be \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base eaaa8334bc89ac6bc640448950b82413062ba8be \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51523/instruction.md b/tasks/spring-projects__spring-boot-51523/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3c0e216b516e16d22909ea025e3d0d6c0e2f2dce --- /dev/null +++ b/tasks/spring-projects__spring-boot-51523/instruction.md @@ -0,0 +1,65 @@ +# Issue + +**Title:** Bump actions/setup-java from 5 to 6 + +## Description + +Bumps [actions/setup-java](https://github.com/actions/setup-java) from 5 to 6. +<details> +<summary>Release notes</summary> +<p><em>Sourced from <a href="https://github.com/actions/setup-java/releases">actions/setup-java's releases</a>.</em></p> +<blockquote> +<h2>v6.0.0</h2> +<h2>What's Changed</h2> +<ul> +<li>dist: Migrate from Zulu Discovery API to Azul Metadata API by <a href="https://github.com/jameswald"><code>@​jameswald</code></a> in <a href="">actions/setup-java#1010</a></li> +<li>feat: add .mvn/extensions.xml to Maven cache key pattern by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> with <a href="https://github.com/Copilot"><code>@​Copilot</code></a> in <a href="">actions/setup-java#1041</a></li> +<li>Migrate to ESM and upgrade dependencies by <a href="https://github.com/priyagupta108"><code>@​priyagupta108</code></a> in <a href="">actions/setup-java#1078</a></li> +<li>Map Zulu x86 architecture to i686 for Azul Metadata API by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1079</a></li> +<li>Rename jdkFile input to jdk-file with deprecated alias by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1083</a></li> +<li>Infer distribution from asdf .tool-versions vendor prefix by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1084</a></li> +<li>Add Maven compiler problem matcher for javac diagnostics by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1086</a></li> +<li>feat: expose cache-primary-key output (<a href="">#597</a>) by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1088</a></li> +<li>docs: clarify V6 ESM migration is not a user-facing breaking change by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1090</a></li> +<li>Support multi-field Java versions like <code>18.0.1.1</code> by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1092</a></li> +<li>docs: document seeding the Maven cache for plugin dependencies by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1094</a></li> +<li>docs: clarify Maven cache paths and key hash inputs by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1096</a></li> +<li>Support pinning java-version as "latest" by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1093</a></li> +<li>chore(deps-dev): bump eslint from 10.6.0 to 10.7.0 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1101</a></li> +<li>chore(deps-dev): bump eslint-plugin-n from 18.2.1 to 18.2.2 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1103</a></li> +<li>chore(deps-dev): bump prettier from 3.9.4 to 3.9.5 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1105</a></li> +<li>chore(deps): bump actions/checkout from 6 to 7 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1106</a></li> +<li>chore(deps-dev): bump <code>@​types/node</code> from 26.1.0 to 26.1.1 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1104</a></li> +<li>dist: Cover Tencent Kona JDK 25 by <a href="https://github.com/johnshajiang"><code>@​johnshajiang</code></a> in <a href="">actions/setup-java#1108</a></li> +<li>chore(deps-dev): bump typescript from 6.0.3 to 7.0.2 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1102</a></li> +<li>Preserve Maven toolchains across repeated setup-java runs (<a href="">#1099</a>) by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1111</a></li> +<li>dist: Support Liberica NIK (<a href="">#878</a>) by <a href="https://github.com/asm0dey"><code>@​asm0dey</code></a> in <a href="">actions/setup-java#1112</a></li> +<li>Fix template injection (zizmor alert <a href="">#118</a>) in e2e-versions.yml by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> with <a href="https://github.com/Copilot"><code>@​Copilot</code></a> in <a href="">actions/setup-java#1114</a></li> +<li>Fix template injection in e2e-versions.yml (zizmor alert <a href="">#122</a>) by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> with <a href="https://github.com/Copilot"><code>@​Copilot</code></a> in <a href="">actions/setup-java#1120</a></li> +<li>Disable persisted checkout credentials in e2e workflow by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> with <a href="https://github.com/Copilot"><code>@​Copilot</code></a> in <a href="">actions/setup-java#1115</a></li> +<li>feat: Update recommended configuration for GPG signing by <a href="https://github.com/wetneb"><code>@​wetneb</code></a> in <a href="">actions/setup-java#608</a></li> +<li>Cache Maven and Gradle wrapper distributions separately from the dependency cache by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1097</a></li> +<li>Consolidate cache-dependency-path e2e workflow and add maven/sbt coverage by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1124</a></li> +<li>Use gpg.passphraseEnvName instead of the deprecated gpg.passphrase server by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1123</a></li> +<li>Extract repeated directory-check assertions into check-dir.sh helper by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1127</a></li> +<li>Consolidate duplicate jobs in e2e-versions workflow by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1125</a></li> +<li>Use YAML anchors to reduce boilerplate in e2e-versions workflow by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1126</a></li> +<li>Updated msft json for now by <a href="https://github.com/jmjaffe37"><code>@​jmjaffe37</code></a> in <a href="">actions/setup-java#1129</a></li> +<li>Document missing action inputs in README by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1130</a></li> +<li>chore(deps): bump <code>@​actions/cache</code> to 6.2.0 by <a href="https://github.com/philip-gai"><code>@​philip-gai</code></a> in <a href="">actions/setup-java#1128</a></li> +<li>Add an option to disable Java problem matchers by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1133</a></li> +<li>docs: update setup-java examples by <a href="https://github.com/HarithaVattikuti"><code>@​HarithaVattikuti</code></a> in <a href="">actions/setup-java#1131</a></li> +<li>Clarify credential environment variable inputs by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1134</a></li> +<li>chore(deps-dev): bump <code>@​typescript-eslint/eslint-plugin</code> from 8.63.0 to 8.64.0 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1135</a></li> +<li>chore(deps): bump actions/setup-python from 6 to 7 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1143</a></li> +<li>chore(deps): bump fast-xml-parser from 5.9.3 to 5.10.1 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1142</a></li> +<li>chore(deps-dev): bump <code>@​typescript-eslint/parser</code> from 8.64.0 to 8.65.0 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1138</a></li> +<li>chore(deps-dev): bump lint-staged from 17.0.8 to 17.2.0 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1136</a></li> +<li>chore(deps-dev): bump typescript from 6.0.3 to 7.0.2 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1137</a></li> +<li>chore(deps): fix npm audited vulnerabilities by <a href="https://github.com/mhoffrog"><code>@​mhoffrog</code></a> in <a href="">actions/setup-java#1140</a></li> +<li>Fix formatting issues in README.md by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1144</a></li> +<li>Remediate npm audit findings and rebuild distributions by <a href="https://github.com/brunoborges"><code>@​brunob + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `eaaa8334bc89`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51523/solution/patch.diff b/tasks/spring-projects__spring-boot-51523/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d4b230abd945c45ee5f6490098f78e93f610784e --- /dev/null +++ b/tasks/spring-projects__spring-boot-51523/solution/patch.diff @@ -0,0 +1,39 @@ +diff --git a/.github/actions/prepare-gradle-build/action.yml b/.github/actions/prepare-gradle-build/action.yml +index 508c88ae787..4aa26a582ab 100644 +--- a/.github/actions/prepare-gradle-build/action.yml ++++ b/.github/actions/prepare-gradle-build/action.yml +@@ -34,7 +34,7 @@ runs: + tool-cache: true + docker-images: false + - name: Set Up Java +- uses: actions/setup-java@v5 ++ uses: actions/setup-java@v6 + with: + distribution: ${{ inputs.java-early-access == 'true' && 'temurin' || (inputs.java-distribution || 'liberica') }} + java-version: | +diff --git a/.github/actions/publish-gradle-plugin/action.yml b/.github/actions/publish-gradle-plugin/action.yml +index e01647c9efd..4bbf9b00ed7 100644 +--- a/.github/actions/publish-gradle-plugin/action.yml ++++ b/.github/actions/publish-gradle-plugin/action.yml +@@ -28,7 +28,7 @@ runs: + shell: bash + run: jf rt download --spec ${{ format('{0}/artifacts.spec', github.action_path) }} --spec-vars 'buildName=${{ format('spring-boot-{0}', inputs.plugin-version) }};buildNumber=${{ inputs.build-number }}' + - name: Set Up Java +- uses: actions/setup-java@v5 ++ uses: actions/setup-java@v6 + with: + distribution: 'liberica' + java-version: '17' +diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml +index f610eefff8a..2ee7c016910 100644 +--- a/.github/workflows/verify.yml ++++ b/.github/workflows/verify.yml +@@ -49,7 +49,7 @@ jobs: + path: send-notification + sparse-checkout: .github/actions/send-notification + - name: Set Up Java +- uses: actions/setup-java@v5 ++ uses: actions/setup-java@v6 + with: + distribution: 'liberica' + java-version: 17 diff --git a/tasks/spring-projects__spring-boot-51523/solution/solve.sh b/tasks/spring-projects__spring-boot-51523/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51523/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51523/task.toml b/tasks/spring-projects__spring-boot-51523/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0cc83be80a039cc9bd42a5c64f0d4bf9bd1f5a9d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51523/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51523" +description = "Bump actions/setup-java from 5 to 6" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "eaaa8334bc89ac6bc640448950b82413062ba8be" +reference = "https://github.com/spring-projects/spring-boot/pull/51523" +source_access = "auto" +built_at = "2026-11-16T16:09:44.799952+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:477bf7aeb32485ee5ab4fa2a4b4917db74e755c8ee9a44c98bfea3c92a140488" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-02T06:07:10Z" +diff_format = "unified" +context_files = [ + ".github/actions/prepare-gradle-build/action.yml", + ".github/actions/publish-gradle-plugin/action.yml", + ".github/workflows/verify.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.164451+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:79d030a8ba87bfc5d8be6e56e3d2fd54afdcb08b4f60c5a84e732d2ca6251651" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51523/tests/capture.py b/tasks/spring-projects__spring-boot-51523/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51523/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51523/tests/instruction.md b/tasks/spring-projects__spring-boot-51523/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3c0e216b516e16d22909ea025e3d0d6c0e2f2dce --- /dev/null +++ b/tasks/spring-projects__spring-boot-51523/tests/instruction.md @@ -0,0 +1,65 @@ +# Issue + +**Title:** Bump actions/setup-java from 5 to 6 + +## Description + +Bumps [actions/setup-java](https://github.com/actions/setup-java) from 5 to 6. +<details> +<summary>Release notes</summary> +<p><em>Sourced from <a href="https://github.com/actions/setup-java/releases">actions/setup-java's releases</a>.</em></p> +<blockquote> +<h2>v6.0.0</h2> +<h2>What's Changed</h2> +<ul> +<li>dist: Migrate from Zulu Discovery API to Azul Metadata API by <a href="https://github.com/jameswald"><code>@​jameswald</code></a> in <a href="">actions/setup-java#1010</a></li> +<li>feat: add .mvn/extensions.xml to Maven cache key pattern by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> with <a href="https://github.com/Copilot"><code>@​Copilot</code></a> in <a href="">actions/setup-java#1041</a></li> +<li>Migrate to ESM and upgrade dependencies by <a href="https://github.com/priyagupta108"><code>@​priyagupta108</code></a> in <a href="">actions/setup-java#1078</a></li> +<li>Map Zulu x86 architecture to i686 for Azul Metadata API by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1079</a></li> +<li>Rename jdkFile input to jdk-file with deprecated alias by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1083</a></li> +<li>Infer distribution from asdf .tool-versions vendor prefix by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1084</a></li> +<li>Add Maven compiler problem matcher for javac diagnostics by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1086</a></li> +<li>feat: expose cache-primary-key output (<a href="">#597</a>) by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1088</a></li> +<li>docs: clarify V6 ESM migration is not a user-facing breaking change by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1090</a></li> +<li>Support multi-field Java versions like <code>18.0.1.1</code> by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1092</a></li> +<li>docs: document seeding the Maven cache for plugin dependencies by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1094</a></li> +<li>docs: clarify Maven cache paths and key hash inputs by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1096</a></li> +<li>Support pinning java-version as "latest" by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1093</a></li> +<li>chore(deps-dev): bump eslint from 10.6.0 to 10.7.0 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1101</a></li> +<li>chore(deps-dev): bump eslint-plugin-n from 18.2.1 to 18.2.2 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1103</a></li> +<li>chore(deps-dev): bump prettier from 3.9.4 to 3.9.5 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1105</a></li> +<li>chore(deps): bump actions/checkout from 6 to 7 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1106</a></li> +<li>chore(deps-dev): bump <code>@​types/node</code> from 26.1.0 to 26.1.1 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1104</a></li> +<li>dist: Cover Tencent Kona JDK 25 by <a href="https://github.com/johnshajiang"><code>@​johnshajiang</code></a> in <a href="">actions/setup-java#1108</a></li> +<li>chore(deps-dev): bump typescript from 6.0.3 to 7.0.2 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1102</a></li> +<li>Preserve Maven toolchains across repeated setup-java runs (<a href="">#1099</a>) by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1111</a></li> +<li>dist: Support Liberica NIK (<a href="">#878</a>) by <a href="https://github.com/asm0dey"><code>@​asm0dey</code></a> in <a href="">actions/setup-java#1112</a></li> +<li>Fix template injection (zizmor alert <a href="">#118</a>) in e2e-versions.yml by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> with <a href="https://github.com/Copilot"><code>@​Copilot</code></a> in <a href="">actions/setup-java#1114</a></li> +<li>Fix template injection in e2e-versions.yml (zizmor alert <a href="">#122</a>) by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> with <a href="https://github.com/Copilot"><code>@​Copilot</code></a> in <a href="">actions/setup-java#1120</a></li> +<li>Disable persisted checkout credentials in e2e workflow by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> with <a href="https://github.com/Copilot"><code>@​Copilot</code></a> in <a href="">actions/setup-java#1115</a></li> +<li>feat: Update recommended configuration for GPG signing by <a href="https://github.com/wetneb"><code>@​wetneb</code></a> in <a href="">actions/setup-java#608</a></li> +<li>Cache Maven and Gradle wrapper distributions separately from the dependency cache by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1097</a></li> +<li>Consolidate cache-dependency-path e2e workflow and add maven/sbt coverage by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1124</a></li> +<li>Use gpg.passphraseEnvName instead of the deprecated gpg.passphrase server by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1123</a></li> +<li>Extract repeated directory-check assertions into check-dir.sh helper by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1127</a></li> +<li>Consolidate duplicate jobs in e2e-versions workflow by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1125</a></li> +<li>Use YAML anchors to reduce boilerplate in e2e-versions workflow by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1126</a></li> +<li>Updated msft json for now by <a href="https://github.com/jmjaffe37"><code>@​jmjaffe37</code></a> in <a href="">actions/setup-java#1129</a></li> +<li>Document missing action inputs in README by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1130</a></li> +<li>chore(deps): bump <code>@​actions/cache</code> to 6.2.0 by <a href="https://github.com/philip-gai"><code>@​philip-gai</code></a> in <a href="">actions/setup-java#1128</a></li> +<li>Add an option to disable Java problem matchers by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1133</a></li> +<li>docs: update setup-java examples by <a href="https://github.com/HarithaVattikuti"><code>@​HarithaVattikuti</code></a> in <a href="">actions/setup-java#1131</a></li> +<li>Clarify credential environment variable inputs by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1134</a></li> +<li>chore(deps-dev): bump <code>@​typescript-eslint/eslint-plugin</code> from 8.63.0 to 8.64.0 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1135</a></li> +<li>chore(deps): bump actions/setup-python from 6 to 7 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1143</a></li> +<li>chore(deps): bump fast-xml-parser from 5.9.3 to 5.10.1 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1142</a></li> +<li>chore(deps-dev): bump <code>@​typescript-eslint/parser</code> from 8.64.0 to 8.65.0 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1138</a></li> +<li>chore(deps-dev): bump lint-staged from 17.0.8 to 17.2.0 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1136</a></li> +<li>chore(deps-dev): bump typescript from 6.0.3 to 7.0.2 by <a href="https://github.com/dependabot"><code>@​dependabot</code></a>[bot] in <a href="">actions/setup-java#1137</a></li> +<li>chore(deps): fix npm audited vulnerabilities by <a href="https://github.com/mhoffrog"><code>@​mhoffrog</code></a> in <a href="">actions/setup-java#1140</a></li> +<li>Fix formatting issues in README.md by <a href="https://github.com/brunoborges"><code>@​brunoborges</code></a> in <a href="">actions/setup-java#1144</a></li> +<li>Remediate npm audit findings and rebuild distributions by <a href="https://github.com/brunoborges"><code>@​brunob + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `eaaa8334bc89`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51523/tests/oracle.patch b/tasks/spring-projects__spring-boot-51523/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d4b230abd945c45ee5f6490098f78e93f610784e --- /dev/null +++ b/tasks/spring-projects__spring-boot-51523/tests/oracle.patch @@ -0,0 +1,39 @@ +diff --git a/.github/actions/prepare-gradle-build/action.yml b/.github/actions/prepare-gradle-build/action.yml +index 508c88ae787..4aa26a582ab 100644 +--- a/.github/actions/prepare-gradle-build/action.yml ++++ b/.github/actions/prepare-gradle-build/action.yml +@@ -34,7 +34,7 @@ runs: + tool-cache: true + docker-images: false + - name: Set Up Java +- uses: actions/setup-java@v5 ++ uses: actions/setup-java@v6 + with: + distribution: ${{ inputs.java-early-access == 'true' && 'temurin' || (inputs.java-distribution || 'liberica') }} + java-version: | +diff --git a/.github/actions/publish-gradle-plugin/action.yml b/.github/actions/publish-gradle-plugin/action.yml +index e01647c9efd..4bbf9b00ed7 100644 +--- a/.github/actions/publish-gradle-plugin/action.yml ++++ b/.github/actions/publish-gradle-plugin/action.yml +@@ -28,7 +28,7 @@ runs: + shell: bash + run: jf rt download --spec ${{ format('{0}/artifacts.spec', github.action_path) }} --spec-vars 'buildName=${{ format('spring-boot-{0}', inputs.plugin-version) }};buildNumber=${{ inputs.build-number }}' + - name: Set Up Java +- uses: actions/setup-java@v5 ++ uses: actions/setup-java@v6 + with: + distribution: 'liberica' + java-version: '17' +diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml +index f610eefff8a..2ee7c016910 100644 +--- a/.github/workflows/verify.yml ++++ b/.github/workflows/verify.yml +@@ -49,7 +49,7 @@ jobs: + path: send-notification + sparse-checkout: .github/actions/send-notification + - name: Set Up Java +- uses: actions/setup-java@v5 ++ uses: actions/setup-java@v6 + with: + distribution: 'liberica' + java-version: 17 diff --git a/tasks/spring-projects__spring-boot-51523/tests/test.sh b/tasks/spring-projects__spring-boot-51523/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c2c78919d7cc14824b02e1c087371d0c614cb9dd --- /dev/null +++ b/tasks/spring-projects__spring-boot-51523/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace eaaa8334bc89ac6bc640448950b82413062ba8be > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51523/tests/verifier.py b/tasks/spring-projects__spring-boot-51523/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51523/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51526/environment/Dockerfile b/tasks/spring-projects__spring-boot-51526/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dac0b26ec3e6534ff8e5fc87d9f5d817d2a9fa9e --- /dev/null +++ b/tasks/spring-projects__spring-boot-51526/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 05383f774baa0b6e601f9f77da3a7f3b041ed8c4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 05383f774baa0b6e601f9f77da3a7f3b041ed8c4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 05383f774baa0b6e601f9f77da3a7f3b041ed8c4 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51526/instruction.md b/tasks/spring-projects__spring-boot-51526/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e58af2ac98622bc689919c2126c6df1cd19d1259 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51526/instruction.md @@ -0,0 +1,67 @@ +# Issue + +**Title:** Bump @antora/cli from 3.2.0-rc.3 to 3.2.0 in /antora + +## Description + +Bumps [@antora/cli](https://gitlab.com/antora/antora/tree/HEAD/packages/cli) from 3.2.0-rc.3 to 3.2.0. +<details> +<summary>Changelog</summary> +<p><em>Sourced from <a href="https://gitlab.com/antora/antora/blob/main/CHANGELOG.adoc">@​antora/cli's changelog</a>.</em></p> +<blockquote> +<p>== 3.2.0 (2026-08-29)</p> +<p>=== Changed</p> +<ul> +<li><em>site-generator</em>: Log original error message when Antora extension is suspected to be Asciidoctor extension</li> +<li>Upgrade js-yaml to 5.3.x (playbook-builder, content-aggregator, ui-loader)</li> +</ul> +<p>=== Fixed</p> +<ul> +<li>Don't crash if pub property not set on start page</li> +</ul> +</blockquote> +</details> +<details> +<summary>Commits</summary> +<ul> +<li><a href="https://gitlab.com/antora/antora/commit/85665d02158ec725565b527bde9b3dbf1fa5b827"><code>85665d0</code></a> release 3.2.0</li> +<li><a href="https://gitlab.com/antora/antora/commit/79f23d7f8dc32f9c9f28453704f014caa88ab3d2"><code>79f23d7</code></a> add Node.js 26 to test matrix</li> +<li><a href="https://gitlab.com/antora/antora/commit/04c952a6222ccb72333e85ce38ada7bb1b947f03"><code>04c952a</code></a> upgrade xmldom</li> +<li><a href="https://gitlab.com/antora/antora/commit/4b923ed6583579e84be3407152b609da6f58402d"><code>4b923ed</code></a> update declared supported versions of Node.js</li> +<li><a href="https://gitlab.com/antora/antora/commit/ecc28eb57e78b8762c3fbecd1d5bcf6995ecf49e"><code>ecc28eb</code></a> update release date on what's new page</li> +<li><a href="https://gitlab.com/antora/antora/commit/03b788c0ad11af3a671313a32c8f33c1dfdb4a55"><code>03b788c</code></a> add missing entries from what's new page</li> +<li><a href="https://gitlab.com/antora/antora/commit/058f436d96f5a4d2aec2746105e09844d15961ed"><code>058f436</code></a> apply pending formatting to example code</li> +<li><a href="https://gitlab.com/antora/antora/commit/9452cca3881404bf808299322033957589f47f70"><code>9452cca</code></a> upgrade js-yaml</li> +<li><a href="https://gitlab.com/antora/antora/commit/621fe9397de807c132741b401247f462aceb2296"><code>621fe93</code></a> refresh dependency lock file</li> +<li><a href="https://gitlab.com/antora/antora/commit/57a244e0b94f3c3bfad43ac4cfed815b8be95218"><code>57a244e</code></a> remove unused images</li> +<li>Additional commits viewable in <a href="https://gitlab.com/antora/antora/compare/v3.2.0-rc.3...v3.2.0">compare view</a></li> +</ul> +</details> +<br /> + +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=@antora/cli&package-manager=npm_and_yarn&previous-version=3.2.0-rc.3&new-version=3.2.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +<details> +<summary>Dependabot commands and options</summary> +<br /> + +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) + +</details> + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `05383f774baa`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51526/solution/patch.diff b/tasks/spring-projects__spring-boot-51526/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1c2b00befc0d0a21e7bb2e4729b40866a93e4dc0 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51526/solution/patch.diff @@ -0,0 +1,156 @@ +diff --git a/antora/package-lock.json b/antora/package-lock.json +index 8d384c39390..64e323431d5 100644 +--- a/antora/package-lock.json ++++ b/antora/package-lock.json +@@ -6,7 +6,7 @@ + "": { + "dependencies": { + "@antora/atlas-extension": "1.0.0-alpha.5", +- "@antora/cli": "3.2.0-rc.3", ++ "@antora/cli": "3.2.0", + "@antora/site-generator": "3.2.0-rc.3", + "@asciidoctor/tabs": "1.0.0-beta.6", + "@springio/antora-extensions": "1.14.13", +@@ -58,13 +58,13 @@ + } + }, + "node_modules/@antora/cli": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/cli/-/cli-3.2.0-rc.3.tgz", +- "integrity": "sha512-MQJBkv+UyQgFNybEyFYlUUKmezZg9TMdR/qE5o6gjw7ytt5a1c6gmNdrbrIlGCHYurojInwhJXKON9NujxK0dA==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/cli/-/cli-3.2.0.tgz", ++ "integrity": "sha512-bJ5Vl+FMH52xm2jxdcbrEUN3aeoIYj5NGzLGsVwIPewM0RXee0kckbToAFnU0EK0Uw07cBomiJ5hwVELex0/ug==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/logger": "3.2.0-rc.3", +- "@antora/playbook-builder": "3.2.0-rc.3", ++ "@antora/logger": "3.2.0", ++ "@antora/playbook-builder": "3.2.0", + "@antora/user-require-helper": "~3.0", + "commander": "~14.0" + }, +@@ -75,56 +75,6 @@ + "node": ">=20.0.0" + } + }, +- "node_modules/@antora/cli/node_modules/@antora/logger": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.3.tgz", +- "integrity": "sha512-UJDfQQDL0x9kOdB926b/3NwpE7zlExTleJcwd1P0Smjd1Cgy7LI5idLgzxydB+Rn5UhL5c3SmxhDFDfMyg9A+w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@antora/expand-path-helper": "~3.0", +- "pino": "~10.3" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, +- "node_modules/@antora/cli/node_modules/@antora/playbook-builder": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/playbook-builder/-/playbook-builder-3.2.0-rc.3.tgz", +- "integrity": "sha512-UQGkIk13kPwFR0WMmoQDe1rdGJy6fs7Dj/OkZ3+n5Uo1OncBrg4kGyo/EFjIe9nU2rjC8zkpmQ1o39NWUNeV2w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@iarna/toml": "~2.2", +- "convict": "~6.2", +- "js-yaml": "~4.2", +- "json5": "~2.2" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, +- "node_modules/@antora/cli/node_modules/js-yaml": { +- "version": "4.2.0", +- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz", +- "integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==", +- "funding": [ +- { +- "type": "github", +- "url": "https://github.com/sponsors/puzrin" +- }, +- { +- "type": "github", +- "url": "https://github.com/sponsors/nodeca" +- } +- ], +- "license": "MIT", +- "dependencies": { +- "argparse": "^2.0.1" +- }, +- "bin": { +- "js-yaml": "bin/js-yaml.js" +- } +- }, + "node_modules/@antora/content-aggregator": { + "version": "3.2.0-rc.3", + "resolved": "https://registry.npmjs.org/@antora/content-aggregator/-/content-aggregator-3.2.0-rc.3.tgz", +@@ -251,9 +201,9 @@ + } + }, + "node_modules/@antora/logger": { +- "version": "3.2.0-rc.2", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.2.tgz", +- "integrity": "sha512-qNCOxx1WbleUaFzeyZ3kbRL2Hf4hN6CbvvRY7w45+iwH/ErejAR5iDtH2sCWbRJGYUt2hUbJ6FmpFFkXProaeA==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0.tgz", ++ "integrity": "sha512-2+bTFjYOuwoWjgtIfpf8bit6OuizI7O8RnXsHzX2y6/PBbm9K8ulvmqtnFk8933P5ILTZ/NSrbgvcFz5BXrY8A==", + "license": "MPL-2.0", + "dependencies": { + "@antora/expand-path-helper": "~3.0", +@@ -302,14 +252,14 @@ + } + }, + "node_modules/@antora/playbook-builder": { +- "version": "3.2.0-rc.2", +- "resolved": "https://registry.npmjs.org/@antora/playbook-builder/-/playbook-builder-3.2.0-rc.2.tgz", +- "integrity": "sha512-Fk/Ko/HYGGfDfIMZydyHidc66ASPyb+Wi0pzI4hTsK4PP8cP4NR2Rat9njAIUoMTuwsBogBGKH9uJ9l5bj/G4Q==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/playbook-builder/-/playbook-builder-3.2.0.tgz", ++ "integrity": "sha512-mAOrE+vDRa0wUcTc3JIZWvEai69vZ1kx6CvZi8ugSYrcWbZxNDp+R5pYWRX9037dZ5e6s5hKKGV503thm9BiSw==", + "license": "MPL-2.0", + "dependencies": { + "@iarna/toml": "~2.2", + "convict": "~6.2", +- "js-yaml": "~4.2", ++ "js-yaml": "~5.4", + "json5": "~2.2" + }, + "engines": { +@@ -317,9 +267,9 @@ + } + }, + "node_modules/@antora/playbook-builder/node_modules/js-yaml": { +- "version": "4.2.0", +- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz", +- "integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==", ++ "version": "5.4.1", ++ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.4.1.tgz", ++ "integrity": "sha512-28R/k+NAjeuf7+CKlTxWZVExJGwVVLwY06DgEnOMz2gEpfNkDcD7QvyiVPT0xy0XXhU8vHsd4Ot42OOPdJG7dQ==", + "funding": [ + { + "type": "github", +@@ -335,7 +285,7 @@ + "argparse": "^2.0.1" + }, + "bin": { +- "js-yaml": "bin/js-yaml.js" ++ "js-yaml": "bin/js-yaml.mjs" + } + }, + "node_modules/@antora/redirect-producer": { +diff --git a/antora/package.json b/antora/package.json +index a2a7665d396..6772baec36a 100644 +--- a/antora/package.json ++++ b/antora/package.json +@@ -3,7 +3,7 @@ + "antora": "node npm/antora.js" + }, + "dependencies": { +- "@antora/cli": "3.2.0-rc.3", ++ "@antora/cli": "3.2.0", + "@antora/site-generator": "3.2.0-rc.3", + "@antora/atlas-extension": "1.0.0-alpha.5", + "@springio/antora-extensions": "1.14.13", diff --git a/tasks/spring-projects__spring-boot-51526/solution/solve.sh b/tasks/spring-projects__spring-boot-51526/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51526/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51526/task.toml b/tasks/spring-projects__spring-boot-51526/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ce51c9103a99b342e9355980391a2ba5e7595abf --- /dev/null +++ b/tasks/spring-projects__spring-boot-51526/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51526" +description = "Bump @antora/cli from 3.2.0-rc.3 to 3.2.0 in /antora" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "05383f774baa0b6e601f9f77da3a7f3b041ed8c4" +reference = "https://github.com/spring-projects/spring-boot/pull/51526" +source_access = "auto" +built_at = "2026-11-16T16:09:44.796704+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7fb556a334df4f0f45a0c641eee5e1eb39ffe2349d897aef44bc0c4e451a2127" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-02T06:28:01Z" +diff_format = "unified" +context_files = [ + "antora/package-lock.json", + "antora/package.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 86 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.164993+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b7b99964845411304acbe7a6758a8631410d9fdfd9686f61a9dee13a348f9978" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51526/tests/capture.py b/tasks/spring-projects__spring-boot-51526/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51526/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51526/tests/instruction.md b/tasks/spring-projects__spring-boot-51526/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e58af2ac98622bc689919c2126c6df1cd19d1259 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51526/tests/instruction.md @@ -0,0 +1,67 @@ +# Issue + +**Title:** Bump @antora/cli from 3.2.0-rc.3 to 3.2.0 in /antora + +## Description + +Bumps [@antora/cli](https://gitlab.com/antora/antora/tree/HEAD/packages/cli) from 3.2.0-rc.3 to 3.2.0. +<details> +<summary>Changelog</summary> +<p><em>Sourced from <a href="https://gitlab.com/antora/antora/blob/main/CHANGELOG.adoc">@​antora/cli's changelog</a>.</em></p> +<blockquote> +<p>== 3.2.0 (2026-08-29)</p> +<p>=== Changed</p> +<ul> +<li><em>site-generator</em>: Log original error message when Antora extension is suspected to be Asciidoctor extension</li> +<li>Upgrade js-yaml to 5.3.x (playbook-builder, content-aggregator, ui-loader)</li> +</ul> +<p>=== Fixed</p> +<ul> +<li>Don't crash if pub property not set on start page</li> +</ul> +</blockquote> +</details> +<details> +<summary>Commits</summary> +<ul> +<li><a href="https://gitlab.com/antora/antora/commit/85665d02158ec725565b527bde9b3dbf1fa5b827"><code>85665d0</code></a> release 3.2.0</li> +<li><a href="https://gitlab.com/antora/antora/commit/79f23d7f8dc32f9c9f28453704f014caa88ab3d2"><code>79f23d7</code></a> add Node.js 26 to test matrix</li> +<li><a href="https://gitlab.com/antora/antora/commit/04c952a6222ccb72333e85ce38ada7bb1b947f03"><code>04c952a</code></a> upgrade xmldom</li> +<li><a href="https://gitlab.com/antora/antora/commit/4b923ed6583579e84be3407152b609da6f58402d"><code>4b923ed</code></a> update declared supported versions of Node.js</li> +<li><a href="https://gitlab.com/antora/antora/commit/ecc28eb57e78b8762c3fbecd1d5bcf6995ecf49e"><code>ecc28eb</code></a> update release date on what's new page</li> +<li><a href="https://gitlab.com/antora/antora/commit/03b788c0ad11af3a671313a32c8f33c1dfdb4a55"><code>03b788c</code></a> add missing entries from what's new page</li> +<li><a href="https://gitlab.com/antora/antora/commit/058f436d96f5a4d2aec2746105e09844d15961ed"><code>058f436</code></a> apply pending formatting to example code</li> +<li><a href="https://gitlab.com/antora/antora/commit/9452cca3881404bf808299322033957589f47f70"><code>9452cca</code></a> upgrade js-yaml</li> +<li><a href="https://gitlab.com/antora/antora/commit/621fe9397de807c132741b401247f462aceb2296"><code>621fe93</code></a> refresh dependency lock file</li> +<li><a href="https://gitlab.com/antora/antora/commit/57a244e0b94f3c3bfad43ac4cfed815b8be95218"><code>57a244e</code></a> remove unused images</li> +<li>Additional commits viewable in <a href="https://gitlab.com/antora/antora/compare/v3.2.0-rc.3...v3.2.0">compare view</a></li> +</ul> +</details> +<br /> + +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=@antora/cli&package-manager=npm_and_yarn&previous-version=3.2.0-rc.3&new-version=3.2.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +<details> +<summary>Dependabot commands and options</summary> +<br /> + +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) + +</details> + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `05383f774baa`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51526/tests/oracle.patch b/tasks/spring-projects__spring-boot-51526/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1c2b00befc0d0a21e7bb2e4729b40866a93e4dc0 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51526/tests/oracle.patch @@ -0,0 +1,156 @@ +diff --git a/antora/package-lock.json b/antora/package-lock.json +index 8d384c39390..64e323431d5 100644 +--- a/antora/package-lock.json ++++ b/antora/package-lock.json +@@ -6,7 +6,7 @@ + "": { + "dependencies": { + "@antora/atlas-extension": "1.0.0-alpha.5", +- "@antora/cli": "3.2.0-rc.3", ++ "@antora/cli": "3.2.0", + "@antora/site-generator": "3.2.0-rc.3", + "@asciidoctor/tabs": "1.0.0-beta.6", + "@springio/antora-extensions": "1.14.13", +@@ -58,13 +58,13 @@ + } + }, + "node_modules/@antora/cli": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/cli/-/cli-3.2.0-rc.3.tgz", +- "integrity": "sha512-MQJBkv+UyQgFNybEyFYlUUKmezZg9TMdR/qE5o6gjw7ytt5a1c6gmNdrbrIlGCHYurojInwhJXKON9NujxK0dA==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/cli/-/cli-3.2.0.tgz", ++ "integrity": "sha512-bJ5Vl+FMH52xm2jxdcbrEUN3aeoIYj5NGzLGsVwIPewM0RXee0kckbToAFnU0EK0Uw07cBomiJ5hwVELex0/ug==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/logger": "3.2.0-rc.3", +- "@antora/playbook-builder": "3.2.0-rc.3", ++ "@antora/logger": "3.2.0", ++ "@antora/playbook-builder": "3.2.0", + "@antora/user-require-helper": "~3.0", + "commander": "~14.0" + }, +@@ -75,56 +75,6 @@ + "node": ">=20.0.0" + } + }, +- "node_modules/@antora/cli/node_modules/@antora/logger": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.3.tgz", +- "integrity": "sha512-UJDfQQDL0x9kOdB926b/3NwpE7zlExTleJcwd1P0Smjd1Cgy7LI5idLgzxydB+Rn5UhL5c3SmxhDFDfMyg9A+w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@antora/expand-path-helper": "~3.0", +- "pino": "~10.3" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, +- "node_modules/@antora/cli/node_modules/@antora/playbook-builder": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/playbook-builder/-/playbook-builder-3.2.0-rc.3.tgz", +- "integrity": "sha512-UQGkIk13kPwFR0WMmoQDe1rdGJy6fs7Dj/OkZ3+n5Uo1OncBrg4kGyo/EFjIe9nU2rjC8zkpmQ1o39NWUNeV2w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@iarna/toml": "~2.2", +- "convict": "~6.2", +- "js-yaml": "~4.2", +- "json5": "~2.2" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, +- "node_modules/@antora/cli/node_modules/js-yaml": { +- "version": "4.2.0", +- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz", +- "integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==", +- "funding": [ +- { +- "type": "github", +- "url": "https://github.com/sponsors/puzrin" +- }, +- { +- "type": "github", +- "url": "https://github.com/sponsors/nodeca" +- } +- ], +- "license": "MIT", +- "dependencies": { +- "argparse": "^2.0.1" +- }, +- "bin": { +- "js-yaml": "bin/js-yaml.js" +- } +- }, + "node_modules/@antora/content-aggregator": { + "version": "3.2.0-rc.3", + "resolved": "https://registry.npmjs.org/@antora/content-aggregator/-/content-aggregator-3.2.0-rc.3.tgz", +@@ -251,9 +201,9 @@ + } + }, + "node_modules/@antora/logger": { +- "version": "3.2.0-rc.2", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.2.tgz", +- "integrity": "sha512-qNCOxx1WbleUaFzeyZ3kbRL2Hf4hN6CbvvRY7w45+iwH/ErejAR5iDtH2sCWbRJGYUt2hUbJ6FmpFFkXProaeA==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0.tgz", ++ "integrity": "sha512-2+bTFjYOuwoWjgtIfpf8bit6OuizI7O8RnXsHzX2y6/PBbm9K8ulvmqtnFk8933P5ILTZ/NSrbgvcFz5BXrY8A==", + "license": "MPL-2.0", + "dependencies": { + "@antora/expand-path-helper": "~3.0", +@@ -302,14 +252,14 @@ + } + }, + "node_modules/@antora/playbook-builder": { +- "version": "3.2.0-rc.2", +- "resolved": "https://registry.npmjs.org/@antora/playbook-builder/-/playbook-builder-3.2.0-rc.2.tgz", +- "integrity": "sha512-Fk/Ko/HYGGfDfIMZydyHidc66ASPyb+Wi0pzI4hTsK4PP8cP4NR2Rat9njAIUoMTuwsBogBGKH9uJ9l5bj/G4Q==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/playbook-builder/-/playbook-builder-3.2.0.tgz", ++ "integrity": "sha512-mAOrE+vDRa0wUcTc3JIZWvEai69vZ1kx6CvZi8ugSYrcWbZxNDp+R5pYWRX9037dZ5e6s5hKKGV503thm9BiSw==", + "license": "MPL-2.0", + "dependencies": { + "@iarna/toml": "~2.2", + "convict": "~6.2", +- "js-yaml": "~4.2", ++ "js-yaml": "~5.4", + "json5": "~2.2" + }, + "engines": { +@@ -317,9 +267,9 @@ + } + }, + "node_modules/@antora/playbook-builder/node_modules/js-yaml": { +- "version": "4.2.0", +- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz", +- "integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==", ++ "version": "5.4.1", ++ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.4.1.tgz", ++ "integrity": "sha512-28R/k+NAjeuf7+CKlTxWZVExJGwVVLwY06DgEnOMz2gEpfNkDcD7QvyiVPT0xy0XXhU8vHsd4Ot42OOPdJG7dQ==", + "funding": [ + { + "type": "github", +@@ -335,7 +285,7 @@ + "argparse": "^2.0.1" + }, + "bin": { +- "js-yaml": "bin/js-yaml.js" ++ "js-yaml": "bin/js-yaml.mjs" + } + }, + "node_modules/@antora/redirect-producer": { +diff --git a/antora/package.json b/antora/package.json +index a2a7665d396..6772baec36a 100644 +--- a/antora/package.json ++++ b/antora/package.json +@@ -3,7 +3,7 @@ + "antora": "node npm/antora.js" + }, + "dependencies": { +- "@antora/cli": "3.2.0-rc.3", ++ "@antora/cli": "3.2.0", + "@antora/site-generator": "3.2.0-rc.3", + "@antora/atlas-extension": "1.0.0-alpha.5", + "@springio/antora-extensions": "1.14.13", diff --git a/tasks/spring-projects__spring-boot-51526/tests/test.sh b/tasks/spring-projects__spring-boot-51526/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a6f930af95d4a0e82d69020fa63d40e4fce0f7fd --- /dev/null +++ b/tasks/spring-projects__spring-boot-51526/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 05383f774baa0b6e601f9f77da3a7f3b041ed8c4 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51526/tests/verifier.py b/tasks/spring-projects__spring-boot-51526/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51526/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51527/environment/Dockerfile b/tasks/spring-projects__spring-boot-51527/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5257295cc0cf6f60e52f76e46581a906397a4a64 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51527/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d4fbe320f24f86c8e98f553a20ba95f4f5661850 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d4fbe320f24f86c8e98f553a20ba95f4f5661850 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d4fbe320f24f86c8e98f553a20ba95f4f5661850 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51527/instruction.md b/tasks/spring-projects__spring-boot-51527/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b317eb5443bd6eca236ea4f592883848eaf4d4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51527/instruction.md @@ -0,0 +1,67 @@ +# Issue + +**Title:** Bump @antora/site-generator from 3.2.0-rc.3 to 3.2.0 in /antora + +## Description + +Bumps [@antora/site-generator](https://gitlab.com/antora/antora/tree/HEAD/packages/site-generator) from 3.2.0-rc.3 to 3.2.0. +<details> +<summary>Changelog</summary> +<p><em>Sourced from <a href="https://gitlab.com/antora/antora/blob/main/CHANGELOG.adoc">@​antora/site-generator's changelog</a>.</em></p> +<blockquote> +<p>== 3.2.0 (2026-08-29)</p> +<p>=== Changed</p> +<ul> +<li><em>site-generator</em>: Log original error message when Antora extension is suspected to be Asciidoctor extension</li> +<li>Upgrade js-yaml to 5.3.x (playbook-builder, content-aggregator, ui-loader)</li> +</ul> +<p>=== Fixed</p> +<ul> +<li>Don't crash if pub property not set on start page</li> +</ul> +</blockquote> +</details> +<details> +<summary>Commits</summary> +<ul> +<li><a href="https://gitlab.com/antora/antora/commit/85665d02158ec725565b527bde9b3dbf1fa5b827"><code>85665d0</code></a> release 3.2.0</li> +<li><a href="https://gitlab.com/antora/antora/commit/79f23d7f8dc32f9c9f28453704f014caa88ab3d2"><code>79f23d7</code></a> add Node.js 26 to test matrix</li> +<li><a href="https://gitlab.com/antora/antora/commit/04c952a6222ccb72333e85ce38ada7bb1b947f03"><code>04c952a</code></a> upgrade xmldom</li> +<li><a href="https://gitlab.com/antora/antora/commit/4b923ed6583579e84be3407152b609da6f58402d"><code>4b923ed</code></a> update declared supported versions of Node.js</li> +<li><a href="https://gitlab.com/antora/antora/commit/ecc28eb57e78b8762c3fbecd1d5bcf6995ecf49e"><code>ecc28eb</code></a> update release date on what's new page</li> +<li><a href="https://gitlab.com/antora/antora/commit/03b788c0ad11af3a671313a32c8f33c1dfdb4a55"><code>03b788c</code></a> add missing entries from what's new page</li> +<li><a href="https://gitlab.com/antora/antora/commit/058f436d96f5a4d2aec2746105e09844d15961ed"><code>058f436</code></a> apply pending formatting to example code</li> +<li><a href="https://gitlab.com/antora/antora/commit/9452cca3881404bf808299322033957589f47f70"><code>9452cca</code></a> upgrade js-yaml</li> +<li><a href="https://gitlab.com/antora/antora/commit/621fe9397de807c132741b401247f462aceb2296"><code>621fe93</code></a> refresh dependency lock file</li> +<li><a href="https://gitlab.com/antora/antora/commit/57a244e0b94f3c3bfad43ac4cfed815b8be95218"><code>57a244e</code></a> remove unused images</li> +<li>Additional commits viewable in <a href="https://gitlab.com/antora/antora/compare/v3.2.0-rc.3...v3.2.0">compare view</a></li> +</ul> +</details> +<br /> + +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=@antora/site-generator&package-manager=npm_and_yarn&previous-version=3.2.0-rc.3&new-version=3.2.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +<details> +<summary>Dependabot commands and options</summary> +<br /> + +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) + +</details> + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d4fbe320f24f`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51527/solution/patch.diff b/tasks/spring-projects__spring-boot-51527/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e6528a2375fc9b74c48e3325c7b0350890e631dc --- /dev/null +++ b/tasks/spring-projects__spring-boot-51527/solution/patch.diff @@ -0,0 +1,447 @@ +diff --git a/antora/package-lock.json b/antora/package-lock.json +index 64e323431d5..2db0e2c9059 100644 +--- a/antora/package-lock.json ++++ b/antora/package-lock.json +@@ -7,7 +7,7 @@ + "dependencies": { + "@antora/atlas-extension": "1.0.0-alpha.5", + "@antora/cli": "3.2.0", +- "@antora/site-generator": "3.2.0-rc.3", ++ "@antora/site-generator": "3.2.0", + "@asciidoctor/tabs": "1.0.0-beta.6", + "@springio/antora-extensions": "1.14.13", + "@springio/antora-xref-extension": "1.0.0-alpha.5", +@@ -16,12 +16,12 @@ + } + }, + "node_modules/@antora/asciidoc-loader": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/asciidoc-loader/-/asciidoc-loader-3.2.0-rc.3.tgz", +- "integrity": "sha512-6y7TOoQ5t8gyc7rOwJJb4PU/tG4bdK233CmDVtSnPqI/pdl6Dm4bEGwR+wWnmztqRoYQgSIGqaKv1sx78tH0JQ==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/asciidoc-loader/-/asciidoc-loader-3.2.0.tgz", ++ "integrity": "sha512-IaxhqSl9CvAi5Ieqt3Kc1SlJ11iq4kkWNFAAwUFCv/9L0WbzoczQ+o0y0W2lEONXVCKOBT1yzFBi55149SNwUQ==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/logger": "3.2.0-rc.3", ++ "@antora/logger": "3.2.0", + "@antora/user-require-helper": "~3.0", + "@asciidoctor/core": "~2.2" + }, +@@ -29,19 +29,6 @@ + "node": ">=20.0.0" + } + }, +- "node_modules/@antora/asciidoc-loader/node_modules/@antora/logger": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.3.tgz", +- "integrity": "sha512-UJDfQQDL0x9kOdB926b/3NwpE7zlExTleJcwd1P0Smjd1Cgy7LI5idLgzxydB+Rn5UhL5c3SmxhDFDfMyg9A+w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@antora/expand-path-helper": "~3.0", +- "pino": "~10.3" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, + "node_modules/@antora/atlas-extension": { + "version": "1.0.0-alpha.5", + "resolved": "https://registry.npmjs.org/@antora/atlas-extension/-/atlas-extension-1.0.0-alpha.5.tgz", +@@ -76,20 +63,20 @@ + } + }, + "node_modules/@antora/content-aggregator": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/content-aggregator/-/content-aggregator-3.2.0-rc.3.tgz", +- "integrity": "sha512-TJWX6bBjXYuyU2ur3HE4IOMrKbaLTOgXZ2J8SkOzr8LH+UqwnFX0FFdH2uHrgneqanQPP70C7aJcaoorQwx2Cw==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/content-aggregator/-/content-aggregator-3.2.0.tgz", ++ "integrity": "sha512-Q7lTjNFlpQx3SWW8QbNv5P4f1DhiKhYY3PyMifRHc4npuILOU0q4+kmlO1W1swSDDCg5pDjmgwitwAi9VQgvhg==", + "license": "MPL-2.0", + "dependencies": { + "@antora/expand-path-helper": "~3.0", +- "@antora/logger": "3.2.0-rc.3", ++ "@antora/logger": "3.2.0", + "@antora/user-require-helper": "~3.0", + "braces": "~3.0", + "cache-directory": "~2.0", + "fast-glob": "~3.3", + "hpagent": "~1.2", + "isomorphic-git": "~1.38", +- "js-yaml": "~4.2", ++ "js-yaml": "~5.4", + "multi-progress": "~4.0", + "picomatch": "~4.0", + "progress": "~2.0", +@@ -101,23 +88,10 @@ + "node": ">=20.0.0" + } + }, +- "node_modules/@antora/content-aggregator/node_modules/@antora/logger": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.3.tgz", +- "integrity": "sha512-UJDfQQDL0x9kOdB926b/3NwpE7zlExTleJcwd1P0Smjd1Cgy7LI5idLgzxydB+Rn5UhL5c3SmxhDFDfMyg9A+w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@antora/expand-path-helper": "~3.0", +- "pino": "~10.3" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, + "node_modules/@antora/content-aggregator/node_modules/js-yaml": { +- "version": "4.2.0", +- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz", +- "integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==", ++ "version": "5.4.1", ++ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.4.1.tgz", ++ "integrity": "sha512-28R/k+NAjeuf7+CKlTxWZVExJGwVVLwY06DgEnOMz2gEpfNkDcD7QvyiVPT0xy0XXhU8vHsd4Ot42OOPdJG7dQ==", + "funding": [ + { + "type": "github", +@@ -133,17 +107,17 @@ + "argparse": "^2.0.1" + }, + "bin": { +- "js-yaml": "bin/js-yaml.js" ++ "js-yaml": "bin/js-yaml.mjs" + } + }, + "node_modules/@antora/content-classifier": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/content-classifier/-/content-classifier-3.2.0-rc.3.tgz", +- "integrity": "sha512-eU+I5ygHubZ0eywYkP62OOgP9NHQS4aR0qaTCndEd2zTW1mx1LdrNjHFOinnrMirmaBcsYeZX+dq8NCdyBYALQ==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/content-classifier/-/content-classifier-3.2.0.tgz", ++ "integrity": "sha512-fUrh08qpgbsjV7noFTWDQaevLC2NAs3gHRJbaTTvULEb+OZRCB0LjEPyvhIAk1wKwkfPqcnjAShJHurH/gXPCg==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/asciidoc-loader": "3.2.0-rc.3", +- "@antora/logger": "3.2.0-rc.3", ++ "@antora/asciidoc-loader": "3.2.0", ++ "@antora/logger": "3.2.0", + "mime-types": "~3.0", + "vinyl": "~3.0" + }, +@@ -151,26 +125,13 @@ + "node": ">=20.0.0" + } + }, +- "node_modules/@antora/content-classifier/node_modules/@antora/logger": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.3.tgz", +- "integrity": "sha512-UJDfQQDL0x9kOdB926b/3NwpE7zlExTleJcwd1P0Smjd1Cgy7LI5idLgzxydB+Rn5UhL5c3SmxhDFDfMyg9A+w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@antora/expand-path-helper": "~3.0", +- "pino": "~10.3" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, + "node_modules/@antora/document-converter": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/document-converter/-/document-converter-3.2.0-rc.3.tgz", +- "integrity": "sha512-80wKpw8QUaHTTtHKCbW4579lyhxDvf0Q/XYUwSxfHBFQToKAPk/T5Wgd4F/5uaub2uoxM+NCqxMFQB8Eqd6ZuA==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/document-converter/-/document-converter-3.2.0.tgz", ++ "integrity": "sha512-+cwQxIIRNI9+BXHk2fff/jvBd17p/AHslAT02ic6tWlgRaORc5y5/dRK+Q9hSjE6vpndE92gyokRn2zsigOUDg==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/asciidoc-loader": "3.2.0-rc.3" ++ "@antora/asciidoc-loader": "3.2.0" + }, + "engines": { + "node": ">=20.0.0" +@@ -186,9 +147,9 @@ + } + }, + "node_modules/@antora/file-publisher": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/file-publisher/-/file-publisher-3.2.0-rc.3.tgz", +- "integrity": "sha512-6lUT2cnudeB3Comc61vzBgo6x0H9caBM2hBneMNEAA6zr4DaG2GK5oNqHXuBwQomgffw/OoSqr/y4gMW1YYiGw==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/file-publisher/-/file-publisher-3.2.0.tgz", ++ "integrity": "sha512-UqKzDI2JR/Ms88kgUteyqvIikekDBoZZGPo8L79GpvffPBP2CJmhCSSue1IuV0aFtobHuCgWqWtHzsdhy7KJ6Q==", + "license": "MPL-2.0", + "dependencies": { + "@antora/expand-path-helper": "~3.0", +@@ -214,43 +175,30 @@ + } + }, + "node_modules/@antora/navigation-builder": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/navigation-builder/-/navigation-builder-3.2.0-rc.3.tgz", +- "integrity": "sha512-TRU2XpZO/81id6Rot5ktlVDyyLhmFfL2dU/9JClVZJj6L9HDv1zb8R5HtZI5ujJcp1M0M3AQZKwk7WUtJ57rmQ==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/navigation-builder/-/navigation-builder-3.2.0.tgz", ++ "integrity": "sha512-W7TI0e2doDwpF7YYsYUYJtxFQfDre4egU33eOM8Y7ZEUaAZBweOCiANFgZmfZiCvM3nswLyBtMJqvVzAc8vPTg==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/asciidoc-loader": "3.2.0-rc.3" ++ "@antora/asciidoc-loader": "3.2.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@antora/page-composer": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/page-composer/-/page-composer-3.2.0-rc.3.tgz", +- "integrity": "sha512-h6NCDWwpYQeR9z4XCRQmxdr8Fi10TT/g1oxy1W7xNP+KjTBjkLdjXZBwDqc7OVZo9U5NUx7uPxZwfmPGXYlJiA==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/page-composer/-/page-composer-3.2.0.tgz", ++ "integrity": "sha512-cBr9wYnF6ba4fbbVvs+fR/88BPoqFB9bxdU2z2kWXDsAkQIT/OHLauo+UY+H5+pw/SET1A9bOwMaNlvM4mvfxg==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/logger": "3.2.0-rc.3", ++ "@antora/logger": "3.2.0", + "handlebars": "~4.7" + }, + "engines": { + "node": ">=20.0.0" + } + }, +- "node_modules/@antora/page-composer/node_modules/@antora/logger": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.3.tgz", +- "integrity": "sha512-UJDfQQDL0x9kOdB926b/3NwpE7zlExTleJcwd1P0Smjd1Cgy7LI5idLgzxydB+Rn5UhL5c3SmxhDFDfMyg9A+w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@antora/expand-path-helper": "~3.0", +- "pino": "~10.3" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, + "node_modules/@antora/playbook-builder": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@antora/playbook-builder/-/playbook-builder-3.2.0.tgz", +@@ -289,12 +237,12 @@ + } + }, + "node_modules/@antora/redirect-producer": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/redirect-producer/-/redirect-producer-3.2.0-rc.3.tgz", +- "integrity": "sha512-TX9aEJHbJSynWcJA0qyYk/Pu5ZzWU+3gfSrlz72hbhB7euZXJ3XR+/G59yh1zL4GLG+eX7jNYk8sELFQsYe/ag==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/redirect-producer/-/redirect-producer-3.2.0.tgz", ++ "integrity": "sha512-soJbguowD3r7rCMn/r6OMiphXXUwNXUE9MeR6xrDa1RnoTu5mNALIhgI4mBid1CZ/jb+tnJ0WQWVArM1d9EmKw==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/content-classifier": "3.2.0-rc.3", ++ "@antora/content-classifier": "3.2.0", + "vinyl": "~3.0" + }, + "engines": { +@@ -302,87 +250,37 @@ + } + }, + "node_modules/@antora/site-generator": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/site-generator/-/site-generator-3.2.0-rc.3.tgz", +- "integrity": "sha512-JLl/N8PDllUKhixeegipDRa7byxKIYQOJHUKlScjxa3pffDcbvOH5EBt5mAkBxI0dyo68bEQmz5i+R/19Oli5A==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/site-generator/-/site-generator-3.2.0.tgz", ++ "integrity": "sha512-bgShOpARuO+1MF50HUsv25C7msyZk6GpaP2EBcjqD3s0Dj51amQL5KMqAbwfKLjTCiAUTGpC/Yb8rGeogUnmYw==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/asciidoc-loader": "3.2.0-rc.3", +- "@antora/content-aggregator": "3.2.0-rc.3", +- "@antora/content-classifier": "3.2.0-rc.3", +- "@antora/document-converter": "3.2.0-rc.3", +- "@antora/file-publisher": "3.2.0-rc.3", +- "@antora/logger": "3.2.0-rc.3", +- "@antora/navigation-builder": "3.2.0-rc.3", +- "@antora/page-composer": "3.2.0-rc.3", +- "@antora/playbook-builder": "3.2.0-rc.3", +- "@antora/redirect-producer": "3.2.0-rc.3", +- "@antora/site-mapper": "3.2.0-rc.3", +- "@antora/site-publisher": "3.2.0-rc.3", +- "@antora/ui-loader": "3.2.0-rc.3", ++ "@antora/asciidoc-loader": "3.2.0", ++ "@antora/content-aggregator": "3.2.0", ++ "@antora/content-classifier": "3.2.0", ++ "@antora/document-converter": "3.2.0", ++ "@antora/file-publisher": "3.2.0", ++ "@antora/logger": "3.2.0", ++ "@antora/navigation-builder": "3.2.0", ++ "@antora/page-composer": "3.2.0", ++ "@antora/playbook-builder": "3.2.0", ++ "@antora/redirect-producer": "3.2.0", ++ "@antora/site-mapper": "3.2.0", ++ "@antora/site-publisher": "3.2.0", ++ "@antora/ui-loader": "3.2.0", + "@antora/user-require-helper": "~3.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, +- "node_modules/@antora/site-generator/node_modules/@antora/logger": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.3.tgz", +- "integrity": "sha512-UJDfQQDL0x9kOdB926b/3NwpE7zlExTleJcwd1P0Smjd1Cgy7LI5idLgzxydB+Rn5UhL5c3SmxhDFDfMyg9A+w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@antora/expand-path-helper": "~3.0", +- "pino": "~10.3" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, +- "node_modules/@antora/site-generator/node_modules/@antora/playbook-builder": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/playbook-builder/-/playbook-builder-3.2.0-rc.3.tgz", +- "integrity": "sha512-UQGkIk13kPwFR0WMmoQDe1rdGJy6fs7Dj/OkZ3+n5Uo1OncBrg4kGyo/EFjIe9nU2rjC8zkpmQ1o39NWUNeV2w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@iarna/toml": "~2.2", +- "convict": "~6.2", +- "js-yaml": "~4.2", +- "json5": "~2.2" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, +- "node_modules/@antora/site-generator/node_modules/js-yaml": { +- "version": "4.2.0", +- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz", +- "integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==", +- "funding": [ +- { +- "type": "github", +- "url": "https://github.com/sponsors/puzrin" +- }, +- { +- "type": "github", +- "url": "https://github.com/sponsors/nodeca" +- } +- ], +- "license": "MIT", +- "dependencies": { +- "argparse": "^2.0.1" +- }, +- "bin": { +- "js-yaml": "bin/js-yaml.js" +- } +- }, + "node_modules/@antora/site-mapper": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/site-mapper/-/site-mapper-3.2.0-rc.3.tgz", +- "integrity": "sha512-1TYG53PUeNCr32bPKQkW3Q0unYpFsbl1wHGFsLYRDt3+0kjL9TyrSRkmAYxJiOjv95rL/VZSzxQqRJ7vx83QVg==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/site-mapper/-/site-mapper-3.2.0.tgz", ++ "integrity": "sha512-ZnBl03Ha5dLlduVoKGC2kn+n0o8IPwoMzSbu+rLok+uzEPR2La7fQXNJa9exNzBtnE2GnNkj37jJg6YHQpIUiw==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/content-classifier": "3.2.0-rc.3", ++ "@antora/content-classifier": "3.2.0", + "vinyl": "~3.0" + }, + "engines": { +@@ -390,21 +288,21 @@ + } + }, + "node_modules/@antora/site-publisher": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/site-publisher/-/site-publisher-3.2.0-rc.3.tgz", +- "integrity": "sha512-aDJgMxlxpCrXCnaoBZa8V2sXGxyGIC4+++Nf3xkIDl6FUbd+rTLKnVjyi0nwh+TRKUea8mibVqHLd976Erj/gQ==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/site-publisher/-/site-publisher-3.2.0.tgz", ++ "integrity": "sha512-zXYxyH0+NuhaPnGReDvL8CCmYPsocxSKn3HeE3Z39lrexK/qSajliUGYW0jP9IRi+cCFXpvuC7PDYtQfZDvWaw==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/file-publisher": "3.2.0-rc.3" ++ "@antora/file-publisher": "3.2.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@antora/ui-loader": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/ui-loader/-/ui-loader-3.2.0-rc.3.tgz", +- "integrity": "sha512-Ws8r/o+5QQPYzy/2kcsIg6pFetNaeo0qAxu8RU5MkGCpupJKC8WTDQm0fULtcLnYZpv+PZ5SZr/lk9hKo3eCig==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/ui-loader/-/ui-loader-3.2.0.tgz", ++ "integrity": "sha512-EYagiuG2Tk5QtnG/rwTzu/8mxDtL8J2oqZc74g0h4h3iatJeD8yNrDc8iDhNaycEZNaxPRfIK73tpKuIFZw+Iw==", + "license": "MPL-2.0", + "dependencies": { + "@antora/expand-path-helper": "~3.0", +@@ -412,7 +310,7 @@ + "cache-directory": "~2.0", + "fast-glob": "~3.3", + "hpagent": "~1.2", +- "js-yaml": "~4.2", ++ "js-yaml": "~5.4", + "picomatch": "~4.0", + "should-proxy": "~1.0", + "simple-get": "~4.0", +@@ -424,9 +322,9 @@ + } + }, + "node_modules/@antora/ui-loader/node_modules/js-yaml": { +- "version": "4.2.0", +- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz", +- "integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==", ++ "version": "5.4.1", ++ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.4.1.tgz", ++ "integrity": "sha512-28R/k+NAjeuf7+CKlTxWZVExJGwVVLwY06DgEnOMz2gEpfNkDcD7QvyiVPT0xy0XXhU8vHsd4Ot42OOPdJG7dQ==", + "funding": [ + { + "type": "github", +@@ -442,7 +340,7 @@ + "argparse": "^2.0.1" + }, + "bin": { +- "js-yaml": "bin/js-yaml.js" ++ "js-yaml": "bin/js-yaml.mjs" + } + }, + "node_modules/@antora/user-require-helper": { +@@ -1628,9 +1526,9 @@ + } + }, + "node_modules/fastq": { +- "version": "1.20.1", +- "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", +- "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", ++ "version": "1.20.3", ++ "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", ++ "integrity": "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" +@@ -2526,9 +2424,9 @@ + "license": "MIT" + }, + "node_modules/picomatch": { +- "version": "4.0.5", +- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", +- "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", ++ "version": "4.0.7", ++ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", ++ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "license": "MIT", + "engines": { + "node": ">=12" +diff --git a/antora/package.json b/antora/package.json +index 6772baec36a..beb07a51a52 100644 +--- a/antora/package.json ++++ b/antora/package.json +@@ -4,7 +4,7 @@ + }, + "dependencies": { + "@antora/cli": "3.2.0", +- "@antora/site-generator": "3.2.0-rc.3", ++ "@antora/site-generator": "3.2.0", + "@antora/atlas-extension": "1.0.0-alpha.5", + "@springio/antora-extensions": "1.14.13", + "@springio/antora-xref-extension": "1.0.0-alpha.5", diff --git a/tasks/spring-projects__spring-boot-51527/solution/solve.sh b/tasks/spring-projects__spring-boot-51527/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51527/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51527/task.toml b/tasks/spring-projects__spring-boot-51527/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..60a235fe1b58fae25aa345c10d2d6ff827013dc9 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51527/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51527" +description = "Bump @antora/site-generator from 3.2.0-rc.3 to 3.2.0 in /antora" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "d4fbe320f24f86c8e98f553a20ba95f4f5661850" +reference = "https://github.com/spring-projects/spring-boot/pull/51527" +source_access = "auto" +built_at = "2026-11-16T16:09:44.794158+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e182cf5eb4f921cfa530cae1209982c6d8499c15d2daf7d51b0365d26389974a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-02T06:31:50Z" +diff_format = "unified" +context_files = [ + "antora/package-lock.json", + "antora/package.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 256 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.165579+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3c4dd5fec892ab512bec40277c6477dba2a40b90950fe65336ea080c1f97029c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51527/tests/capture.py b/tasks/spring-projects__spring-boot-51527/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51527/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51527/tests/instruction.md b/tasks/spring-projects__spring-boot-51527/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b317eb5443bd6eca236ea4f592883848eaf4d4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51527/tests/instruction.md @@ -0,0 +1,67 @@ +# Issue + +**Title:** Bump @antora/site-generator from 3.2.0-rc.3 to 3.2.0 in /antora + +## Description + +Bumps [@antora/site-generator](https://gitlab.com/antora/antora/tree/HEAD/packages/site-generator) from 3.2.0-rc.3 to 3.2.0. +<details> +<summary>Changelog</summary> +<p><em>Sourced from <a href="https://gitlab.com/antora/antora/blob/main/CHANGELOG.adoc">@​antora/site-generator's changelog</a>.</em></p> +<blockquote> +<p>== 3.2.0 (2026-08-29)</p> +<p>=== Changed</p> +<ul> +<li><em>site-generator</em>: Log original error message when Antora extension is suspected to be Asciidoctor extension</li> +<li>Upgrade js-yaml to 5.3.x (playbook-builder, content-aggregator, ui-loader)</li> +</ul> +<p>=== Fixed</p> +<ul> +<li>Don't crash if pub property not set on start page</li> +</ul> +</blockquote> +</details> +<details> +<summary>Commits</summary> +<ul> +<li><a href="https://gitlab.com/antora/antora/commit/85665d02158ec725565b527bde9b3dbf1fa5b827"><code>85665d0</code></a> release 3.2.0</li> +<li><a href="https://gitlab.com/antora/antora/commit/79f23d7f8dc32f9c9f28453704f014caa88ab3d2"><code>79f23d7</code></a> add Node.js 26 to test matrix</li> +<li><a href="https://gitlab.com/antora/antora/commit/04c952a6222ccb72333e85ce38ada7bb1b947f03"><code>04c952a</code></a> upgrade xmldom</li> +<li><a href="https://gitlab.com/antora/antora/commit/4b923ed6583579e84be3407152b609da6f58402d"><code>4b923ed</code></a> update declared supported versions of Node.js</li> +<li><a href="https://gitlab.com/antora/antora/commit/ecc28eb57e78b8762c3fbecd1d5bcf6995ecf49e"><code>ecc28eb</code></a> update release date on what's new page</li> +<li><a href="https://gitlab.com/antora/antora/commit/03b788c0ad11af3a671313a32c8f33c1dfdb4a55"><code>03b788c</code></a> add missing entries from what's new page</li> +<li><a href="https://gitlab.com/antora/antora/commit/058f436d96f5a4d2aec2746105e09844d15961ed"><code>058f436</code></a> apply pending formatting to example code</li> +<li><a href="https://gitlab.com/antora/antora/commit/9452cca3881404bf808299322033957589f47f70"><code>9452cca</code></a> upgrade js-yaml</li> +<li><a href="https://gitlab.com/antora/antora/commit/621fe9397de807c132741b401247f462aceb2296"><code>621fe93</code></a> refresh dependency lock file</li> +<li><a href="https://gitlab.com/antora/antora/commit/57a244e0b94f3c3bfad43ac4cfed815b8be95218"><code>57a244e</code></a> remove unused images</li> +<li>Additional commits viewable in <a href="https://gitlab.com/antora/antora/compare/v3.2.0-rc.3...v3.2.0">compare view</a></li> +</ul> +</details> +<br /> + +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=@antora/site-generator&package-manager=npm_and_yarn&previous-version=3.2.0-rc.3&new-version=3.2.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +<details> +<summary>Dependabot commands and options</summary> +<br /> + +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show <dependency name> ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) +- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) + +</details> + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d4fbe320f24f`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51527/tests/oracle.patch b/tasks/spring-projects__spring-boot-51527/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e6528a2375fc9b74c48e3325c7b0350890e631dc --- /dev/null +++ b/tasks/spring-projects__spring-boot-51527/tests/oracle.patch @@ -0,0 +1,447 @@ +diff --git a/antora/package-lock.json b/antora/package-lock.json +index 64e323431d5..2db0e2c9059 100644 +--- a/antora/package-lock.json ++++ b/antora/package-lock.json +@@ -7,7 +7,7 @@ + "dependencies": { + "@antora/atlas-extension": "1.0.0-alpha.5", + "@antora/cli": "3.2.0", +- "@antora/site-generator": "3.2.0-rc.3", ++ "@antora/site-generator": "3.2.0", + "@asciidoctor/tabs": "1.0.0-beta.6", + "@springio/antora-extensions": "1.14.13", + "@springio/antora-xref-extension": "1.0.0-alpha.5", +@@ -16,12 +16,12 @@ + } + }, + "node_modules/@antora/asciidoc-loader": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/asciidoc-loader/-/asciidoc-loader-3.2.0-rc.3.tgz", +- "integrity": "sha512-6y7TOoQ5t8gyc7rOwJJb4PU/tG4bdK233CmDVtSnPqI/pdl6Dm4bEGwR+wWnmztqRoYQgSIGqaKv1sx78tH0JQ==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/asciidoc-loader/-/asciidoc-loader-3.2.0.tgz", ++ "integrity": "sha512-IaxhqSl9CvAi5Ieqt3Kc1SlJ11iq4kkWNFAAwUFCv/9L0WbzoczQ+o0y0W2lEONXVCKOBT1yzFBi55149SNwUQ==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/logger": "3.2.0-rc.3", ++ "@antora/logger": "3.2.0", + "@antora/user-require-helper": "~3.0", + "@asciidoctor/core": "~2.2" + }, +@@ -29,19 +29,6 @@ + "node": ">=20.0.0" + } + }, +- "node_modules/@antora/asciidoc-loader/node_modules/@antora/logger": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.3.tgz", +- "integrity": "sha512-UJDfQQDL0x9kOdB926b/3NwpE7zlExTleJcwd1P0Smjd1Cgy7LI5idLgzxydB+Rn5UhL5c3SmxhDFDfMyg9A+w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@antora/expand-path-helper": "~3.0", +- "pino": "~10.3" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, + "node_modules/@antora/atlas-extension": { + "version": "1.0.0-alpha.5", + "resolved": "https://registry.npmjs.org/@antora/atlas-extension/-/atlas-extension-1.0.0-alpha.5.tgz", +@@ -76,20 +63,20 @@ + } + }, + "node_modules/@antora/content-aggregator": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/content-aggregator/-/content-aggregator-3.2.0-rc.3.tgz", +- "integrity": "sha512-TJWX6bBjXYuyU2ur3HE4IOMrKbaLTOgXZ2J8SkOzr8LH+UqwnFX0FFdH2uHrgneqanQPP70C7aJcaoorQwx2Cw==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/content-aggregator/-/content-aggregator-3.2.0.tgz", ++ "integrity": "sha512-Q7lTjNFlpQx3SWW8QbNv5P4f1DhiKhYY3PyMifRHc4npuILOU0q4+kmlO1W1swSDDCg5pDjmgwitwAi9VQgvhg==", + "license": "MPL-2.0", + "dependencies": { + "@antora/expand-path-helper": "~3.0", +- "@antora/logger": "3.2.0-rc.3", ++ "@antora/logger": "3.2.0", + "@antora/user-require-helper": "~3.0", + "braces": "~3.0", + "cache-directory": "~2.0", + "fast-glob": "~3.3", + "hpagent": "~1.2", + "isomorphic-git": "~1.38", +- "js-yaml": "~4.2", ++ "js-yaml": "~5.4", + "multi-progress": "~4.0", + "picomatch": "~4.0", + "progress": "~2.0", +@@ -101,23 +88,10 @@ + "node": ">=20.0.0" + } + }, +- "node_modules/@antora/content-aggregator/node_modules/@antora/logger": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.3.tgz", +- "integrity": "sha512-UJDfQQDL0x9kOdB926b/3NwpE7zlExTleJcwd1P0Smjd1Cgy7LI5idLgzxydB+Rn5UhL5c3SmxhDFDfMyg9A+w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@antora/expand-path-helper": "~3.0", +- "pino": "~10.3" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, + "node_modules/@antora/content-aggregator/node_modules/js-yaml": { +- "version": "4.2.0", +- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz", +- "integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==", ++ "version": "5.4.1", ++ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.4.1.tgz", ++ "integrity": "sha512-28R/k+NAjeuf7+CKlTxWZVExJGwVVLwY06DgEnOMz2gEpfNkDcD7QvyiVPT0xy0XXhU8vHsd4Ot42OOPdJG7dQ==", + "funding": [ + { + "type": "github", +@@ -133,17 +107,17 @@ + "argparse": "^2.0.1" + }, + "bin": { +- "js-yaml": "bin/js-yaml.js" ++ "js-yaml": "bin/js-yaml.mjs" + } + }, + "node_modules/@antora/content-classifier": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/content-classifier/-/content-classifier-3.2.0-rc.3.tgz", +- "integrity": "sha512-eU+I5ygHubZ0eywYkP62OOgP9NHQS4aR0qaTCndEd2zTW1mx1LdrNjHFOinnrMirmaBcsYeZX+dq8NCdyBYALQ==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/content-classifier/-/content-classifier-3.2.0.tgz", ++ "integrity": "sha512-fUrh08qpgbsjV7noFTWDQaevLC2NAs3gHRJbaTTvULEb+OZRCB0LjEPyvhIAk1wKwkfPqcnjAShJHurH/gXPCg==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/asciidoc-loader": "3.2.0-rc.3", +- "@antora/logger": "3.2.0-rc.3", ++ "@antora/asciidoc-loader": "3.2.0", ++ "@antora/logger": "3.2.0", + "mime-types": "~3.0", + "vinyl": "~3.0" + }, +@@ -151,26 +125,13 @@ + "node": ">=20.0.0" + } + }, +- "node_modules/@antora/content-classifier/node_modules/@antora/logger": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.3.tgz", +- "integrity": "sha512-UJDfQQDL0x9kOdB926b/3NwpE7zlExTleJcwd1P0Smjd1Cgy7LI5idLgzxydB+Rn5UhL5c3SmxhDFDfMyg9A+w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@antora/expand-path-helper": "~3.0", +- "pino": "~10.3" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, + "node_modules/@antora/document-converter": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/document-converter/-/document-converter-3.2.0-rc.3.tgz", +- "integrity": "sha512-80wKpw8QUaHTTtHKCbW4579lyhxDvf0Q/XYUwSxfHBFQToKAPk/T5Wgd4F/5uaub2uoxM+NCqxMFQB8Eqd6ZuA==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/document-converter/-/document-converter-3.2.0.tgz", ++ "integrity": "sha512-+cwQxIIRNI9+BXHk2fff/jvBd17p/AHslAT02ic6tWlgRaORc5y5/dRK+Q9hSjE6vpndE92gyokRn2zsigOUDg==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/asciidoc-loader": "3.2.0-rc.3" ++ "@antora/asciidoc-loader": "3.2.0" + }, + "engines": { + "node": ">=20.0.0" +@@ -186,9 +147,9 @@ + } + }, + "node_modules/@antora/file-publisher": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/file-publisher/-/file-publisher-3.2.0-rc.3.tgz", +- "integrity": "sha512-6lUT2cnudeB3Comc61vzBgo6x0H9caBM2hBneMNEAA6zr4DaG2GK5oNqHXuBwQomgffw/OoSqr/y4gMW1YYiGw==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/file-publisher/-/file-publisher-3.2.0.tgz", ++ "integrity": "sha512-UqKzDI2JR/Ms88kgUteyqvIikekDBoZZGPo8L79GpvffPBP2CJmhCSSue1IuV0aFtobHuCgWqWtHzsdhy7KJ6Q==", + "license": "MPL-2.0", + "dependencies": { + "@antora/expand-path-helper": "~3.0", +@@ -214,43 +175,30 @@ + } + }, + "node_modules/@antora/navigation-builder": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/navigation-builder/-/navigation-builder-3.2.0-rc.3.tgz", +- "integrity": "sha512-TRU2XpZO/81id6Rot5ktlVDyyLhmFfL2dU/9JClVZJj6L9HDv1zb8R5HtZI5ujJcp1M0M3AQZKwk7WUtJ57rmQ==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/navigation-builder/-/navigation-builder-3.2.0.tgz", ++ "integrity": "sha512-W7TI0e2doDwpF7YYsYUYJtxFQfDre4egU33eOM8Y7ZEUaAZBweOCiANFgZmfZiCvM3nswLyBtMJqvVzAc8vPTg==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/asciidoc-loader": "3.2.0-rc.3" ++ "@antora/asciidoc-loader": "3.2.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@antora/page-composer": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/page-composer/-/page-composer-3.2.0-rc.3.tgz", +- "integrity": "sha512-h6NCDWwpYQeR9z4XCRQmxdr8Fi10TT/g1oxy1W7xNP+KjTBjkLdjXZBwDqc7OVZo9U5NUx7uPxZwfmPGXYlJiA==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/page-composer/-/page-composer-3.2.0.tgz", ++ "integrity": "sha512-cBr9wYnF6ba4fbbVvs+fR/88BPoqFB9bxdU2z2kWXDsAkQIT/OHLauo+UY+H5+pw/SET1A9bOwMaNlvM4mvfxg==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/logger": "3.2.0-rc.3", ++ "@antora/logger": "3.2.0", + "handlebars": "~4.7" + }, + "engines": { + "node": ">=20.0.0" + } + }, +- "node_modules/@antora/page-composer/node_modules/@antora/logger": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.3.tgz", +- "integrity": "sha512-UJDfQQDL0x9kOdB926b/3NwpE7zlExTleJcwd1P0Smjd1Cgy7LI5idLgzxydB+Rn5UhL5c3SmxhDFDfMyg9A+w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@antora/expand-path-helper": "~3.0", +- "pino": "~10.3" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, + "node_modules/@antora/playbook-builder": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@antora/playbook-builder/-/playbook-builder-3.2.0.tgz", +@@ -289,12 +237,12 @@ + } + }, + "node_modules/@antora/redirect-producer": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/redirect-producer/-/redirect-producer-3.2.0-rc.3.tgz", +- "integrity": "sha512-TX9aEJHbJSynWcJA0qyYk/Pu5ZzWU+3gfSrlz72hbhB7euZXJ3XR+/G59yh1zL4GLG+eX7jNYk8sELFQsYe/ag==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/redirect-producer/-/redirect-producer-3.2.0.tgz", ++ "integrity": "sha512-soJbguowD3r7rCMn/r6OMiphXXUwNXUE9MeR6xrDa1RnoTu5mNALIhgI4mBid1CZ/jb+tnJ0WQWVArM1d9EmKw==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/content-classifier": "3.2.0-rc.3", ++ "@antora/content-classifier": "3.2.0", + "vinyl": "~3.0" + }, + "engines": { +@@ -302,87 +250,37 @@ + } + }, + "node_modules/@antora/site-generator": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/site-generator/-/site-generator-3.2.0-rc.3.tgz", +- "integrity": "sha512-JLl/N8PDllUKhixeegipDRa7byxKIYQOJHUKlScjxa3pffDcbvOH5EBt5mAkBxI0dyo68bEQmz5i+R/19Oli5A==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/site-generator/-/site-generator-3.2.0.tgz", ++ "integrity": "sha512-bgShOpARuO+1MF50HUsv25C7msyZk6GpaP2EBcjqD3s0Dj51amQL5KMqAbwfKLjTCiAUTGpC/Yb8rGeogUnmYw==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/asciidoc-loader": "3.2.0-rc.3", +- "@antora/content-aggregator": "3.2.0-rc.3", +- "@antora/content-classifier": "3.2.0-rc.3", +- "@antora/document-converter": "3.2.0-rc.3", +- "@antora/file-publisher": "3.2.0-rc.3", +- "@antora/logger": "3.2.0-rc.3", +- "@antora/navigation-builder": "3.2.0-rc.3", +- "@antora/page-composer": "3.2.0-rc.3", +- "@antora/playbook-builder": "3.2.0-rc.3", +- "@antora/redirect-producer": "3.2.0-rc.3", +- "@antora/site-mapper": "3.2.0-rc.3", +- "@antora/site-publisher": "3.2.0-rc.3", +- "@antora/ui-loader": "3.2.0-rc.3", ++ "@antora/asciidoc-loader": "3.2.0", ++ "@antora/content-aggregator": "3.2.0", ++ "@antora/content-classifier": "3.2.0", ++ "@antora/document-converter": "3.2.0", ++ "@antora/file-publisher": "3.2.0", ++ "@antora/logger": "3.2.0", ++ "@antora/navigation-builder": "3.2.0", ++ "@antora/page-composer": "3.2.0", ++ "@antora/playbook-builder": "3.2.0", ++ "@antora/redirect-producer": "3.2.0", ++ "@antora/site-mapper": "3.2.0", ++ "@antora/site-publisher": "3.2.0", ++ "@antora/ui-loader": "3.2.0", + "@antora/user-require-helper": "~3.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, +- "node_modules/@antora/site-generator/node_modules/@antora/logger": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/logger/-/logger-3.2.0-rc.3.tgz", +- "integrity": "sha512-UJDfQQDL0x9kOdB926b/3NwpE7zlExTleJcwd1P0Smjd1Cgy7LI5idLgzxydB+Rn5UhL5c3SmxhDFDfMyg9A+w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@antora/expand-path-helper": "~3.0", +- "pino": "~10.3" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, +- "node_modules/@antora/site-generator/node_modules/@antora/playbook-builder": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/playbook-builder/-/playbook-builder-3.2.0-rc.3.tgz", +- "integrity": "sha512-UQGkIk13kPwFR0WMmoQDe1rdGJy6fs7Dj/OkZ3+n5Uo1OncBrg4kGyo/EFjIe9nU2rjC8zkpmQ1o39NWUNeV2w==", +- "license": "MPL-2.0", +- "dependencies": { +- "@iarna/toml": "~2.2", +- "convict": "~6.2", +- "js-yaml": "~4.2", +- "json5": "~2.2" +- }, +- "engines": { +- "node": ">=20.0.0" +- } +- }, +- "node_modules/@antora/site-generator/node_modules/js-yaml": { +- "version": "4.2.0", +- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz", +- "integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==", +- "funding": [ +- { +- "type": "github", +- "url": "https://github.com/sponsors/puzrin" +- }, +- { +- "type": "github", +- "url": "https://github.com/sponsors/nodeca" +- } +- ], +- "license": "MIT", +- "dependencies": { +- "argparse": "^2.0.1" +- }, +- "bin": { +- "js-yaml": "bin/js-yaml.js" +- } +- }, + "node_modules/@antora/site-mapper": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/site-mapper/-/site-mapper-3.2.0-rc.3.tgz", +- "integrity": "sha512-1TYG53PUeNCr32bPKQkW3Q0unYpFsbl1wHGFsLYRDt3+0kjL9TyrSRkmAYxJiOjv95rL/VZSzxQqRJ7vx83QVg==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/site-mapper/-/site-mapper-3.2.0.tgz", ++ "integrity": "sha512-ZnBl03Ha5dLlduVoKGC2kn+n0o8IPwoMzSbu+rLok+uzEPR2La7fQXNJa9exNzBtnE2GnNkj37jJg6YHQpIUiw==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/content-classifier": "3.2.0-rc.3", ++ "@antora/content-classifier": "3.2.0", + "vinyl": "~3.0" + }, + "engines": { +@@ -390,21 +288,21 @@ + } + }, + "node_modules/@antora/site-publisher": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/site-publisher/-/site-publisher-3.2.0-rc.3.tgz", +- "integrity": "sha512-aDJgMxlxpCrXCnaoBZa8V2sXGxyGIC4+++Nf3xkIDl6FUbd+rTLKnVjyi0nwh+TRKUea8mibVqHLd976Erj/gQ==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/site-publisher/-/site-publisher-3.2.0.tgz", ++ "integrity": "sha512-zXYxyH0+NuhaPnGReDvL8CCmYPsocxSKn3HeE3Z39lrexK/qSajliUGYW0jP9IRi+cCFXpvuC7PDYtQfZDvWaw==", + "license": "MPL-2.0", + "dependencies": { +- "@antora/file-publisher": "3.2.0-rc.3" ++ "@antora/file-publisher": "3.2.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/@antora/ui-loader": { +- "version": "3.2.0-rc.3", +- "resolved": "https://registry.npmjs.org/@antora/ui-loader/-/ui-loader-3.2.0-rc.3.tgz", +- "integrity": "sha512-Ws8r/o+5QQPYzy/2kcsIg6pFetNaeo0qAxu8RU5MkGCpupJKC8WTDQm0fULtcLnYZpv+PZ5SZr/lk9hKo3eCig==", ++ "version": "3.2.0", ++ "resolved": "https://registry.npmjs.org/@antora/ui-loader/-/ui-loader-3.2.0.tgz", ++ "integrity": "sha512-EYagiuG2Tk5QtnG/rwTzu/8mxDtL8J2oqZc74g0h4h3iatJeD8yNrDc8iDhNaycEZNaxPRfIK73tpKuIFZw+Iw==", + "license": "MPL-2.0", + "dependencies": { + "@antora/expand-path-helper": "~3.0", +@@ -412,7 +310,7 @@ + "cache-directory": "~2.0", + "fast-glob": "~3.3", + "hpagent": "~1.2", +- "js-yaml": "~4.2", ++ "js-yaml": "~5.4", + "picomatch": "~4.0", + "should-proxy": "~1.0", + "simple-get": "~4.0", +@@ -424,9 +322,9 @@ + } + }, + "node_modules/@antora/ui-loader/node_modules/js-yaml": { +- "version": "4.2.0", +- "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz", +- "integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==", ++ "version": "5.4.1", ++ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.4.1.tgz", ++ "integrity": "sha512-28R/k+NAjeuf7+CKlTxWZVExJGwVVLwY06DgEnOMz2gEpfNkDcD7QvyiVPT0xy0XXhU8vHsd4Ot42OOPdJG7dQ==", + "funding": [ + { + "type": "github", +@@ -442,7 +340,7 @@ + "argparse": "^2.0.1" + }, + "bin": { +- "js-yaml": "bin/js-yaml.js" ++ "js-yaml": "bin/js-yaml.mjs" + } + }, + "node_modules/@antora/user-require-helper": { +@@ -1628,9 +1526,9 @@ + } + }, + "node_modules/fastq": { +- "version": "1.20.1", +- "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", +- "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", ++ "version": "1.20.3", ++ "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", ++ "integrity": "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" +@@ -2526,9 +2424,9 @@ + "license": "MIT" + }, + "node_modules/picomatch": { +- "version": "4.0.5", +- "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.5.tgz", +- "integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==", ++ "version": "4.0.7", ++ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", ++ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "license": "MIT", + "engines": { + "node": ">=12" +diff --git a/antora/package.json b/antora/package.json +index 6772baec36a..beb07a51a52 100644 +--- a/antora/package.json ++++ b/antora/package.json +@@ -4,7 +4,7 @@ + }, + "dependencies": { + "@antora/cli": "3.2.0", +- "@antora/site-generator": "3.2.0-rc.3", ++ "@antora/site-generator": "3.2.0", + "@antora/atlas-extension": "1.0.0-alpha.5", + "@springio/antora-extensions": "1.14.13", + "@springio/antora-xref-extension": "1.0.0-alpha.5", diff --git a/tasks/spring-projects__spring-boot-51527/tests/test.sh b/tasks/spring-projects__spring-boot-51527/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..fd952014c82824d69574a246bf7516d53cedae6e --- /dev/null +++ b/tasks/spring-projects__spring-boot-51527/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d4fbe320f24f86c8e98f553a20ba95f4f5661850 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51527/tests/verifier.py b/tasks/spring-projects__spring-boot-51527/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51527/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51540/environment/Dockerfile b/tasks/spring-projects__spring-boot-51540/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a878ab6d7089403c62941e4bf9a3188563105369 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51540/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 05bd7202bae0efa11652c76ffd1fb8d3be4b6533 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 05bd7202bae0efa11652c76ffd1fb8d3be4b6533 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 05bd7202bae0efa11652c76ffd1fb8d3be4b6533 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51540/instruction.md b/tasks/spring-projects__spring-boot-51540/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..15a2aa119c575e21a3715d0a852cb84a596dda44 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51540/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** jarmode tools commands print stacktrace instead of an error message + +## Description + +Split out of #51505 at @mhalbritter's request. + +The tools jar mode wraps every exception in `IllegalStateException`, so a `JarModeErrorException` thrown by a command never reaches the branch of `JarModeRunner` that prints `Error: <message>`. Running `list-layers` against a jar built without layers shows a stack trace instead of `Error: Layers are not enabled`. + +`JarMode` declares `run` as `throws JarModeErrorException` "on an error that should print a simple error message", so the wrapping breaks that contract. It predates the exception: #43435 added JarModeErrorException` and converted `ExtractCommand` and `Layers`, but left `ToolsJarMode` alone. Rethrowing ahead of the generic catch restores the branch. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `05bd7202bae0`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51540/solution/patch.diff b/tasks/spring-projects__spring-boot-51540/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f3906483ac5b0f51338a73663cd0f55fb32e4045 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51540/solution/patch.diff @@ -0,0 +1,61 @@ +diff --git a/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/ToolsJarMode.java b/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/ToolsJarMode.java +index c8c705ea8d8..c9cfe51fcca 100644 +--- a/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/ToolsJarMode.java ++++ b/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/ToolsJarMode.java +@@ -22,11 +22,13 @@ import java.util.List; + import org.jspecify.annotations.Nullable; + + import org.springframework.boot.loader.jarmode.JarMode; ++import org.springframework.boot.loader.jarmode.JarModeErrorException; + + /** + * {@link JarMode} providing {@code "tools"} support. + * + * @author Moritz Halbritter ++ * @author Hyeongjun Cho + * @since 3.3.0 + */ + public class ToolsJarMode implements JarMode { +@@ -54,6 +56,9 @@ public class ToolsJarMode implements JarMode { + try { + new Runner(this.out, this.context, getCommands(this.context)).run(args); + } ++ catch (JarModeErrorException ex) { ++ throw ex; ++ } + catch (Exception ex) { + throw new IllegalStateException(ex); + } +diff --git a/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/ToolsJarModeTests.java b/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/ToolsJarModeTests.java +index de5ad3c9d60..fc4c401fefe 100644 +--- a/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/ToolsJarModeTests.java ++++ b/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/ToolsJarModeTests.java +@@ -21,12 +21,16 @@ import java.io.IOException; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + ++import org.springframework.boot.loader.jarmode.JarModeErrorException; ++ + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + + /** + * Tests for {@link ToolsJarMode}. + * + * @author Moritz Halbritter ++ * @author Hyeongjun Cho + */ + class ToolsJarModeTests extends AbstractJarModeTests { + +@@ -95,6 +99,11 @@ class ToolsJarModeTests extends AbstractJarModeTests { + assertThat(this.out).hasSameContentAsResource("tools-error-option-missing-value-output.txt"); + } + ++ @Test ++ void commandFailureIsThrownAsJarModeErrorException() { ++ assertThatExceptionOfType(JarModeErrorException.class).isThrownBy(() -> run("list-layers")); ++ } ++ + private void run(String... args) { + this.mode.run("tools", args); + } diff --git a/tasks/spring-projects__spring-boot-51540/solution/solve.sh b/tasks/spring-projects__spring-boot-51540/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51540/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51540/task.toml b/tasks/spring-projects__spring-boot-51540/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f37554c7848572d87057269934d4774674a2cdab --- /dev/null +++ b/tasks/spring-projects__spring-boot-51540/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51540" +description = "jarmode tools commands print stacktrace instead of an error message" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "05bd7202bae0efa11652c76ffd1fb8d3be4b6533" +reference = "https://github.com/spring-projects/spring-boot/pull/51540" +source_access = "auto" +built_at = "2026-11-16T16:09:44.788179+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:614da5d9bf6fa36761f0fbeb713da4d5f404480681de8bd1c748312bf57d6cc6" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-02T14:24:27Z" +diff_format = "unified" +context_files = [ + "loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/ToolsJarMode.java", + "loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/ToolsJarModeTests.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.166126+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9c6ac5ee4af293537d94af15585110031e5bdfc96553819e0ae65f740f1faa5a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51540/tests/capture.py b/tasks/spring-projects__spring-boot-51540/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51540/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51540/tests/instruction.md b/tasks/spring-projects__spring-boot-51540/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..15a2aa119c575e21a3715d0a852cb84a596dda44 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51540/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** jarmode tools commands print stacktrace instead of an error message + +## Description + +Split out of #51505 at @mhalbritter's request. + +The tools jar mode wraps every exception in `IllegalStateException`, so a `JarModeErrorException` thrown by a command never reaches the branch of `JarModeRunner` that prints `Error: <message>`. Running `list-layers` against a jar built without layers shows a stack trace instead of `Error: Layers are not enabled`. + +`JarMode` declares `run` as `throws JarModeErrorException` "on an error that should print a simple error message", so the wrapping breaks that contract. It predates the exception: #43435 added JarModeErrorException` and converted `ExtractCommand` and `Layers`, but left `ToolsJarMode` alone. Rethrowing ahead of the generic catch restores the branch. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `05bd7202bae0`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51540/tests/oracle.patch b/tasks/spring-projects__spring-boot-51540/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f3906483ac5b0f51338a73663cd0f55fb32e4045 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51540/tests/oracle.patch @@ -0,0 +1,61 @@ +diff --git a/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/ToolsJarMode.java b/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/ToolsJarMode.java +index c8c705ea8d8..c9cfe51fcca 100644 +--- a/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/ToolsJarMode.java ++++ b/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/ToolsJarMode.java +@@ -22,11 +22,13 @@ import java.util.List; + import org.jspecify.annotations.Nullable; + + import org.springframework.boot.loader.jarmode.JarMode; ++import org.springframework.boot.loader.jarmode.JarModeErrorException; + + /** + * {@link JarMode} providing {@code "tools"} support. + * + * @author Moritz Halbritter ++ * @author Hyeongjun Cho + * @since 3.3.0 + */ + public class ToolsJarMode implements JarMode { +@@ -54,6 +56,9 @@ public class ToolsJarMode implements JarMode { + try { + new Runner(this.out, this.context, getCommands(this.context)).run(args); + } ++ catch (JarModeErrorException ex) { ++ throw ex; ++ } + catch (Exception ex) { + throw new IllegalStateException(ex); + } +diff --git a/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/ToolsJarModeTests.java b/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/ToolsJarModeTests.java +index de5ad3c9d60..fc4c401fefe 100644 +--- a/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/ToolsJarModeTests.java ++++ b/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/ToolsJarModeTests.java +@@ -21,12 +21,16 @@ import java.io.IOException; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; + ++import org.springframework.boot.loader.jarmode.JarModeErrorException; ++ + import static org.assertj.core.api.Assertions.assertThat; ++import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + + /** + * Tests for {@link ToolsJarMode}. + * + * @author Moritz Halbritter ++ * @author Hyeongjun Cho + */ + class ToolsJarModeTests extends AbstractJarModeTests { + +@@ -95,6 +99,11 @@ class ToolsJarModeTests extends AbstractJarModeTests { + assertThat(this.out).hasSameContentAsResource("tools-error-option-missing-value-output.txt"); + } + ++ @Test ++ void commandFailureIsThrownAsJarModeErrorException() { ++ assertThatExceptionOfType(JarModeErrorException.class).isThrownBy(() -> run("list-layers")); ++ } ++ + private void run(String... args) { + this.mode.run("tools", args); + } diff --git a/tasks/spring-projects__spring-boot-51540/tests/test.sh b/tasks/spring-projects__spring-boot-51540/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..33e69acab3da7d2d4ea33946e16e435286d66860 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51540/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 05bd7202bae0efa11652c76ffd1fb8d3be4b6533 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51540/tests/verifier.py b/tasks/spring-projects__spring-boot-51540/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51540/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51546/environment/Dockerfile b/tasks/spring-projects__spring-boot-51546/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a878ab6d7089403c62941e4bf9a3188563105369 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51546/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 05bd7202bae0efa11652c76ffd1fb8d3be4b6533 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 05bd7202bae0efa11652c76ffd1fb8d3be4b6533 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 05bd7202bae0efa11652c76ffd1fb8d3be4b6533 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51546/instruction.md b/tasks/spring-projects__spring-boot-51546/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2448483a8f8d658aefc6b3dc7e9a1ec3cec6d1a5 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51546/instruction.md @@ -0,0 +1,95 @@ +# Issue + +**Title:** Docker Compose integration for RabbitMQ skips credential fallbacks when an environment variable has no value + +## Description + +## What happened? + +Docker records an environment variable declared without a value as a bare name. For example, with this Compose file and neither variable set on the host: + +```yaml +services: + rabbitmq: + image: rabbitmq + environment: + - RABBITMQ_DEFAULT_USER + - RABBITMQ_DEFAULT_PASS +``` + +`docker inspect` reports: + +```json +["RABBITMQ_DEFAULT_USER","RABBITMQ_DEFAULT_PASS","PATH=/usr/local/sbin:..."] +``` + +`DockerEnv` maps such an entry to a null value rather than omitting the key. `DockerEnvTests` covers this directly: + +```java +@Test +void createParsesEnv() { + DockerEnv env = new DockerEnv(List.of("a=b", "c")); + assertThat(env.asMap()).containsExactly(entry("a", "b"), entry("c", null)); +} +``` + +`RabbitEnvironment` reads these entries with `Map.getOrDefault`: + +```java +this.username = env.getOrDefault("RABBITMQ_DEFAULT_USER", env.getOrDefault("RABBITMQ_USERNAME", "guest")); +this.password = env.getOrDefault("RABBITMQ_DEFAULT_PASS", env.getOrDefault("RABBITMQ_PASSWORD", "guest")); +``` + +`getOrDefault` returns the default only when the key is absent, so it returns null when the key is present but mapped to null. For the username, this bypasses both the `RABBITMQ_USERNAME` fallback and the `guest` default. The same problem affects the password. + +The other environment classes in this area check for null before falling back. For example, `PostgresEnvironment` uses: + +```java +private String extract(Map<String, @Nullable String> env, String[] keys, String defaultValue) { + for (String key : keys) { + String value = env.get(key); + if (value != null) { + return value; + } + } + return defaultValue; +} +``` + +`MySqlEnvironment`, `MariaDbEnvironment`, `OracleEnvironment`, `ClickHouseEnvironment` and `SqlServerEnvironment` follow the same approach. + +When no fallback credentials are configured, the existing consumers mask the missing default. `RabbitConnectionFactoryBeanConfigurer` and `RabbitStreamConfiguration` filter out null values through `PropertyMapper`, leaving the connection factories to use their own `guest` defaults. + +However, when a primary key is present with a null value and its fallback key has a value, `RabbitEnvironment` ignores the configured fallback. For example, if `RABBITMQ_DEFAULT_USER` is null and `RABBITMQ_USERNAME` is `alice`, `getUsername()` returns null instead of `alice`. + +## What does this PR change? + +`RabbitEnvironment` now reads each key with `get` and falls back when the value is null, matching the sibling classes: + +```java +private static String extract(Map<String, @Nullable String> env, String key, String fallbackKey) { + String value = env.get(key); + value = (value != null) ? value : env.get(fallbackKey); + return (value != null) ? value : "guest"; +} +``` + +A non-null primary value is preserved. Otherwise, the fallback value is used, or `guest` if neither key has a non-null value. Empty strings are still treated as explicit values. + +There are no public API changes. + +## Tests + +Added to `RabbitEnvironmentTests`: + +- `getUsernameWhenRabbitmqDefaultUserHasNoValue`, where `RABBITMQ_DEFAULT_USER` is present with a null value +- `getPasswordWhenRabbitmqDefaultPassHasNoValue`, where `RABBITMQ_DEFAULT_PASS` is present with a null value +- `getUsernameWhenRabbitmqDefaultUserHasNoValueAndHasRabbitmqUsername`, where the fallback key should still be used + +All three fail without the change. + +`:module:spring-boot-amqp:test`, `checkFormatMain`, `checkFormatTest`, `checkstyleMain` and `checkstyleTest` pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `05bd7202bae0`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51546/solution/patch.diff b/tasks/spring-projects__spring-boot-51546/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9753a9ef302d800ff3a2eee5e40da87072645ed7 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51546/solution/patch.diff @@ -0,0 +1,66 @@ +diff --git a/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironment.java b/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironment.java +index bc776b015db..0fa34bc1524 100644 +--- a/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironment.java ++++ b/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironment.java +@@ -35,8 +35,14 @@ class RabbitEnvironment { + private final @Nullable String password; + + RabbitEnvironment(Map<String, @Nullable String> env) { +- this.username = env.getOrDefault("RABBITMQ_DEFAULT_USER", env.getOrDefault("RABBITMQ_USERNAME", "guest")); +- this.password = env.getOrDefault("RABBITMQ_DEFAULT_PASS", env.getOrDefault("RABBITMQ_PASSWORD", "guest")); ++ this.username = extract(env, "RABBITMQ_DEFAULT_USER", "RABBITMQ_USERNAME"); ++ this.password = extract(env, "RABBITMQ_DEFAULT_PASS", "RABBITMQ_PASSWORD"); ++ } ++ ++ private static String extract(Map<String, @Nullable String> env, String key, String fallbackKey) { ++ String value = env.get(key); ++ value = (value != null) ? value : env.get(fallbackKey); ++ return (value != null) ? value : "guest"; + } + + @Nullable String getUsername() { +diff --git a/module/spring-boot-amqp/src/test/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironmentTests.java b/module/spring-boot-amqp/src/test/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironmentTests.java +index 1ecb0b4d6ff..734e5cc4ae0 100644 +--- a/module/spring-boot-amqp/src/test/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironmentTests.java ++++ b/module/spring-boot-amqp/src/test/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironmentTests.java +@@ -17,8 +17,10 @@ + package org.springframework.boot.amqp.docker.compose; + + import java.util.Collections; ++import java.util.HashMap; + import java.util.Map; + ++import org.jspecify.annotations.Nullable; + import org.junit.jupiter.api.Test; + + import static org.assertj.core.api.Assertions.assertThat; +@@ -69,4 +71,29 @@ class RabbitEnvironmentTests { + assertThat(environment.getPassword()).isEqualTo("secret"); + } + ++ @Test ++ void getUsernameWhenRabbitmqDefaultUserHasNoValue() { ++ Map<String, @Nullable String> env = new HashMap<>(); ++ env.put("RABBITMQ_DEFAULT_USER", null); ++ RabbitEnvironment environment = new RabbitEnvironment(env); ++ assertThat(environment.getUsername()).isEqualTo("guest"); ++ } ++ ++ @Test ++ void getPasswordWhenRabbitmqDefaultPassHasNoValue() { ++ Map<String, @Nullable String> env = new HashMap<>(); ++ env.put("RABBITMQ_DEFAULT_PASS", null); ++ RabbitEnvironment environment = new RabbitEnvironment(env); ++ assertThat(environment.getPassword()).isEqualTo("guest"); ++ } ++ ++ @Test ++ void getUsernameWhenRabbitmqDefaultUserHasNoValueAndHasRabbitmqUsername() { ++ Map<String, @Nullable String> env = new HashMap<>(); ++ env.put("RABBITMQ_DEFAULT_USER", null); ++ env.put("RABBITMQ_USERNAME", "me"); ++ RabbitEnvironment environment = new RabbitEnvironment(env); ++ assertThat(environment.getUsername()).isEqualTo("me"); ++ } ++ + } diff --git a/tasks/spring-projects__spring-boot-51546/solution/solve.sh b/tasks/spring-projects__spring-boot-51546/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51546/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51546/task.toml b/tasks/spring-projects__spring-boot-51546/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2fb78f1cc7084a4d7295eaebf7038737ef08ce67 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51546/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51546" +description = "Docker Compose integration for RabbitMQ skips credential fallbacks when an environment variable has no value" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "05bd7202bae0efa11652c76ffd1fb8d3be4b6533" +reference = "https://github.com/spring-projects/spring-boot/pull/51546" +source_access = "auto" +built_at = "2026-11-16T16:09:44.782371+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a0bf09e7d29149d9a4ef1f162e724ff90c0846e19e4a529a897cdd6deeaa40f5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-04T09:53:22Z" +diff_format = "unified" +context_files = [ + "module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironment.java", + "module/spring-boot-amqp/src/test/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironmentTests.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 37 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.166714+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9c6ac5ee4af293537d94af15585110031e5bdfc96553819e0ae65f740f1faa5a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51546/tests/capture.py b/tasks/spring-projects__spring-boot-51546/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51546/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51546/tests/instruction.md b/tasks/spring-projects__spring-boot-51546/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2448483a8f8d658aefc6b3dc7e9a1ec3cec6d1a5 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51546/tests/instruction.md @@ -0,0 +1,95 @@ +# Issue + +**Title:** Docker Compose integration for RabbitMQ skips credential fallbacks when an environment variable has no value + +## Description + +## What happened? + +Docker records an environment variable declared without a value as a bare name. For example, with this Compose file and neither variable set on the host: + +```yaml +services: + rabbitmq: + image: rabbitmq + environment: + - RABBITMQ_DEFAULT_USER + - RABBITMQ_DEFAULT_PASS +``` + +`docker inspect` reports: + +```json +["RABBITMQ_DEFAULT_USER","RABBITMQ_DEFAULT_PASS","PATH=/usr/local/sbin:..."] +``` + +`DockerEnv` maps such an entry to a null value rather than omitting the key. `DockerEnvTests` covers this directly: + +```java +@Test +void createParsesEnv() { + DockerEnv env = new DockerEnv(List.of("a=b", "c")); + assertThat(env.asMap()).containsExactly(entry("a", "b"), entry("c", null)); +} +``` + +`RabbitEnvironment` reads these entries with `Map.getOrDefault`: + +```java +this.username = env.getOrDefault("RABBITMQ_DEFAULT_USER", env.getOrDefault("RABBITMQ_USERNAME", "guest")); +this.password = env.getOrDefault("RABBITMQ_DEFAULT_PASS", env.getOrDefault("RABBITMQ_PASSWORD", "guest")); +``` + +`getOrDefault` returns the default only when the key is absent, so it returns null when the key is present but mapped to null. For the username, this bypasses both the `RABBITMQ_USERNAME` fallback and the `guest` default. The same problem affects the password. + +The other environment classes in this area check for null before falling back. For example, `PostgresEnvironment` uses: + +```java +private String extract(Map<String, @Nullable String> env, String[] keys, String defaultValue) { + for (String key : keys) { + String value = env.get(key); + if (value != null) { + return value; + } + } + return defaultValue; +} +``` + +`MySqlEnvironment`, `MariaDbEnvironment`, `OracleEnvironment`, `ClickHouseEnvironment` and `SqlServerEnvironment` follow the same approach. + +When no fallback credentials are configured, the existing consumers mask the missing default. `RabbitConnectionFactoryBeanConfigurer` and `RabbitStreamConfiguration` filter out null values through `PropertyMapper`, leaving the connection factories to use their own `guest` defaults. + +However, when a primary key is present with a null value and its fallback key has a value, `RabbitEnvironment` ignores the configured fallback. For example, if `RABBITMQ_DEFAULT_USER` is null and `RABBITMQ_USERNAME` is `alice`, `getUsername()` returns null instead of `alice`. + +## What does this PR change? + +`RabbitEnvironment` now reads each key with `get` and falls back when the value is null, matching the sibling classes: + +```java +private static String extract(Map<String, @Nullable String> env, String key, String fallbackKey) { + String value = env.get(key); + value = (value != null) ? value : env.get(fallbackKey); + return (value != null) ? value : "guest"; +} +``` + +A non-null primary value is preserved. Otherwise, the fallback value is used, or `guest` if neither key has a non-null value. Empty strings are still treated as explicit values. + +There are no public API changes. + +## Tests + +Added to `RabbitEnvironmentTests`: + +- `getUsernameWhenRabbitmqDefaultUserHasNoValue`, where `RABBITMQ_DEFAULT_USER` is present with a null value +- `getPasswordWhenRabbitmqDefaultPassHasNoValue`, where `RABBITMQ_DEFAULT_PASS` is present with a null value +- `getUsernameWhenRabbitmqDefaultUserHasNoValueAndHasRabbitmqUsername`, where the fallback key should still be used + +All three fail without the change. + +`:module:spring-boot-amqp:test`, `checkFormatMain`, `checkFormatTest`, `checkstyleMain` and `checkstyleTest` pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `05bd7202bae0`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51546/tests/oracle.patch b/tasks/spring-projects__spring-boot-51546/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9753a9ef302d800ff3a2eee5e40da87072645ed7 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51546/tests/oracle.patch @@ -0,0 +1,66 @@ +diff --git a/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironment.java b/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironment.java +index bc776b015db..0fa34bc1524 100644 +--- a/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironment.java ++++ b/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironment.java +@@ -35,8 +35,14 @@ class RabbitEnvironment { + private final @Nullable String password; + + RabbitEnvironment(Map<String, @Nullable String> env) { +- this.username = env.getOrDefault("RABBITMQ_DEFAULT_USER", env.getOrDefault("RABBITMQ_USERNAME", "guest")); +- this.password = env.getOrDefault("RABBITMQ_DEFAULT_PASS", env.getOrDefault("RABBITMQ_PASSWORD", "guest")); ++ this.username = extract(env, "RABBITMQ_DEFAULT_USER", "RABBITMQ_USERNAME"); ++ this.password = extract(env, "RABBITMQ_DEFAULT_PASS", "RABBITMQ_PASSWORD"); ++ } ++ ++ private static String extract(Map<String, @Nullable String> env, String key, String fallbackKey) { ++ String value = env.get(key); ++ value = (value != null) ? value : env.get(fallbackKey); ++ return (value != null) ? value : "guest"; + } + + @Nullable String getUsername() { +diff --git a/module/spring-boot-amqp/src/test/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironmentTests.java b/module/spring-boot-amqp/src/test/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironmentTests.java +index 1ecb0b4d6ff..734e5cc4ae0 100644 +--- a/module/spring-boot-amqp/src/test/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironmentTests.java ++++ b/module/spring-boot-amqp/src/test/java/org/springframework/boot/amqp/docker/compose/RabbitEnvironmentTests.java +@@ -17,8 +17,10 @@ + package org.springframework.boot.amqp.docker.compose; + + import java.util.Collections; ++import java.util.HashMap; + import java.util.Map; + ++import org.jspecify.annotations.Nullable; + import org.junit.jupiter.api.Test; + + import static org.assertj.core.api.Assertions.assertThat; +@@ -69,4 +71,29 @@ class RabbitEnvironmentTests { + assertThat(environment.getPassword()).isEqualTo("secret"); + } + ++ @Test ++ void getUsernameWhenRabbitmqDefaultUserHasNoValue() { ++ Map<String, @Nullable String> env = new HashMap<>(); ++ env.put("RABBITMQ_DEFAULT_USER", null); ++ RabbitEnvironment environment = new RabbitEnvironment(env); ++ assertThat(environment.getUsername()).isEqualTo("guest"); ++ } ++ ++ @Test ++ void getPasswordWhenRabbitmqDefaultPassHasNoValue() { ++ Map<String, @Nullable String> env = new HashMap<>(); ++ env.put("RABBITMQ_DEFAULT_PASS", null); ++ RabbitEnvironment environment = new RabbitEnvironment(env); ++ assertThat(environment.getPassword()).isEqualTo("guest"); ++ } ++ ++ @Test ++ void getUsernameWhenRabbitmqDefaultUserHasNoValueAndHasRabbitmqUsername() { ++ Map<String, @Nullable String> env = new HashMap<>(); ++ env.put("RABBITMQ_DEFAULT_USER", null); ++ env.put("RABBITMQ_USERNAME", "me"); ++ RabbitEnvironment environment = new RabbitEnvironment(env); ++ assertThat(environment.getUsername()).isEqualTo("me"); ++ } ++ + } diff --git a/tasks/spring-projects__spring-boot-51546/tests/test.sh b/tasks/spring-projects__spring-boot-51546/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..33e69acab3da7d2d4ea33946e16e435286d66860 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51546/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 05bd7202bae0efa11652c76ffd1fb8d3be4b6533 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51546/tests/verifier.py b/tasks/spring-projects__spring-boot-51546/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51546/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51549/environment/Dockerfile b/tasks/spring-projects__spring-boot-51549/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..103667988270580daa8d2a4d9af7dfc295ddbabf --- /dev/null +++ b/tasks/spring-projects__spring-boot-51549/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1d79f56ad7ea82bd1ed3402a684d4c4a8659d4b1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1d79f56ad7ea82bd1ed3402a684d4c4a8659d4b1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1d79f56ad7ea82bd1ed3402a684d4c4a8659d4b1 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51549/instruction.md b/tasks/spring-projects__spring-boot-51549/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ffcf43296731ef39a05763798e2c376e6d3bf340 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51549/instruction.md @@ -0,0 +1,49 @@ +# Issue + +**Title:** Custom Spring Security firewall is lost when using spring-boot-cloudfoundry and Actuator in a reactive web application + +## Description + +Hi team, + +This PR addresses an issue where custom ServerWebExchangeFirewall configurations are lost when running reactive applications on Cloud Foundry. + +What was happening? +When VCAP_APPLICATION is present, CloudFoundryReactiveActuatorAutoConfiguration used a BeanPostProcessor (WebFilterChainPostProcessor) to wrap WebFilterChainProxy. + +The trouble with that approach is that instantiating a new WebFilterChainProxy creates a fresh instance with its private firewall field defaulting to new StrictServerWebExchangeFirewall(). As a result: + +Any custom ServerWebExchangeFirewall bean declared by the user was discarded. +Direct customizations (e.g. calling setFirewall(...) on the proxy) were also lost. +Incoming requests were evaluated by the new proxy's strict firewall at the perimeter, rejecting valid requests that rely on customized firewall rules (like matrix parameters or specific URI encodings). +The Fix +Following @wilkinsona's suggestion in #45377, we aligned the reactive configuration with how the servlet side already handles this in IgnoredCloudFoundryPathsWebSecurityConfiguration: + +Removed WebFilterChainPostProcessor. +Added a dedicated @Order(-1) SecurityWebFilterChain bean matching /cloudfoundryapplication/** with permitAll(), csrf.disable(), and CORS configuration. +This allows Spring Security's native ServerHttpSecurityConfiguration to create and keep the single WebFilterChainProxy. Cloud Foundry routes are given higher precedence to bypass authentication, while the rest of the application's security configuration and the user's custom firewall remain completely untouched. + +How this was verified +Added regression tests in CloudFoundryReactiveActuatorAutoConfigurationTests: + +customFirewallBeanIsPreserved: Asserts that a custom ServerWebExchangeFirewall @Bean stays on WebFilterChainProxy. +directlyConfiguredFirewallIsPreserved: Asserts that firewalls set directly via proxy.setFirewall(...) in a post-processor survive. +customFirewallIsInvokedOnRequests: Verifies runtime execution of firewall.getFirewalledExchange(...). +userSecurityWebFilterChainIsPreserved: Confirms that user-defined SecurityWebFilterChain beans coexist alongside the Cloud Foundry chain with correct ordering. +Ran: + +bash +./gradlew :module:spring-boot-cloudfoundry:test +./gradlew :module:spring-boot-cloudfoundry:check +All reactive tests, servlet tests, checkstyle, and Spring JavaFormat checks pass cleanly. + +Contributor Checklist + Signed-off-by trailer included in commit for DCO + Code formatted with Spring JavaFormat + Checkstyle checks pass + @author tag added + Unit/slice regression tests added + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1d79f56ad7ea`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51549/solution/patch.diff b/tasks/spring-projects__spring-boot-51549/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..83d45d93f23d7d327cab3b16081887c9f317d456 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51549/solution/patch.diff @@ -0,0 +1,267 @@ +diff --git a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfiguration.java b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfiguration.java +index 2ca73137091..696b8804607 100644 +--- a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfiguration.java ++++ b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfiguration.java +@@ -24,9 +24,7 @@ import java.util.List; + + import org.jspecify.annotations.Nullable; + +-import org.springframework.beans.BeansException; + import org.springframework.beans.factory.ObjectProvider; +-import org.springframework.beans.factory.config.BeanPostProcessor; + import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint; + import org.springframework.boot.actuate.autoconfigure.info.InfoEndpointAutoConfiguration; + import org.springframework.boot.actuate.endpoint.ExposableEndpoint; +@@ -56,22 +54,25 @@ import org.springframework.boot.info.GitProperties; + import org.springframework.context.ApplicationContext; + import org.springframework.context.annotation.Bean; + import org.springframework.context.annotation.Configuration; ++import org.springframework.core.Ordered; ++import org.springframework.core.annotation.Order; + import org.springframework.core.env.Environment; + import org.springframework.http.HttpHeaders; + import org.springframework.http.HttpMethod; +-import org.springframework.security.web.server.MatcherSecurityWebFilterChain; ++import org.springframework.security.config.web.server.ServerHttpSecurity; ++import org.springframework.security.web.server.SecurityWebFilterChain; + import org.springframework.security.web.server.WebFilterChainProxy; + import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; + import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers; + import org.springframework.web.cors.CorsConfiguration; + import org.springframework.web.reactive.function.client.WebClient; +-import org.springframework.web.server.WebFilter; + + /** + * {@link EnableAutoConfiguration Auto-configuration} to expose actuator endpoints for + * Cloud Foundry to use in a reactive environment. + * + * @author Madhura Bhave ++ * @author Aashikant Kumar + * @since 4.0.0 + */ + @AutoConfiguration(after = InfoEndpointAutoConfiguration.class, +@@ -133,7 +134,7 @@ public final class CloudFoundryReactiveActuatorAutoConfiguration { + ? new SecurityService(webClientBuilder, cloudControllerUrl, skipSslValidation) : null; + } + +- private CorsConfiguration getCorsConfiguration() { ++ private static CorsConfiguration getCorsConfiguration() { + CorsConfiguration corsConfiguration = new CorsConfiguration(); + corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL); + corsConfiguration.setAllowedMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); +@@ -158,38 +159,21 @@ public final class CloudFoundryReactiveActuatorAutoConfiguration { + } + + @Configuration(proxyBeanMethods = false) +- @ConditionalOnClass(MatcherSecurityWebFilterChain.class) +- static class IgnoredPathsSecurityConfiguration { ++ @ConditionalOnClass({ ServerHttpSecurity.class, SecurityWebFilterChain.class, WebFilterChainProxy.class }) ++ static class PermitAllCloudFoundrySecurityConfiguration { + +- @Bean +- static WebFilterChainPostProcessor webFilterChainPostProcessor() { +- return new WebFilterChainPostProcessor(); +- } +- +- } +- +- static class WebFilterChainPostProcessor implements BeanPostProcessor { ++ private static final int FILTER_CHAIN_ORDER = Ordered.HIGHEST_PRECEDENCE; + +- WebFilterChainPostProcessor() { +- } +- +- @Override +- public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { +- if (bean instanceof WebFilterChainProxy webFilterChainProxy) { +- return postProcess(webFilterChainProxy); +- } +- return bean; +- } +- +- private WebFilterChainProxy postProcess(WebFilterChainProxy existing) { +- ServerWebExchangeMatcher cloudFoundryRequestMatcher = ServerWebExchangeMatchers +- .pathMatchers(BASE_PATH + "/**"); +- WebFilter noOpFilter = (exchange, chain) -> chain.filter(exchange); +- MatcherSecurityWebFilterChain ignoredRequestFilterChain = new MatcherSecurityWebFilterChain( +- cloudFoundryRequestMatcher, Collections.singletonList(noOpFilter)); +- MatcherSecurityWebFilterChain allRequestsFilterChain = new MatcherSecurityWebFilterChain( +- ServerWebExchangeMatchers.anyExchange(), Collections.singletonList(existing)); +- return new WebFilterChainProxy(ignoredRequestFilterChain, allRequestsFilterChain); ++ @Bean ++ @Order(FILTER_CHAIN_ORDER) ++ SecurityWebFilterChain cloudFoundrySecurityWebFilterChain(ServerHttpSecurity http) { ++ ServerWebExchangeMatcher cloudFoundryRequest = ServerWebExchangeMatchers.pathMatchers(BASE_PATH + "/**"); ++ http.securityMatcher(cloudFoundryRequest); ++ http.authorizeExchange((exchanges) -> exchanges.anyExchange().permitAll()); ++ http.csrf((csrf) -> csrf.disable()); ++ CorsConfiguration corsConfiguration = getCorsConfiguration(); ++ http.cors((cors) -> cors.configurationSource((exchange) -> corsConfiguration)); ++ return http.build(); + } + + } +diff --git a/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfigurationTests.java b/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfigurationTests.java +index 57f0ce66a0a..10964be67ff 100644 +--- a/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfigurationTests.java ++++ b/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfigurationTests.java +@@ -42,6 +42,7 @@ import org.springframework.boot.actuate.endpoint.ApiVersion; + import org.springframework.boot.actuate.endpoint.EndpointId; + import org.springframework.boot.actuate.endpoint.annotation.Endpoint; + import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; ++import org.springframework.boot.actuate.endpoint.annotation.WriteOperation; + import org.springframework.boot.actuate.endpoint.web.ExposableWebEndpoint; + import org.springframework.boot.actuate.endpoint.web.WebOperation; + import org.springframework.boot.actuate.endpoint.web.WebOperationRequestPredicate; +@@ -66,27 +67,35 @@ import org.springframework.boot.webflux.autoconfigure.WebFluxAutoConfiguration; + import org.springframework.context.ApplicationContext; + import org.springframework.context.annotation.Bean; + import org.springframework.context.annotation.Configuration; ++import org.springframework.http.HttpHeaders; + import org.springframework.http.HttpMethod; ++import org.springframework.http.HttpStatus; + import org.springframework.http.HttpStatusCode; ++import org.springframework.http.MediaType; + import org.springframework.http.ResponseEntity; + import org.springframework.mock.http.server.reactive.MockServerHttpRequest; + import org.springframework.mock.web.server.MockServerWebExchange; ++import org.springframework.security.config.web.server.ServerHttpSecurity; + import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; + import org.springframework.security.core.userdetails.User; + import org.springframework.security.web.server.SecurityWebFilterChain; + import org.springframework.security.web.server.WebFilterChainProxy; + import org.springframework.test.web.reactive.server.WebTestClient; + import org.springframework.web.cors.CorsConfiguration; ++import org.springframework.web.cors.reactive.CorsConfigurationSource; ++import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; + import org.springframework.web.reactive.function.client.WebClient; + + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatExceptionOfType; ++import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; + + /** + * Tests for {@link CloudFoundryReactiveActuatorAutoConfiguration}. + * + * @author Madhura Bhave + * @author Moritz Halbritter ++ * @author Aashikant Kumar + */ + class CloudFoundryReactiveActuatorAutoConfigurationTests { + +@@ -186,8 +195,9 @@ class CloudFoundryReactiveActuatorAutoConfigurationTests { + + @Test + @SuppressWarnings("unchecked") +- void cloudFoundryPathsIgnoredBySpringSecurity() { +- this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new) ++ void cloudFoundryPathsPermittedBySpringSecurity() { ++ this.contextRunner.withUserConfiguration(SecurityConfiguration.class) ++ .withBean(TestEndpoint.class, TestEndpoint::new) + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { +@@ -206,14 +216,64 @@ class CloudFoundryReactiveActuatorAutoConfigurationTests { + assertThat(cfRequestWithAdditionalPathMatches).isTrue(); + assertThat(otherCfRequestMatches).isTrue(); + assertThat(otherRequestMatches).isFalse(); +- otherRequestMatches = filters.get(1) +- .matches(MockServerWebExchange.from(MockServerHttpRequest.get("/some-other-path").build())) +- .block(Duration.ofSeconds(30)); +- assertThat(otherRequestMatches).isTrue(); + }); + }); + } + ++ @Test ++ void cloudFoundryPathsPermittedWithCsrfBySpringSecurity() { ++ this.contextRunner.withUserConfiguration(SecurityConfiguration.class) ++ .withBean(TestEndpoint.class, TestEndpoint::new) ++ .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") ++ .run((context) -> { ++ WebTestClient client = WebTestClient.bindToApplicationContext(context).apply(springSecurity()).build(); ++ client.post() ++ .uri(BASE_PATH + "/test?name=test") ++ .contentType(MediaType.APPLICATION_JSON) ++ .exchange() ++ .expectStatus() ++ .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); ++ // If CSRF fails we'll get a 403, if it works we get service unavailable ++ // because of "Cloud controller URL is not available" ++ }); ++ } ++ ++ @Test ++ void crossOriginRequestToCloudFoundryPathsPermittedBySpringSecurity() { ++ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); ++ source.registerCorsConfiguration("/**", new CorsConfiguration()); ++ this.contextRunner.withUserConfiguration(SecurityConfiguration.class) ++ .withBean(TestEndpoint.class, TestEndpoint::new) ++ .withBean("corsConfigurationSource", CorsConfigurationSource.class, () -> source) ++ .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") ++ .run((context) -> { ++ WebTestClient client = WebTestClient.bindToApplicationContext(context) ++ .apply(springSecurity()) ++ .configureClient() ++ .baseUrl("https://app.example.com") ++ .build(); ++ client.get() ++ .uri(BASE_PATH + "/test") ++ .header(HttpHeaders.ORIGIN, "elsewhere.example.com") ++ .exchange() ++ .expectStatus() ++ .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); ++ // If CORS fails we'll get a 403, if it works we get service unavailable ++ // because of "Cloud controller URL is not available" ++ }); ++ } ++ ++ @Test ++ void otherPathsRejectedBySpringSecurity() { ++ this.contextRunner.withUserConfiguration(SecurityConfiguration.class) ++ .withBean(TestEndpoint.class, TestEndpoint::new) ++ .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") ++ .run((context) -> { ++ WebTestClient client = WebTestClient.bindToApplicationContext(context).apply(springSecurity()).build(); ++ client.get().uri("/test").exchange().expectStatus().isEqualTo(HttpStatus.UNAUTHORIZED); ++ }); ++ } ++ + private static @Nullable Boolean getMatches(List<? extends SecurityWebFilterChain> filters, String urlTemplate) { + return filters.get(0) + .matches(MockServerWebExchange.from(MockServerHttpRequest.get(urlTemplate).build())) +@@ -257,7 +317,7 @@ class CloudFoundryReactiveActuatorAutoConfigurationTests { + .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())) + .findFirst() + .get(); +- assertThat(endpoint.getOperations()).hasSize(1); ++ assertThat(endpoint.getOperations()).hasSize(2); + WebOperation operation = endpoint.getOperations().iterator().next(); + assertThat(operation.getRequestPredicate().getPath()).isEqualTo("test"); + }); +@@ -387,6 +447,10 @@ class CloudFoundryReactiveActuatorAutoConfigurationTests { + return "hello world"; + } + ++ @WriteOperation ++ void update(String name) { ++ } ++ + } + + @Configuration(proxyBeanMethods = false) +@@ -400,4 +464,14 @@ class CloudFoundryReactiveActuatorAutoConfigurationTests { + + } + ++ @Configuration(proxyBeanMethods = false) ++ static class SecurityConfiguration { ++ ++ @Bean ++ SecurityWebFilterChain appSecurity(ServerHttpSecurity httpSecurity) { ++ return httpSecurity.authorizeExchange((spec) -> spec.anyExchange().denyAll()).build(); ++ } ++ ++ } ++ + } diff --git a/tasks/spring-projects__spring-boot-51549/solution/solve.sh b/tasks/spring-projects__spring-boot-51549/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51549/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51549/task.toml b/tasks/spring-projects__spring-boot-51549/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8777047cf9322963468dda4f6e0839ecf1829b30 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51549/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51549" +description = "Custom Spring Security firewall is lost when using spring-boot-cloudfoundry and Actuator in a reactive web application" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "1d79f56ad7ea82bd1ed3402a684d4c4a8659d4b1" +reference = "https://github.com/spring-projects/spring-boot/pull/51549" +source_access = "auto" +built_at = "2026-11-16T16:09:44.739886+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:393663ab4d77bb0d496cce03f958c8c87378368d92d2bd1069efe03276faa4f3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-08T08:20:39Z" +diff_format = "unified" +context_files = [ + "module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfiguration.java", + "module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfigurationTests.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 142 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.167328+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6b725c586435f4fc5716afe19d435184f83adcf80c457e11f7ded726c3a3f114" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51549/tests/capture.py b/tasks/spring-projects__spring-boot-51549/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51549/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51549/tests/instruction.md b/tasks/spring-projects__spring-boot-51549/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ffcf43296731ef39a05763798e2c376e6d3bf340 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51549/tests/instruction.md @@ -0,0 +1,49 @@ +# Issue + +**Title:** Custom Spring Security firewall is lost when using spring-boot-cloudfoundry and Actuator in a reactive web application + +## Description + +Hi team, + +This PR addresses an issue where custom ServerWebExchangeFirewall configurations are lost when running reactive applications on Cloud Foundry. + +What was happening? +When VCAP_APPLICATION is present, CloudFoundryReactiveActuatorAutoConfiguration used a BeanPostProcessor (WebFilterChainPostProcessor) to wrap WebFilterChainProxy. + +The trouble with that approach is that instantiating a new WebFilterChainProxy creates a fresh instance with its private firewall field defaulting to new StrictServerWebExchangeFirewall(). As a result: + +Any custom ServerWebExchangeFirewall bean declared by the user was discarded. +Direct customizations (e.g. calling setFirewall(...) on the proxy) were also lost. +Incoming requests were evaluated by the new proxy's strict firewall at the perimeter, rejecting valid requests that rely on customized firewall rules (like matrix parameters or specific URI encodings). +The Fix +Following @wilkinsona's suggestion in #45377, we aligned the reactive configuration with how the servlet side already handles this in IgnoredCloudFoundryPathsWebSecurityConfiguration: + +Removed WebFilterChainPostProcessor. +Added a dedicated @Order(-1) SecurityWebFilterChain bean matching /cloudfoundryapplication/** with permitAll(), csrf.disable(), and CORS configuration. +This allows Spring Security's native ServerHttpSecurityConfiguration to create and keep the single WebFilterChainProxy. Cloud Foundry routes are given higher precedence to bypass authentication, while the rest of the application's security configuration and the user's custom firewall remain completely untouched. + +How this was verified +Added regression tests in CloudFoundryReactiveActuatorAutoConfigurationTests: + +customFirewallBeanIsPreserved: Asserts that a custom ServerWebExchangeFirewall @Bean stays on WebFilterChainProxy. +directlyConfiguredFirewallIsPreserved: Asserts that firewalls set directly via proxy.setFirewall(...) in a post-processor survive. +customFirewallIsInvokedOnRequests: Verifies runtime execution of firewall.getFirewalledExchange(...). +userSecurityWebFilterChainIsPreserved: Confirms that user-defined SecurityWebFilterChain beans coexist alongside the Cloud Foundry chain with correct ordering. +Ran: + +bash +./gradlew :module:spring-boot-cloudfoundry:test +./gradlew :module:spring-boot-cloudfoundry:check +All reactive tests, servlet tests, checkstyle, and Spring JavaFormat checks pass cleanly. + +Contributor Checklist + Signed-off-by trailer included in commit for DCO + Code formatted with Spring JavaFormat + Checkstyle checks pass + @author tag added + Unit/slice regression tests added + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1d79f56ad7ea`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51549/tests/oracle.patch b/tasks/spring-projects__spring-boot-51549/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..83d45d93f23d7d327cab3b16081887c9f317d456 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51549/tests/oracle.patch @@ -0,0 +1,267 @@ +diff --git a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfiguration.java b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfiguration.java +index 2ca73137091..696b8804607 100644 +--- a/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfiguration.java ++++ b/module/spring-boot-cloudfoundry/src/main/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfiguration.java +@@ -24,9 +24,7 @@ import java.util.List; + + import org.jspecify.annotations.Nullable; + +-import org.springframework.beans.BeansException; + import org.springframework.beans.factory.ObjectProvider; +-import org.springframework.beans.factory.config.BeanPostProcessor; + import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint; + import org.springframework.boot.actuate.autoconfigure.info.InfoEndpointAutoConfiguration; + import org.springframework.boot.actuate.endpoint.ExposableEndpoint; +@@ -56,22 +54,25 @@ import org.springframework.boot.info.GitProperties; + import org.springframework.context.ApplicationContext; + import org.springframework.context.annotation.Bean; + import org.springframework.context.annotation.Configuration; ++import org.springframework.core.Ordered; ++import org.springframework.core.annotation.Order; + import org.springframework.core.env.Environment; + import org.springframework.http.HttpHeaders; + import org.springframework.http.HttpMethod; +-import org.springframework.security.web.server.MatcherSecurityWebFilterChain; ++import org.springframework.security.config.web.server.ServerHttpSecurity; ++import org.springframework.security.web.server.SecurityWebFilterChain; + import org.springframework.security.web.server.WebFilterChainProxy; + import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; + import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers; + import org.springframework.web.cors.CorsConfiguration; + import org.springframework.web.reactive.function.client.WebClient; +-import org.springframework.web.server.WebFilter; + + /** + * {@link EnableAutoConfiguration Auto-configuration} to expose actuator endpoints for + * Cloud Foundry to use in a reactive environment. + * + * @author Madhura Bhave ++ * @author Aashikant Kumar + * @since 4.0.0 + */ + @AutoConfiguration(after = InfoEndpointAutoConfiguration.class, +@@ -133,7 +134,7 @@ public final class CloudFoundryReactiveActuatorAutoConfiguration { + ? new SecurityService(webClientBuilder, cloudControllerUrl, skipSslValidation) : null; + } + +- private CorsConfiguration getCorsConfiguration() { ++ private static CorsConfiguration getCorsConfiguration() { + CorsConfiguration corsConfiguration = new CorsConfiguration(); + corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL); + corsConfiguration.setAllowedMethods(Arrays.asList(HttpMethod.GET.name(), HttpMethod.POST.name())); +@@ -158,38 +159,21 @@ public final class CloudFoundryReactiveActuatorAutoConfiguration { + } + + @Configuration(proxyBeanMethods = false) +- @ConditionalOnClass(MatcherSecurityWebFilterChain.class) +- static class IgnoredPathsSecurityConfiguration { ++ @ConditionalOnClass({ ServerHttpSecurity.class, SecurityWebFilterChain.class, WebFilterChainProxy.class }) ++ static class PermitAllCloudFoundrySecurityConfiguration { + +- @Bean +- static WebFilterChainPostProcessor webFilterChainPostProcessor() { +- return new WebFilterChainPostProcessor(); +- } +- +- } +- +- static class WebFilterChainPostProcessor implements BeanPostProcessor { ++ private static final int FILTER_CHAIN_ORDER = Ordered.HIGHEST_PRECEDENCE; + +- WebFilterChainPostProcessor() { +- } +- +- @Override +- public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { +- if (bean instanceof WebFilterChainProxy webFilterChainProxy) { +- return postProcess(webFilterChainProxy); +- } +- return bean; +- } +- +- private WebFilterChainProxy postProcess(WebFilterChainProxy existing) { +- ServerWebExchangeMatcher cloudFoundryRequestMatcher = ServerWebExchangeMatchers +- .pathMatchers(BASE_PATH + "/**"); +- WebFilter noOpFilter = (exchange, chain) -> chain.filter(exchange); +- MatcherSecurityWebFilterChain ignoredRequestFilterChain = new MatcherSecurityWebFilterChain( +- cloudFoundryRequestMatcher, Collections.singletonList(noOpFilter)); +- MatcherSecurityWebFilterChain allRequestsFilterChain = new MatcherSecurityWebFilterChain( +- ServerWebExchangeMatchers.anyExchange(), Collections.singletonList(existing)); +- return new WebFilterChainProxy(ignoredRequestFilterChain, allRequestsFilterChain); ++ @Bean ++ @Order(FILTER_CHAIN_ORDER) ++ SecurityWebFilterChain cloudFoundrySecurityWebFilterChain(ServerHttpSecurity http) { ++ ServerWebExchangeMatcher cloudFoundryRequest = ServerWebExchangeMatchers.pathMatchers(BASE_PATH + "/**"); ++ http.securityMatcher(cloudFoundryRequest); ++ http.authorizeExchange((exchanges) -> exchanges.anyExchange().permitAll()); ++ http.csrf((csrf) -> csrf.disable()); ++ CorsConfiguration corsConfiguration = getCorsConfiguration(); ++ http.cors((cors) -> cors.configurationSource((exchange) -> corsConfiguration)); ++ return http.build(); + } + + } +diff --git a/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfigurationTests.java b/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfigurationTests.java +index 57f0ce66a0a..10964be67ff 100644 +--- a/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfigurationTests.java ++++ b/module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/reactive/CloudFoundryReactiveActuatorAutoConfigurationTests.java +@@ -42,6 +42,7 @@ import org.springframework.boot.actuate.endpoint.ApiVersion; + import org.springframework.boot.actuate.endpoint.EndpointId; + import org.springframework.boot.actuate.endpoint.annotation.Endpoint; + import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; ++import org.springframework.boot.actuate.endpoint.annotation.WriteOperation; + import org.springframework.boot.actuate.endpoint.web.ExposableWebEndpoint; + import org.springframework.boot.actuate.endpoint.web.WebOperation; + import org.springframework.boot.actuate.endpoint.web.WebOperationRequestPredicate; +@@ -66,27 +67,35 @@ import org.springframework.boot.webflux.autoconfigure.WebFluxAutoConfiguration; + import org.springframework.context.ApplicationContext; + import org.springframework.context.annotation.Bean; + import org.springframework.context.annotation.Configuration; ++import org.springframework.http.HttpHeaders; + import org.springframework.http.HttpMethod; ++import org.springframework.http.HttpStatus; + import org.springframework.http.HttpStatusCode; ++import org.springframework.http.MediaType; + import org.springframework.http.ResponseEntity; + import org.springframework.mock.http.server.reactive.MockServerHttpRequest; + import org.springframework.mock.web.server.MockServerWebExchange; ++import org.springframework.security.config.web.server.ServerHttpSecurity; + import org.springframework.security.core.userdetails.MapReactiveUserDetailsService; + import org.springframework.security.core.userdetails.User; + import org.springframework.security.web.server.SecurityWebFilterChain; + import org.springframework.security.web.server.WebFilterChainProxy; + import org.springframework.test.web.reactive.server.WebTestClient; + import org.springframework.web.cors.CorsConfiguration; ++import org.springframework.web.cors.reactive.CorsConfigurationSource; ++import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; + import org.springframework.web.reactive.function.client.WebClient; + + import static org.assertj.core.api.Assertions.assertThat; + import static org.assertj.core.api.Assertions.assertThatExceptionOfType; ++import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; + + /** + * Tests for {@link CloudFoundryReactiveActuatorAutoConfiguration}. + * + * @author Madhura Bhave + * @author Moritz Halbritter ++ * @author Aashikant Kumar + */ + class CloudFoundryReactiveActuatorAutoConfigurationTests { + +@@ -186,8 +195,9 @@ class CloudFoundryReactiveActuatorAutoConfigurationTests { + + @Test + @SuppressWarnings("unchecked") +- void cloudFoundryPathsIgnoredBySpringSecurity() { +- this.contextRunner.withBean(TestEndpoint.class, TestEndpoint::new) ++ void cloudFoundryPathsPermittedBySpringSecurity() { ++ this.contextRunner.withUserConfiguration(SecurityConfiguration.class) ++ .withBean(TestEndpoint.class, TestEndpoint::new) + .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id", + "vcap.application.cf_api:https://my-cloud-controller.com") + .run((context) -> { +@@ -206,14 +216,64 @@ class CloudFoundryReactiveActuatorAutoConfigurationTests { + assertThat(cfRequestWithAdditionalPathMatches).isTrue(); + assertThat(otherCfRequestMatches).isTrue(); + assertThat(otherRequestMatches).isFalse(); +- otherRequestMatches = filters.get(1) +- .matches(MockServerWebExchange.from(MockServerHttpRequest.get("/some-other-path").build())) +- .block(Duration.ofSeconds(30)); +- assertThat(otherRequestMatches).isTrue(); + }); + }); + } + ++ @Test ++ void cloudFoundryPathsPermittedWithCsrfBySpringSecurity() { ++ this.contextRunner.withUserConfiguration(SecurityConfiguration.class) ++ .withBean(TestEndpoint.class, TestEndpoint::new) ++ .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") ++ .run((context) -> { ++ WebTestClient client = WebTestClient.bindToApplicationContext(context).apply(springSecurity()).build(); ++ client.post() ++ .uri(BASE_PATH + "/test?name=test") ++ .contentType(MediaType.APPLICATION_JSON) ++ .exchange() ++ .expectStatus() ++ .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); ++ // If CSRF fails we'll get a 403, if it works we get service unavailable ++ // because of "Cloud controller URL is not available" ++ }); ++ } ++ ++ @Test ++ void crossOriginRequestToCloudFoundryPathsPermittedBySpringSecurity() { ++ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); ++ source.registerCorsConfiguration("/**", new CorsConfiguration()); ++ this.contextRunner.withUserConfiguration(SecurityConfiguration.class) ++ .withBean(TestEndpoint.class, TestEndpoint::new) ++ .withBean("corsConfigurationSource", CorsConfigurationSource.class, () -> source) ++ .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") ++ .run((context) -> { ++ WebTestClient client = WebTestClient.bindToApplicationContext(context) ++ .apply(springSecurity()) ++ .configureClient() ++ .baseUrl("https://app.example.com") ++ .build(); ++ client.get() ++ .uri(BASE_PATH + "/test") ++ .header(HttpHeaders.ORIGIN, "elsewhere.example.com") ++ .exchange() ++ .expectStatus() ++ .isEqualTo(HttpStatus.SERVICE_UNAVAILABLE); ++ // If CORS fails we'll get a 403, if it works we get service unavailable ++ // because of "Cloud controller URL is not available" ++ }); ++ } ++ ++ @Test ++ void otherPathsRejectedBySpringSecurity() { ++ this.contextRunner.withUserConfiguration(SecurityConfiguration.class) ++ .withBean(TestEndpoint.class, TestEndpoint::new) ++ .withPropertyValues("VCAP_APPLICATION:---", "vcap.application.application_id:my-app-id") ++ .run((context) -> { ++ WebTestClient client = WebTestClient.bindToApplicationContext(context).apply(springSecurity()).build(); ++ client.get().uri("/test").exchange().expectStatus().isEqualTo(HttpStatus.UNAUTHORIZED); ++ }); ++ } ++ + private static @Nullable Boolean getMatches(List<? extends SecurityWebFilterChain> filters, String urlTemplate) { + return filters.get(0) + .matches(MockServerWebExchange.from(MockServerHttpRequest.get(urlTemplate).build())) +@@ -257,7 +317,7 @@ class CloudFoundryReactiveActuatorAutoConfigurationTests { + .filter((candidate) -> EndpointId.of("test").equals(candidate.getEndpointId())) + .findFirst() + .get(); +- assertThat(endpoint.getOperations()).hasSize(1); ++ assertThat(endpoint.getOperations()).hasSize(2); + WebOperation operation = endpoint.getOperations().iterator().next(); + assertThat(operation.getRequestPredicate().getPath()).isEqualTo("test"); + }); +@@ -387,6 +447,10 @@ class CloudFoundryReactiveActuatorAutoConfigurationTests { + return "hello world"; + } + ++ @WriteOperation ++ void update(String name) { ++ } ++ + } + + @Configuration(proxyBeanMethods = false) +@@ -400,4 +464,14 @@ class CloudFoundryReactiveActuatorAutoConfigurationTests { + + } + ++ @Configuration(proxyBeanMethods = false) ++ static class SecurityConfiguration { ++ ++ @Bean ++ SecurityWebFilterChain appSecurity(ServerHttpSecurity httpSecurity) { ++ return httpSecurity.authorizeExchange((spec) -> spec.anyExchange().denyAll()).build(); ++ } ++ ++ } ++ + } diff --git a/tasks/spring-projects__spring-boot-51549/tests/test.sh b/tasks/spring-projects__spring-boot-51549/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..01959129c07fc0de79505fe62a1b88d7f56a59c5 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51549/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 1d79f56ad7ea82bd1ed3402a684d4c4a8659d4b1 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51549/tests/verifier.py b/tasks/spring-projects__spring-boot-51549/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51549/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51555/environment/Dockerfile b/tasks/spring-projects__spring-boot-51555/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f5b6101f4375422ce7db173e2a8a8c990956dc28 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51555/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 982582d0df05203130f9abed2c5f45e802c7c05a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 982582d0df05203130f9abed2c5f45e802c7c05a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 982582d0df05203130f9abed2c5f45e802c7c05a \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51555/instruction.md b/tasks/spring-projects__spring-boot-51555/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ad946542a45b1d7d4a3e3ab313dd03d659679fd8 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51555/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** Fix unrecognized JSpecify nullable annotation locations + +## Description + +## Why + +NullAway’s new `JSpecifyUnrecognizedAnnotationLocation` checker found five `@Nullable` annotations in locations that JSpecify does not recognize. Those annotations do not express the intended nullness to JSpecify-aware tools. + +## What + +Move wildcard annotations onto their bounds, where JSpecify recognizes them, and remove annotations from a cast and a local-variable root type where the enclosing declarations already express or infer the nullable result. + +## How to verify + +- Built all `compileJava` tasks with the NullAway snapshot from uber/NullAway#1787 and `JSpecifyUnrecognizedAnnotationLocation` configured at `ERROR` severity. +- `./gradlew :core:spring-boot:test --tests org.springframework.boot.context.properties.PropertyMapperTests` +- `./gradlew :module:spring-boot-jpa:test --tests org.springframework.boot.jpa.EntityManagerFactoryBuilderTests` +- `./gradlew :module:spring-boot-webflux:test --tests org.springframework.boot.webflux.actuate.endpoint.web.AbstractWebFluxEndpointHandlerMappingTests` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `982582d0df05`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51555/solution/patch.diff b/tasks/spring-projects__spring-boot-51555/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..23e848128cdc163a29c6f109f6877c930b68ce5b --- /dev/null +++ b/tasks/spring-projects__spring-boot-51555/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/core/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java b/core/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java +index 222eae45cc7..bf1430e8b63 100644 +--- a/core/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java ++++ b/core/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java +@@ -430,7 +430,7 @@ public final class PropertyMapper { + * @param consumer the consumer that should accept the value if it's not been + * filtered + */ +- public void to(Consumer<@Nullable ? super T> consumer) { ++ public void to(Consumer<? super @Nullable T> consumer) { + Assert.notNull(consumer, "'consumer' must not be null"); + T value = getValue(); + if (value == null || test(value)) { +diff --git a/module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/actuate/endpoint/web/AbstractWebFluxEndpointHandlerMapping.java b/module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/actuate/endpoint/web/AbstractWebFluxEndpointHandlerMapping.java +index 72bd7471a0b..5460b40eb4e 100644 +--- a/module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/actuate/endpoint/web/AbstractWebFluxEndpointHandlerMapping.java ++++ b/module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/actuate/endpoint/web/AbstractWebFluxEndpointHandlerMapping.java +@@ -416,7 +416,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi + } + + private @Nullable Publisher<?> invoke(InvocationContext invocationContext) { +- return (@Nullable Publisher<?>) this.invoker.invoke(invocationContext); ++ return (Publisher<?>) this.invoker.invoke(invocationContext); + } + + private Map<String, Object> getArguments(ServerWebExchange exchange, @Nullable Map<String, String> body) { diff --git a/tasks/spring-projects__spring-boot-51555/solution/solve.sh b/tasks/spring-projects__spring-boot-51555/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51555/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51555/task.toml b/tasks/spring-projects__spring-boot-51555/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..47fc962db07a1fd1ff63fbe65e23fdd25b72081f --- /dev/null +++ b/tasks/spring-projects__spring-boot-51555/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51555" +description = "Fix unrecognized JSpecify nullable annotation locations" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "982582d0df05203130f9abed2c5f45e802c7c05a" +reference = "https://github.com/spring-projects/spring-boot/pull/51555" +source_access = "auto" +built_at = "2026-11-16T16:09:44.784243+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:003e34de48c504270e8088730ffb5a7985966b1dbf2c09a4102c74ecb1d34113" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-04T09:08:21Z" +diff_format = "unified" +context_files = [ + "core/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java", + "module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/actuate/endpoint/web/AbstractWebFluxEndpointHandlerMapping.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.167915+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:bc84af0a3331f280433ace6a632ae748232a5906ebb977de5c81942443dd2357" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51555/tests/capture.py b/tasks/spring-projects__spring-boot-51555/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51555/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51555/tests/instruction.md b/tasks/spring-projects__spring-boot-51555/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ad946542a45b1d7d4a3e3ab313dd03d659679fd8 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51555/tests/instruction.md @@ -0,0 +1,24 @@ +# Issue + +**Title:** Fix unrecognized JSpecify nullable annotation locations + +## Description + +## Why + +NullAway’s new `JSpecifyUnrecognizedAnnotationLocation` checker found five `@Nullable` annotations in locations that JSpecify does not recognize. Those annotations do not express the intended nullness to JSpecify-aware tools. + +## What + +Move wildcard annotations onto their bounds, where JSpecify recognizes them, and remove annotations from a cast and a local-variable root type where the enclosing declarations already express or infer the nullable result. + +## How to verify + +- Built all `compileJava` tasks with the NullAway snapshot from uber/NullAway#1787 and `JSpecifyUnrecognizedAnnotationLocation` configured at `ERROR` severity. +- `./gradlew :core:spring-boot:test --tests org.springframework.boot.context.properties.PropertyMapperTests` +- `./gradlew :module:spring-boot-jpa:test --tests org.springframework.boot.jpa.EntityManagerFactoryBuilderTests` +- `./gradlew :module:spring-boot-webflux:test --tests org.springframework.boot.webflux.actuate.endpoint.web.AbstractWebFluxEndpointHandlerMappingTests` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `982582d0df05`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51555/tests/oracle.patch b/tasks/spring-projects__spring-boot-51555/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..23e848128cdc163a29c6f109f6877c930b68ce5b --- /dev/null +++ b/tasks/spring-projects__spring-boot-51555/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/core/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java b/core/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java +index 222eae45cc7..bf1430e8b63 100644 +--- a/core/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java ++++ b/core/spring-boot/src/main/java/org/springframework/boot/context/properties/PropertyMapper.java +@@ -430,7 +430,7 @@ public final class PropertyMapper { + * @param consumer the consumer that should accept the value if it's not been + * filtered + */ +- public void to(Consumer<@Nullable ? super T> consumer) { ++ public void to(Consumer<? super @Nullable T> consumer) { + Assert.notNull(consumer, "'consumer' must not be null"); + T value = getValue(); + if (value == null || test(value)) { +diff --git a/module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/actuate/endpoint/web/AbstractWebFluxEndpointHandlerMapping.java b/module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/actuate/endpoint/web/AbstractWebFluxEndpointHandlerMapping.java +index 72bd7471a0b..5460b40eb4e 100644 +--- a/module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/actuate/endpoint/web/AbstractWebFluxEndpointHandlerMapping.java ++++ b/module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/actuate/endpoint/web/AbstractWebFluxEndpointHandlerMapping.java +@@ -416,7 +416,7 @@ public abstract class AbstractWebFluxEndpointHandlerMapping extends RequestMappi + } + + private @Nullable Publisher<?> invoke(InvocationContext invocationContext) { +- return (@Nullable Publisher<?>) this.invoker.invoke(invocationContext); ++ return (Publisher<?>) this.invoker.invoke(invocationContext); + } + + private Map<String, Object> getArguments(ServerWebExchange exchange, @Nullable Map<String, String> body) { diff --git a/tasks/spring-projects__spring-boot-51555/tests/test.sh b/tasks/spring-projects__spring-boot-51555/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b73f147974fe94f364999af5808f7aab46681234 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51555/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 982582d0df05203130f9abed2c5f45e802c7c05a > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51555/tests/verifier.py b/tasks/spring-projects__spring-boot-51555/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51555/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51568/environment/Dockerfile b/tasks/spring-projects__spring-boot-51568/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..219ee298e94eee7f029da186760068f2914b5f04 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51568/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 10190c7cc79420addb847eac7de801caa4356824 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 10190c7cc79420addb847eac7de801caa4356824 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 10190c7cc79420addb847eac7de801caa4356824 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51568/instruction.md b/tasks/spring-projects__spring-boot-51568/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..42b9d19c34a65722bfc88964e6cafa1744f674c5 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51568/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Some assertion messages name the wrong parameter + +## Description + +Three `Assert` messages name a parameter that doesn't exist on the method. In each case neighbouring code in the same class already uses the correct name: + +- `ClientHttpConnectorBuilder.of(Class<T> clientHttpConnectorType)` reports `'requestFactoryType'`, and the javadoc above it refers to `requestFactoryType` as well. Both look like leftovers from `ClientHttpRequestFactoryBuilder.of`. The `@param` tag and the `Assert.isTrue` on the following line already use the correct name. +- `HttpComponentsClientHttpConnectorBuilder.withHttpClientCustomizer(Consumer<HttpAsyncClientBuilder> httpClientCustomizer)` reports `'customizer'`, while `withConnectionManagerCustomizer` and `withConnectionConfigCustomizer` in the same class both use their parameter names. +- `JsonWriter.Member.as(Extractor<T, R> extractor)` reports `'adapter'`. The other four `Assert.notNull` calls on an `extractor` in that file all use `'extractor'`. + +The first two were part of #51509 and were correctly removed there as unrelated to the null check fix. This targets `main` rather than `4.0.x` since these are message-only corrections with no behaviour change. I also checked the rest of the codebase for the same pattern and these three are all I found. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `10190c7cc794`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51568/solution/patch.diff b/tasks/spring-projects__spring-boot-51568/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ba56f59ae5bf088578b660d467e17c57a75e1f19 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51568/solution/patch.diff @@ -0,0 +1,48 @@ +diff --git a/core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java b/core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java +index 5d85b91d7fa..8ee3ccba5fa 100644 +--- a/core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java ++++ b/core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java +@@ -451,7 +451,7 @@ public interface JsonWriter<T> { + */ + @SuppressWarnings("unchecked") + public <R> Member<R> as(Extractor<T, R> extractor) { +- Assert.notNull(extractor, "'adapter' must not be null"); ++ Assert.notNull(extractor, "'extractor' must not be null"); + Member<R> result = (Member<R>) this; + result.valueExtractor = this.valueExtractor.as(extractor::extract); + return result; +diff --git a/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/ClientHttpConnectorBuilder.java b/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/ClientHttpConnectorBuilder.java +index 89cbfcbb27c..d891ff5ce36 100644 +--- a/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/ClientHttpConnectorBuilder.java ++++ b/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/ClientHttpConnectorBuilder.java +@@ -127,7 +127,7 @@ public interface ClientHttpConnectorBuilder<T extends ClientHttpConnector> { + + /** + * Return a new {@link ClientHttpConnectorBuilder} for the given +- * {@code requestFactoryType}. The following implementations are supported: ++ * {@code clientHttpConnectorType}. The following implementations are supported: + * <ul> + * <li>{@link ReactorClientHttpConnector}</li> + * <li>{@link JettyClientHttpConnector}</li> +@@ -140,7 +140,7 @@ public interface ClientHttpConnectorBuilder<T extends ClientHttpConnector> { + */ + @SuppressWarnings("unchecked") + static <T extends ClientHttpConnector> ClientHttpConnectorBuilder<T> of(Class<T> clientHttpConnectorType) { +- Assert.notNull(clientHttpConnectorType, "'requestFactoryType' must not be null"); ++ Assert.notNull(clientHttpConnectorType, "'clientHttpConnectorType' must not be null"); + Assert.isTrue(clientHttpConnectorType != ClientHttpConnector.class, + "'clientHttpConnectorType' must be an implementation of ClientHttpConnector"); + if (clientHttpConnectorType == ReactorClientHttpConnector.class) { +diff --git a/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/HttpComponentsClientHttpConnectorBuilder.java b/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/HttpComponentsClientHttpConnectorBuilder.java +index d47f8c424ed..6eff3a3c598 100644 +--- a/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/HttpComponentsClientHttpConnectorBuilder.java ++++ b/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/HttpComponentsClientHttpConnectorBuilder.java +@@ -66,7 +66,7 @@ public final class HttpComponentsClientHttpConnectorBuilder + */ + public HttpComponentsClientHttpConnectorBuilder withHttpClientCustomizer( + Consumer<HttpAsyncClientBuilder> httpClientCustomizer) { +- Assert.notNull(httpClientCustomizer, "'customizer' must not be null"); ++ Assert.notNull(httpClientCustomizer, "'httpClientCustomizer' must not be null"); + return new HttpComponentsClientHttpConnectorBuilder(getCustomizers(), + this.httpClientBuilder.withCustomizer(httpClientCustomizer)); + } diff --git a/tasks/spring-projects__spring-boot-51568/solution/solve.sh b/tasks/spring-projects__spring-boot-51568/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51568/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51568/task.toml b/tasks/spring-projects__spring-boot-51568/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..10a75d6edbb7e55a0a2904cfa5bcd0e4b368d0b3 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51568/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51568" +description = "Some assertion messages name the wrong parameter" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "10190c7cc79420addb847eac7de801caa4356824" +reference = "https://github.com/spring-projects/spring-boot/pull/51568" +source_access = "auto" +built_at = "2026-11-16T16:09:44.786480+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ebcaf84ace33d6ede5455d2aa2dda2520a45f0df0cae77c28ea5b2a0de804ef3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-04T08:36:01Z" +diff_format = "unified" +context_files = [ + "core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java", + "module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/ClientHttpConnectorBuilder.java", + "module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/HttpComponentsClientHttpConnectorBuilder.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.168531+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:179192d3f30f72c40a6420efc7b8a240db6d5d01917eda3f983ef00e677833ee" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51568/tests/capture.py b/tasks/spring-projects__spring-boot-51568/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51568/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51568/tests/instruction.md b/tasks/spring-projects__spring-boot-51568/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..42b9d19c34a65722bfc88964e6cafa1744f674c5 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51568/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Some assertion messages name the wrong parameter + +## Description + +Three `Assert` messages name a parameter that doesn't exist on the method. In each case neighbouring code in the same class already uses the correct name: + +- `ClientHttpConnectorBuilder.of(Class<T> clientHttpConnectorType)` reports `'requestFactoryType'`, and the javadoc above it refers to `requestFactoryType` as well. Both look like leftovers from `ClientHttpRequestFactoryBuilder.of`. The `@param` tag and the `Assert.isTrue` on the following line already use the correct name. +- `HttpComponentsClientHttpConnectorBuilder.withHttpClientCustomizer(Consumer<HttpAsyncClientBuilder> httpClientCustomizer)` reports `'customizer'`, while `withConnectionManagerCustomizer` and `withConnectionConfigCustomizer` in the same class both use their parameter names. +- `JsonWriter.Member.as(Extractor<T, R> extractor)` reports `'adapter'`. The other four `Assert.notNull` calls on an `extractor` in that file all use `'extractor'`. + +The first two were part of #51509 and were correctly removed there as unrelated to the null check fix. This targets `main` rather than `4.0.x` since these are message-only corrections with no behaviour change. I also checked the rest of the codebase for the same pattern and these three are all I found. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `10190c7cc794`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51568/tests/oracle.patch b/tasks/spring-projects__spring-boot-51568/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ba56f59ae5bf088578b660d467e17c57a75e1f19 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51568/tests/oracle.patch @@ -0,0 +1,48 @@ +diff --git a/core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java b/core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java +index 5d85b91d7fa..8ee3ccba5fa 100644 +--- a/core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java ++++ b/core/spring-boot/src/main/java/org/springframework/boot/json/JsonWriter.java +@@ -451,7 +451,7 @@ public interface JsonWriter<T> { + */ + @SuppressWarnings("unchecked") + public <R> Member<R> as(Extractor<T, R> extractor) { +- Assert.notNull(extractor, "'adapter' must not be null"); ++ Assert.notNull(extractor, "'extractor' must not be null"); + Member<R> result = (Member<R>) this; + result.valueExtractor = this.valueExtractor.as(extractor::extract); + return result; +diff --git a/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/ClientHttpConnectorBuilder.java b/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/ClientHttpConnectorBuilder.java +index 89cbfcbb27c..d891ff5ce36 100644 +--- a/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/ClientHttpConnectorBuilder.java ++++ b/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/ClientHttpConnectorBuilder.java +@@ -127,7 +127,7 @@ public interface ClientHttpConnectorBuilder<T extends ClientHttpConnector> { + + /** + * Return a new {@link ClientHttpConnectorBuilder} for the given +- * {@code requestFactoryType}. The following implementations are supported: ++ * {@code clientHttpConnectorType}. The following implementations are supported: + * <ul> + * <li>{@link ReactorClientHttpConnector}</li> + * <li>{@link JettyClientHttpConnector}</li> +@@ -140,7 +140,7 @@ public interface ClientHttpConnectorBuilder<T extends ClientHttpConnector> { + */ + @SuppressWarnings("unchecked") + static <T extends ClientHttpConnector> ClientHttpConnectorBuilder<T> of(Class<T> clientHttpConnectorType) { +- Assert.notNull(clientHttpConnectorType, "'requestFactoryType' must not be null"); ++ Assert.notNull(clientHttpConnectorType, "'clientHttpConnectorType' must not be null"); + Assert.isTrue(clientHttpConnectorType != ClientHttpConnector.class, + "'clientHttpConnectorType' must be an implementation of ClientHttpConnector"); + if (clientHttpConnectorType == ReactorClientHttpConnector.class) { +diff --git a/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/HttpComponentsClientHttpConnectorBuilder.java b/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/HttpComponentsClientHttpConnectorBuilder.java +index d47f8c424ed..6eff3a3c598 100644 +--- a/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/HttpComponentsClientHttpConnectorBuilder.java ++++ b/module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/HttpComponentsClientHttpConnectorBuilder.java +@@ -66,7 +66,7 @@ public final class HttpComponentsClientHttpConnectorBuilder + */ + public HttpComponentsClientHttpConnectorBuilder withHttpClientCustomizer( + Consumer<HttpAsyncClientBuilder> httpClientCustomizer) { +- Assert.notNull(httpClientCustomizer, "'customizer' must not be null"); ++ Assert.notNull(httpClientCustomizer, "'httpClientCustomizer' must not be null"); + return new HttpComponentsClientHttpConnectorBuilder(getCustomizers(), + this.httpClientBuilder.withCustomizer(httpClientCustomizer)); + } diff --git a/tasks/spring-projects__spring-boot-51568/tests/test.sh b/tasks/spring-projects__spring-boot-51568/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8b80d29c091ff7dd12c5e65f8b446d96c376466c --- /dev/null +++ b/tasks/spring-projects__spring-boot-51568/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 10190c7cc79420addb847eac7de801caa4356824 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51568/tests/verifier.py b/tasks/spring-projects__spring-boot-51568/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51568/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51593/environment/Dockerfile b/tasks/spring-projects__spring-boot-51593/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..29e97731a46d8daaf37404453ac1c12f732d2185 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51593/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4396a31e2301ec3e9bcc0198c9569d853fa0044b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4396a31e2301ec3e9bcc0198c9569d853fa0044b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4396a31e2301ec3e9bcc0198c9569d853fa0044b \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51593/instruction.md b/tasks/spring-projects__spring-boot-51593/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..073180a9bb6285473115e12ecace804cfa41ced2 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51593/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Switch optional Oracle JDBC driver to the version compiled against Java 17 + +## Description + +Since spring-boot-jdbc requires at least Java 17, it is advisable that the optional dependency from the Oracle JDBC driver points to the version compiled against JDK 17. This PR proposes the following dependency switch: + +- com.oracle.database.jdbc:ojdbc11 -> com.oracle.database.jdbc:ojdbc17 +- com.oracle.database.jdbc:ucp11 -> com.oracle.database.jdbc:ucp17 + +Please note that this is not a version upgrade in the usual sense and as such apparently it is not covered by the semi-automated process that bumps third party library versions. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4396a31e2301`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51593/solution/patch.diff b/tasks/spring-projects__spring-boot-51593/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..36e631d7298a31d9525c96f704bff1ee8b15eab4 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51593/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/module/spring-boot-jdbc/build.gradle b/module/spring-boot-jdbc/build.gradle +index d258ec148e9..ebb9fdc065d 100644 +--- a/module/spring-boot-jdbc/build.gradle ++++ b/module/spring-boot-jdbc/build.gradle +@@ -40,8 +40,8 @@ dependencies { + optional(project(":module:spring-boot-micrometer-metrics")) + optional("com.h2database:h2") + optional("com.mchange:c3p0") +- optional("com.oracle.database.jdbc:ojdbc11") +- optional("com.oracle.database.jdbc:ucp11") ++ optional("com.oracle.database.jdbc:ojdbc17") ++ optional("com.oracle.database.jdbc:ucp17") + optional("com.zaxxer:HikariCP") + optional("io.micrometer:micrometer-core") + optional("org.apache.commons:commons-dbcp2") diff --git a/tasks/spring-projects__spring-boot-51593/solution/solve.sh b/tasks/spring-projects__spring-boot-51593/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51593/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51593/task.toml b/tasks/spring-projects__spring-boot-51593/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f87e212d169bf5385cd6785c2a82ae5ea0ca935d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51593/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51593" +description = "Switch optional Oracle JDBC driver to the version compiled against Java 17" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "4396a31e2301ec3e9bcc0198c9569d853fa0044b" +reference = "https://github.com/spring-projects/spring-boot/pull/51593" +source_access = "auto" +built_at = "2026-11-16T16:09:44.775898+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:40e9988967798cbd8255169c069b0afa9406b707d2549a7fce9bcfa51cf66de6" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T07:44:17Z" +diff_format = "unified" +context_files = [ + "module/spring-boot-jdbc/build.gradle", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.169152+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9bffbbae1a8f0e9aa4d7f33d287aac6c478778f4d7a9e0f8fd5388544768544a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51593/tests/capture.py b/tasks/spring-projects__spring-boot-51593/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51593/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51593/tests/instruction.md b/tasks/spring-projects__spring-boot-51593/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..073180a9bb6285473115e12ecace804cfa41ced2 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51593/tests/instruction.md @@ -0,0 +1,18 @@ +# Issue + +**Title:** Switch optional Oracle JDBC driver to the version compiled against Java 17 + +## Description + +Since spring-boot-jdbc requires at least Java 17, it is advisable that the optional dependency from the Oracle JDBC driver points to the version compiled against JDK 17. This PR proposes the following dependency switch: + +- com.oracle.database.jdbc:ojdbc11 -> com.oracle.database.jdbc:ojdbc17 +- com.oracle.database.jdbc:ucp11 -> com.oracle.database.jdbc:ucp17 + +Please note that this is not a version upgrade in the usual sense and as such apparently it is not covered by the semi-automated process that bumps third party library versions. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4396a31e2301`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51593/tests/oracle.patch b/tasks/spring-projects__spring-boot-51593/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..36e631d7298a31d9525c96f704bff1ee8b15eab4 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51593/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/module/spring-boot-jdbc/build.gradle b/module/spring-boot-jdbc/build.gradle +index d258ec148e9..ebb9fdc065d 100644 +--- a/module/spring-boot-jdbc/build.gradle ++++ b/module/spring-boot-jdbc/build.gradle +@@ -40,8 +40,8 @@ dependencies { + optional(project(":module:spring-boot-micrometer-metrics")) + optional("com.h2database:h2") + optional("com.mchange:c3p0") +- optional("com.oracle.database.jdbc:ojdbc11") +- optional("com.oracle.database.jdbc:ucp11") ++ optional("com.oracle.database.jdbc:ojdbc17") ++ optional("com.oracle.database.jdbc:ucp17") + optional("com.zaxxer:HikariCP") + optional("io.micrometer:micrometer-core") + optional("org.apache.commons:commons-dbcp2") diff --git a/tasks/spring-projects__spring-boot-51593/tests/test.sh b/tasks/spring-projects__spring-boot-51593/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a5a4bb522b933f5d3cb0943f9200816540e048a2 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51593/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4396a31e2301ec3e9bcc0198c9569d853fa0044b > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51593/tests/verifier.py b/tasks/spring-projects__spring-boot-51593/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51593/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51598/environment/Dockerfile b/tasks/spring-projects__spring-boot-51598/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3a34d4f1b567f270ef131d846b603ba9a7ab206a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51598/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 03cf0c49cefdd0f9c3e891544882795160819d69 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 03cf0c49cefdd0f9c3e891544882795160819d69 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 03cf0c49cefdd0f9c3e891544882795160819d69 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51598/instruction.md b/tasks/spring-projects__spring-boot-51598/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..31e0715e1a2b742da2a5c982b7feddaecf806620 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51598/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Avoid Gradle deprecation warnings for Project object as a dependency notation + +## Description + +Currently, running the build with `--warning-mode=all` reports the following deprecation warning: + +```text +> Configure project :documentation:spring-boot-docs +Using a Project object as a dependency notation has been deprecated. This will fail with an error in Gradle 10. Please use the project(String) method on DependencyHandler or the createProjectDependency(String) method on DependencyFactory instead. Consult the upgrading guide for further information: https://docs.gradle.org/9.7.0/userguide/upgrading_version_9.html#dependency_project_notation +``` + +This PR updates AggregatorPlugin to create explicit project dependencies with DependencyFactory#createProjectDependency(...). + +Reference: https://docs.gradle.org/9.7.0/userguide/upgrading_version_9.html#dependency_project_notation + +Note that --warning-mode=all still reports other, unrelated deprecation warnings (implicit property lookup in parent projects, and the IDE plugins' file generation types). +Those are left out of this PR to keep it focused, but I'm happy to follow up on them if that would be useful. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `03cf0c49cefd`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51598/solution/patch.diff b/tasks/spring-projects__spring-boot-51598/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ac1282e09af66d03393b95ea8dc66da4f4fab2e8 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51598/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/buildSrc/src/main/java/org/springframework/boot/build/aggregation/AggregatorPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/aggregation/AggregatorPlugin.java +index ffe2baf527b..92e30f7c040 100644 +--- a/buildSrc/src/main/java/org/springframework/boot/build/aggregation/AggregatorPlugin.java ++++ b/buildSrc/src/main/java/org/springframework/boot/build/aggregation/AggregatorPlugin.java +@@ -47,7 +47,8 @@ public class AggregatorPlugin implements Plugin<Project> { + configureAttributes(configuration, aggregate, target.getObjects()); + }); + target.getRootProject() +- .allprojects((project) -> target.getDependencies().add(dependencies.getName(), project)); ++ .allprojects((project) -> target.getDependencies() ++ .add(dependencies.getName(), project.getDependencyFactory().createProjectDependency())); + aggregate.getFiles() + .convention(aggregated.map((configuration) -> configuration.getIncoming() + .artifactView((view) -> view.setLenient(true)) diff --git a/tasks/spring-projects__spring-boot-51598/solution/solve.sh b/tasks/spring-projects__spring-boot-51598/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51598/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51598/task.toml b/tasks/spring-projects__spring-boot-51598/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3187b4d3dffe1a29a767163f9ff3c0b18874fe27 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51598/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51598" +description = "Avoid Gradle deprecation warnings for Project object as a dependency notation" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "03cf0c49cefdd0f9c3e891544882795160819d69" +reference = "https://github.com/spring-projects/spring-boot/pull/51598" +source_access = "auto" +built_at = "2026-11-16T16:09:44.773742+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:66ed4edb40ca54a2a65ccff4f91d0cf093028bc29dbb97f68bf8172a7fc7a6fc" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T11:38:55Z" +diff_format = "unified" +context_files = [ + "buildSrc/src/main/java/org/springframework/boot/build/aggregation/AggregatorPlugin.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.169702+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8e89833c7f0a3956f54724bfecc277fc00949e94c9750a5ea230d4a9da67745a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51598/tests/capture.py b/tasks/spring-projects__spring-boot-51598/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51598/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51598/tests/instruction.md b/tasks/spring-projects__spring-boot-51598/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..31e0715e1a2b742da2a5c982b7feddaecf806620 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51598/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Avoid Gradle deprecation warnings for Project object as a dependency notation + +## Description + +Currently, running the build with `--warning-mode=all` reports the following deprecation warning: + +```text +> Configure project :documentation:spring-boot-docs +Using a Project object as a dependency notation has been deprecated. This will fail with an error in Gradle 10. Please use the project(String) method on DependencyHandler or the createProjectDependency(String) method on DependencyFactory instead. Consult the upgrading guide for further information: https://docs.gradle.org/9.7.0/userguide/upgrading_version_9.html#dependency_project_notation +``` + +This PR updates AggregatorPlugin to create explicit project dependencies with DependencyFactory#createProjectDependency(...). + +Reference: https://docs.gradle.org/9.7.0/userguide/upgrading_version_9.html#dependency_project_notation + +Note that --warning-mode=all still reports other, unrelated deprecation warnings (implicit property lookup in parent projects, and the IDE plugins' file generation types). +Those are left out of this PR to keep it focused, but I'm happy to follow up on them if that would be useful. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `03cf0c49cefd`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51598/tests/oracle.patch b/tasks/spring-projects__spring-boot-51598/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ac1282e09af66d03393b95ea8dc66da4f4fab2e8 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51598/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/buildSrc/src/main/java/org/springframework/boot/build/aggregation/AggregatorPlugin.java b/buildSrc/src/main/java/org/springframework/boot/build/aggregation/AggregatorPlugin.java +index ffe2baf527b..92e30f7c040 100644 +--- a/buildSrc/src/main/java/org/springframework/boot/build/aggregation/AggregatorPlugin.java ++++ b/buildSrc/src/main/java/org/springframework/boot/build/aggregation/AggregatorPlugin.java +@@ -47,7 +47,8 @@ public class AggregatorPlugin implements Plugin<Project> { + configureAttributes(configuration, aggregate, target.getObjects()); + }); + target.getRootProject() +- .allprojects((project) -> target.getDependencies().add(dependencies.getName(), project)); ++ .allprojects((project) -> target.getDependencies() ++ .add(dependencies.getName(), project.getDependencyFactory().createProjectDependency())); + aggregate.getFiles() + .convention(aggregated.map((configuration) -> configuration.getIncoming() + .artifactView((view) -> view.setLenient(true)) diff --git a/tasks/spring-projects__spring-boot-51598/tests/test.sh b/tasks/spring-projects__spring-boot-51598/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..18c4761da3267d7782410290c1ba315334f84621 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51598/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 03cf0c49cefdd0f9c3e891544882795160819d69 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51598/tests/verifier.py b/tasks/spring-projects__spring-boot-51598/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51598/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51619/environment/Dockerfile b/tasks/spring-projects__spring-boot-51619/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6ed2526502f9ce79555cf83f7c12886f693fe977 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51619/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b1e91c942e90fdd3f229fc792ef7e038e2b28839 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b1e91c942e90fdd3f229fc792ef7e038e2b28839 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b1e91c942e90fdd3f229fc792ef7e038e2b28839 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51619/instruction.md b/tasks/spring-projects__spring-boot-51619/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cc0d061def19038990e560a2385cd45dd32d4d71 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51619/instruction.md @@ -0,0 +1,49 @@ +# Issue + +**Title:** OAuth2 resource server ignores authorities-claim-delimiter when set on its own + +## Description + +## What happened? + +Setting `spring.security.oauth2.resourceserver.jwt.authorities-claim-delimiter` without any other JWT converter properties has no effect. For example, given a JWT with a `scope` claim of `read,write` and the following configuration: + +```properties +spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://example.com/.well-known/jwks.json +spring.security.oauth2.resourceserver.jwt.authorities-claim-delimiter=, +``` + +The resulting authentication has a single authority, `SCOPE_read,write`, instead of `SCOPE_read` and `SCOPE_write`. An authorization rule using `hasAuthority('SCOPE_read')` therefore denies access. + +In both `OAuth2ResourceServerJwtConfiguration` and its reactive counterpart, `JwtConverterConfiguration` is guarded by `JwtConverterPropertiesCondition`. This `AnyNestedCondition` checks three properties: + +- `authority-prefix` +- `principal-claim-name` +- `authorities-claim-name` + +The converter bean method also applies `authorities-claim-delimiter`, but that property is missing from the condition. When it is the only converter property set, the condition does not match and Spring Boot does not configure a converter bean. Spring Security then uses its default converter, which splits the claim on a single space. + +Support for all four properties was added in #38105. The condition added as part of that change checks only three of them. + +The existing "Custom delimiter for JWT scopes" test case did not catch this because it also set `authority-prefix`, which satisfied the condition. + +## What does this PR change? + +Adds a nested condition for `authorities-claim-delimiter` to `JwtConverterPropertiesCondition` in both the servlet and reactive configurations. Setting the delimiter alone now enables the converter configuration. + +Unset properties retain their defaults because `PropertyMapper` skips null values. User-defined converter beans still take precedence through `@ConditionalOnMissingBean`. + +The delimiter is also missing from the corresponding conditions on `4.1.x` and `main`, where they live in `JwtConverterConfiguration.PropertiesCondition` and `ReactiveJwtConverterConfiguration.PropertiesCondition`. + +## Tests + +- Added `shouldConfigureJwtConverterIfAuthoritiesClaimDelimiterIsSet` to both `OAuth2ResourceServerAutoConfigurationTests` and `ReactiveOAuth2ResourceServerAutoConfigurationTests`, following the existing tests for the other three properties. +- Updated the "Custom delimiter for JWT scopes" case in `JwtConverterCustomizationsArgumentsProvider` to set the delimiter without a custom authority prefix. It now expects the split scopes to use the default `SCOPE_` prefix. + +The new tests and the updated parameterized case fail without the fix. The parameterized case fails with `NoSuchBeanDefinitionException` because no converter bean is configured. + +`:module:spring-boot-security-oauth2-resource-server:check` passes with JDK 25. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b1e91c942e90`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51619/solution/patch.diff b/tasks/spring-projects__spring-boot-51619/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..80f4a2b93105d45f77fadfceced5d71895c26294 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51619/solution/patch.diff @@ -0,0 +1,90 @@ +diff --git a/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerJwtConfiguration.java b/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerJwtConfiguration.java +index 9b4adc17474..822ee407c25 100644 +--- a/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerJwtConfiguration.java ++++ b/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerJwtConfiguration.java +@@ -265,6 +265,11 @@ class ReactiveOAuth2ResourceServerJwtConfiguration { + + } + ++ @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authorities-claim-delimiter") ++ static class OnAuthoritiesClaimDelimiter { ++ ++ } ++ + } + + } +diff --git a/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerJwtConfiguration.java b/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerJwtConfiguration.java +index 2f9e477d8db..2ee7fdb4a6c 100644 +--- a/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerJwtConfiguration.java ++++ b/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerJwtConfiguration.java +@@ -257,6 +257,11 @@ class OAuth2ResourceServerJwtConfiguration { + + } + ++ @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authorities-claim-delimiter") ++ static class OnAuthoritiesClaimDelimiter { ++ ++ } ++ + } + + } +diff --git a/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/JwtConverterCustomizationsArgumentsProvider.java b/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/JwtConverterCustomizationsArgumentsProvider.java +index 23f56974a46..a0df6bb7069 100644 +--- a/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/JwtConverterCustomizationsArgumentsProvider.java ++++ b/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/JwtConverterCustomizationsArgumentsProvider.java +@@ -53,7 +53,7 @@ public final class JwtConverterCustomizationsArgumentsProvider implements Argume + String principalClaimProperty = "spring.security.oauth2.resourceserver.jwt.principal-claim-name=" + + customPrincipalClaim; + String[] customPrefixProps = { jwkSetUriProperty, authorityPrefixProperty }; +- String[] customDelimiterProps = { jwkSetUriProperty, authorityPrefixProperty, authoritiesDelimiterProperty }; ++ String[] customDelimiterProps = { jwkSetUriProperty, authoritiesDelimiterProperty }; + String[] customAuthoritiesClaimProps = { jwkSetUriProperty, authoritiesClaimProperty }; + String[] customPrincipalClaimProps = { jwkSetUriProperty, principalClaimProperty }; + String[] allJwtConverterProps = { jwkSetUriProperty, authorityPrefixProperty, authoritiesDelimiterProperty, +@@ -84,7 +84,7 @@ public final class JwtConverterCustomizationsArgumentsProvider implements Argume + Arguments.of(Named.named("Custom prefix for GrantedAuthority", customPrefixProps), + noAuthoritiesCustomizationsJwt, subjectValue, customPrefixAuthorities), + Arguments.of(Named.named("Custom delimiter for JWT scopes", customDelimiterProps), +- customAuthoritiesDelimiterJwt, subjectValue, customPrefixAuthorities), ++ customAuthoritiesDelimiterJwt, subjectValue, defaultPrefixAuthorities), + Arguments.of(Named.named("Custom JWT authority claim name", customAuthoritiesClaimProps), + customAuthoritiesClaimJwt, subjectValue, defaultPrefixAuthorities), + Arguments.of(Named.named("Custom JWT principal claim name", customPrincipalClaimProps), +diff --git a/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java b/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java +index ab737ca6bd7..44706ef0277 100644 +--- a/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java ++++ b/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java +@@ -701,6 +701,13 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { + .run((context) -> assertThat(context).hasSingleBean(ReactiveJwtAuthenticationConverter.class)); + } + ++ @Test ++ void shouldConfigureJwtConverterIfAuthoritiesClaimDelimiterIsSet() { ++ this.contextRunner ++ .withPropertyValues("spring.security.oauth2.resourceserver.jwt.authorities-claim-delimiter=dummy") ++ .run((context) -> assertThat(context).hasSingleBean(ReactiveJwtAuthenticationConverter.class)); ++ } ++ + @ParameterizedTest(name = "{0}") + @ArgumentsSource(JwtConverterCustomizationsArgumentsProvider.class) + void autoConfigurationShouldConfigureResourceServerWithJwtConverterCustomizations(String[] properties, Jwt jwt, +diff --git a/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerAutoConfigurationTests.java b/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerAutoConfigurationTests.java +index b6e472d2961..876964d8202 100644 +--- a/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerAutoConfigurationTests.java ++++ b/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerAutoConfigurationTests.java +@@ -738,6 +738,13 @@ class OAuth2ResourceServerAutoConfigurationTests { + .run((context) -> assertThat(context).hasSingleBean(JwtAuthenticationConverter.class)); + } + ++ @Test ++ void shouldConfigureJwtConverterIfAuthoritiesClaimDelimiterIsSet() { ++ this.contextRunner ++ .withPropertyValues("spring.security.oauth2.resourceserver.jwt.authorities-claim-delimiter=dummy") ++ .run((context) -> assertThat(context).hasSingleBean(JwtAuthenticationConverter.class)); ++ } ++ + @Test + void jwtAuthenticationConverterByJwtConfigIsConditionalOnMissingBean() { + String propertiesPrincipalClaim = "principal_from_properties"; diff --git a/tasks/spring-projects__spring-boot-51619/solution/solve.sh b/tasks/spring-projects__spring-boot-51619/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51619/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51619/task.toml b/tasks/spring-projects__spring-boot-51619/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6ab7b7e49089eb1625944297fbb063f07e2d5ce8 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51619/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51619" +description = "OAuth2 resource server ignores authorities-claim-delimiter when set on its own" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "b1e91c942e90fdd3f229fc792ef7e038e2b28839" +reference = "https://github.com/spring-projects/spring-boot/pull/51619" +source_access = "auto" +built_at = "2026-11-16T16:09:44.769894+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8dce1e86dbf65b6f391f189fc74625f106420ea443e293748a26e5107a802d6c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-08T15:52:33Z" +diff_format = "unified" +context_files = [ + "module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerJwtConfiguration.java", + "module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerJwtConfiguration.java", + "module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/JwtConverterCustomizationsArgumentsProvider.java", + "module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java", + "module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerAutoConfigurationTests.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 28 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.170306+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7b461c8ecea348eacf07b5e1f2653ef2f2cce49bbf79c3e3efff7f8fe6e5047b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51619/tests/capture.py b/tasks/spring-projects__spring-boot-51619/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51619/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51619/tests/instruction.md b/tasks/spring-projects__spring-boot-51619/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cc0d061def19038990e560a2385cd45dd32d4d71 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51619/tests/instruction.md @@ -0,0 +1,49 @@ +# Issue + +**Title:** OAuth2 resource server ignores authorities-claim-delimiter when set on its own + +## Description + +## What happened? + +Setting `spring.security.oauth2.resourceserver.jwt.authorities-claim-delimiter` without any other JWT converter properties has no effect. For example, given a JWT with a `scope` claim of `read,write` and the following configuration: + +```properties +spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://example.com/.well-known/jwks.json +spring.security.oauth2.resourceserver.jwt.authorities-claim-delimiter=, +``` + +The resulting authentication has a single authority, `SCOPE_read,write`, instead of `SCOPE_read` and `SCOPE_write`. An authorization rule using `hasAuthority('SCOPE_read')` therefore denies access. + +In both `OAuth2ResourceServerJwtConfiguration` and its reactive counterpart, `JwtConverterConfiguration` is guarded by `JwtConverterPropertiesCondition`. This `AnyNestedCondition` checks three properties: + +- `authority-prefix` +- `principal-claim-name` +- `authorities-claim-name` + +The converter bean method also applies `authorities-claim-delimiter`, but that property is missing from the condition. When it is the only converter property set, the condition does not match and Spring Boot does not configure a converter bean. Spring Security then uses its default converter, which splits the claim on a single space. + +Support for all four properties was added in #38105. The condition added as part of that change checks only three of them. + +The existing "Custom delimiter for JWT scopes" test case did not catch this because it also set `authority-prefix`, which satisfied the condition. + +## What does this PR change? + +Adds a nested condition for `authorities-claim-delimiter` to `JwtConverterPropertiesCondition` in both the servlet and reactive configurations. Setting the delimiter alone now enables the converter configuration. + +Unset properties retain their defaults because `PropertyMapper` skips null values. User-defined converter beans still take precedence through `@ConditionalOnMissingBean`. + +The delimiter is also missing from the corresponding conditions on `4.1.x` and `main`, where they live in `JwtConverterConfiguration.PropertiesCondition` and `ReactiveJwtConverterConfiguration.PropertiesCondition`. + +## Tests + +- Added `shouldConfigureJwtConverterIfAuthoritiesClaimDelimiterIsSet` to both `OAuth2ResourceServerAutoConfigurationTests` and `ReactiveOAuth2ResourceServerAutoConfigurationTests`, following the existing tests for the other three properties. +- Updated the "Custom delimiter for JWT scopes" case in `JwtConverterCustomizationsArgumentsProvider` to set the delimiter without a custom authority prefix. It now expects the split scopes to use the default `SCOPE_` prefix. + +The new tests and the updated parameterized case fail without the fix. The parameterized case fails with `NoSuchBeanDefinitionException` because no converter bean is configured. + +`:module:spring-boot-security-oauth2-resource-server:check` passes with JDK 25. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b1e91c942e90`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51619/tests/oracle.patch b/tasks/spring-projects__spring-boot-51619/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..80f4a2b93105d45f77fadfceced5d71895c26294 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51619/tests/oracle.patch @@ -0,0 +1,90 @@ +diff --git a/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerJwtConfiguration.java b/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerJwtConfiguration.java +index 9b4adc17474..822ee407c25 100644 +--- a/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerJwtConfiguration.java ++++ b/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerJwtConfiguration.java +@@ -265,6 +265,11 @@ class ReactiveOAuth2ResourceServerJwtConfiguration { + + } + ++ @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authorities-claim-delimiter") ++ static class OnAuthoritiesClaimDelimiter { ++ ++ } ++ + } + + } +diff --git a/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerJwtConfiguration.java b/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerJwtConfiguration.java +index 2f9e477d8db..2ee7fdb4a6c 100644 +--- a/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerJwtConfiguration.java ++++ b/module/spring-boot-security-oauth2-resource-server/src/main/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerJwtConfiguration.java +@@ -257,6 +257,11 @@ class OAuth2ResourceServerJwtConfiguration { + + } + ++ @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authorities-claim-delimiter") ++ static class OnAuthoritiesClaimDelimiter { ++ ++ } ++ + } + + } +diff --git a/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/JwtConverterCustomizationsArgumentsProvider.java b/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/JwtConverterCustomizationsArgumentsProvider.java +index 23f56974a46..a0df6bb7069 100644 +--- a/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/JwtConverterCustomizationsArgumentsProvider.java ++++ b/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/JwtConverterCustomizationsArgumentsProvider.java +@@ -53,7 +53,7 @@ public final class JwtConverterCustomizationsArgumentsProvider implements Argume + String principalClaimProperty = "spring.security.oauth2.resourceserver.jwt.principal-claim-name=" + + customPrincipalClaim; + String[] customPrefixProps = { jwkSetUriProperty, authorityPrefixProperty }; +- String[] customDelimiterProps = { jwkSetUriProperty, authorityPrefixProperty, authoritiesDelimiterProperty }; ++ String[] customDelimiterProps = { jwkSetUriProperty, authoritiesDelimiterProperty }; + String[] customAuthoritiesClaimProps = { jwkSetUriProperty, authoritiesClaimProperty }; + String[] customPrincipalClaimProps = { jwkSetUriProperty, principalClaimProperty }; + String[] allJwtConverterProps = { jwkSetUriProperty, authorityPrefixProperty, authoritiesDelimiterProperty, +@@ -84,7 +84,7 @@ public final class JwtConverterCustomizationsArgumentsProvider implements Argume + Arguments.of(Named.named("Custom prefix for GrantedAuthority", customPrefixProps), + noAuthoritiesCustomizationsJwt, subjectValue, customPrefixAuthorities), + Arguments.of(Named.named("Custom delimiter for JWT scopes", customDelimiterProps), +- customAuthoritiesDelimiterJwt, subjectValue, customPrefixAuthorities), ++ customAuthoritiesDelimiterJwt, subjectValue, defaultPrefixAuthorities), + Arguments.of(Named.named("Custom JWT authority claim name", customAuthoritiesClaimProps), + customAuthoritiesClaimJwt, subjectValue, defaultPrefixAuthorities), + Arguments.of(Named.named("Custom JWT principal claim name", customPrincipalClaimProps), +diff --git a/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java b/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java +index ab737ca6bd7..44706ef0277 100644 +--- a/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java ++++ b/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/reactive/ReactiveOAuth2ResourceServerAutoConfigurationTests.java +@@ -701,6 +701,13 @@ class ReactiveOAuth2ResourceServerAutoConfigurationTests { + .run((context) -> assertThat(context).hasSingleBean(ReactiveJwtAuthenticationConverter.class)); + } + ++ @Test ++ void shouldConfigureJwtConverterIfAuthoritiesClaimDelimiterIsSet() { ++ this.contextRunner ++ .withPropertyValues("spring.security.oauth2.resourceserver.jwt.authorities-claim-delimiter=dummy") ++ .run((context) -> assertThat(context).hasSingleBean(ReactiveJwtAuthenticationConverter.class)); ++ } ++ + @ParameterizedTest(name = "{0}") + @ArgumentsSource(JwtConverterCustomizationsArgumentsProvider.class) + void autoConfigurationShouldConfigureResourceServerWithJwtConverterCustomizations(String[] properties, Jwt jwt, +diff --git a/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerAutoConfigurationTests.java b/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerAutoConfigurationTests.java +index b6e472d2961..876964d8202 100644 +--- a/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerAutoConfigurationTests.java ++++ b/module/spring-boot-security-oauth2-resource-server/src/test/java/org/springframework/boot/security/oauth2/server/resource/autoconfigure/servlet/OAuth2ResourceServerAutoConfigurationTests.java +@@ -738,6 +738,13 @@ class OAuth2ResourceServerAutoConfigurationTests { + .run((context) -> assertThat(context).hasSingleBean(JwtAuthenticationConverter.class)); + } + ++ @Test ++ void shouldConfigureJwtConverterIfAuthoritiesClaimDelimiterIsSet() { ++ this.contextRunner ++ .withPropertyValues("spring.security.oauth2.resourceserver.jwt.authorities-claim-delimiter=dummy") ++ .run((context) -> assertThat(context).hasSingleBean(JwtAuthenticationConverter.class)); ++ } ++ + @Test + void jwtAuthenticationConverterByJwtConfigIsConditionalOnMissingBean() { + String propertiesPrincipalClaim = "principal_from_properties"; diff --git a/tasks/spring-projects__spring-boot-51619/tests/test.sh b/tasks/spring-projects__spring-boot-51619/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0e270ae70f2cb4e5477c8ec1a4178fb1a319deec --- /dev/null +++ b/tasks/spring-projects__spring-boot-51619/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b1e91c942e90fdd3f229fc792ef7e038e2b28839 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51619/tests/verifier.py b/tasks/spring-projects__spring-boot-51619/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51619/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51625/environment/Dockerfile b/tasks/spring-projects__spring-boot-51625/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce8f5a57074a7ee5d96f86c86b92b8713c470566 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51625/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4fc987180d597fd866294d832095cebc04c10cfb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4fc987180d597fd866294d832095cebc04c10cfb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4fc987180d597fd866294d832095cebc04c10cfb \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51625/instruction.md b/tasks/spring-projects__spring-boot-51625/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2973a747493050ebda51d350088e93df25a6d872 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51625/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Avoid implicit property lookup in parent projects + +## Description + +This is a , which left the deprecation warning for implicit property lookup in parent projects to be addressed separately. + +Currently, running the build with `--warning-mode=all` reports three deprecation warnings, such as the following: +```text +> Configure project :plugins:cycle-detection-plugin +Implicit lookup of properties in parent projects has been deprecated. This will fail with an error in Gradle 10. Property 'javaFormatVersion' was not declared in project ':plugins:cycle-detection-plugin' and was resolved from project ':plugins'. Consult the upgrading guide for further information: https://docs.gradle.org/9.7.0/userguide/upgrading_version_9.html#deprecated_implicit_lookup_in_parent_projects +``` + +The settings script for the `gradle/plugins` build currently sets properties from the root `gradle.properties` file only on its root project. As a result, the `cycle-detection-plugin` subproject resolves `javaFormatVersion` and `checkstyleToolVersion` by walking up to its parent project, triggering the deprecation. + +This PR uses `Gradle#beforeProject` instead of `Gradle#rootProject` so that the properties are set directly on every project in the build, avoiding implicit parent-project lookup. + +`buildSrc/settings.gradle` uses the same pattern, but that build has no subprojects, so no parent-project lookup occurs and it does not trigger the deprecation. It is left unchanged. + +I also considered `GradleLifecycle#beforeProject` (`gradle.lifecycle.beforeProject`), which the Javadoc describes as a lifecycle callback "compatible with Configuration Cache and Isolated Projects". As it is still `@Incubating`, this PR uses the stable `Gradle#beforeProject` instead. Happy to switch if you would prefer the incubating API. + +Reference: https://docs.gradle.org/9.7.0/userguide/upgrading_version_9.html#deprecated_implicit_lookup_in_parent_projects + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4fc987180d59`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51625/solution/patch.diff b/tasks/spring-projects__spring-boot-51625/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..09acf9de8d0c19e098d183e0f59dd1d1134e1100 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51625/solution/patch.diff @@ -0,0 +1,30 @@ +diff --git a/gradle/plugins/settings.gradle b/gradle/plugins/settings.gradle +index c7575c020bb..8605bec54b8 100644 +--- a/gradle/plugins/settings.gradle ++++ b/gradle/plugins/settings.gradle +@@ -20,10 +20,12 @@ pluginManagement { + def properties = new Properties() + properties.load(it) + properties.forEach(settings.ext::set) +- gradle.rootProject { ++ gradle.lifecycle.beforeProject { + properties.forEach(project.ext::set) + } + } + } + ++enableFeaturePreview("NO_IMPLICIT_LOOKUP_IN_PARENT_PROJECTS") ++ + include 'cycle-detection-plugin' +diff --git a/settings.gradle b/settings.gradle +index 98073798c87..8ddcececcba 100644 +--- a/settings.gradle ++++ b/settings.gradle +@@ -45,6 +45,7 @@ plugins { + rootProject.name="spring-boot-build" + + enableFeaturePreview("STABLE_CONFIGURATION_CACHE") ++enableFeaturePreview("NO_IMPLICIT_LOOKUP_IN_PARENT_PROJECTS") + + settings.gradle.projectsLoaded { + develocity { diff --git a/tasks/spring-projects__spring-boot-51625/solution/solve.sh b/tasks/spring-projects__spring-boot-51625/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51625/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51625/task.toml b/tasks/spring-projects__spring-boot-51625/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cd3874e5d79b6dace86f6425fbfb18f63c0efbd3 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51625/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51625" +description = "Avoid implicit property lookup in parent projects" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "4fc987180d597fd866294d832095cebc04c10cfb" +reference = "https://github.com/spring-projects/spring-boot/pull/51625" +source_access = "auto" +built_at = "2026-11-16T16:09:44.768102+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ea7bc2d3f556b0e797de31a34dc039d8b674c73b53423997390a7dffd3dacfb1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-09T07:08:47Z" +diff_format = "unified" +context_files = [ + "gradle/plugins/settings.gradle", + "settings.gradle", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.170900+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c40a5d9c40796750ae817c3bdc3fa060d969a35f2adb29fa6fa111741d4b1255" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51625/tests/capture.py b/tasks/spring-projects__spring-boot-51625/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51625/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51625/tests/instruction.md b/tasks/spring-projects__spring-boot-51625/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2973a747493050ebda51d350088e93df25a6d872 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51625/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Avoid implicit property lookup in parent projects + +## Description + +This is a , which left the deprecation warning for implicit property lookup in parent projects to be addressed separately. + +Currently, running the build with `--warning-mode=all` reports three deprecation warnings, such as the following: +```text +> Configure project :plugins:cycle-detection-plugin +Implicit lookup of properties in parent projects has been deprecated. This will fail with an error in Gradle 10. Property 'javaFormatVersion' was not declared in project ':plugins:cycle-detection-plugin' and was resolved from project ':plugins'. Consult the upgrading guide for further information: https://docs.gradle.org/9.7.0/userguide/upgrading_version_9.html#deprecated_implicit_lookup_in_parent_projects +``` + +The settings script for the `gradle/plugins` build currently sets properties from the root `gradle.properties` file only on its root project. As a result, the `cycle-detection-plugin` subproject resolves `javaFormatVersion` and `checkstyleToolVersion` by walking up to its parent project, triggering the deprecation. + +This PR uses `Gradle#beforeProject` instead of `Gradle#rootProject` so that the properties are set directly on every project in the build, avoiding implicit parent-project lookup. + +`buildSrc/settings.gradle` uses the same pattern, but that build has no subprojects, so no parent-project lookup occurs and it does not trigger the deprecation. It is left unchanged. + +I also considered `GradleLifecycle#beforeProject` (`gradle.lifecycle.beforeProject`), which the Javadoc describes as a lifecycle callback "compatible with Configuration Cache and Isolated Projects". As it is still `@Incubating`, this PR uses the stable `Gradle#beforeProject` instead. Happy to switch if you would prefer the incubating API. + +Reference: https://docs.gradle.org/9.7.0/userguide/upgrading_version_9.html#deprecated_implicit_lookup_in_parent_projects + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4fc987180d59`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51625/tests/oracle.patch b/tasks/spring-projects__spring-boot-51625/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..09acf9de8d0c19e098d183e0f59dd1d1134e1100 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51625/tests/oracle.patch @@ -0,0 +1,30 @@ +diff --git a/gradle/plugins/settings.gradle b/gradle/plugins/settings.gradle +index c7575c020bb..8605bec54b8 100644 +--- a/gradle/plugins/settings.gradle ++++ b/gradle/plugins/settings.gradle +@@ -20,10 +20,12 @@ pluginManagement { + def properties = new Properties() + properties.load(it) + properties.forEach(settings.ext::set) +- gradle.rootProject { ++ gradle.lifecycle.beforeProject { + properties.forEach(project.ext::set) + } + } + } + ++enableFeaturePreview("NO_IMPLICIT_LOOKUP_IN_PARENT_PROJECTS") ++ + include 'cycle-detection-plugin' +diff --git a/settings.gradle b/settings.gradle +index 98073798c87..8ddcececcba 100644 +--- a/settings.gradle ++++ b/settings.gradle +@@ -45,6 +45,7 @@ plugins { + rootProject.name="spring-boot-build" + + enableFeaturePreview("STABLE_CONFIGURATION_CACHE") ++enableFeaturePreview("NO_IMPLICIT_LOOKUP_IN_PARENT_PROJECTS") + + settings.gradle.projectsLoaded { + develocity { diff --git a/tasks/spring-projects__spring-boot-51625/tests/test.sh b/tasks/spring-projects__spring-boot-51625/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e25d65446f4a6edccf8033d0e2f52074277a47c5 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51625/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4fc987180d597fd866294d832095cebc04c10cfb > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51625/tests/verifier.py b/tasks/spring-projects__spring-boot-51625/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51625/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51635/environment/Dockerfile b/tasks/spring-projects__spring-boot-51635/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3b3d585b68bceaef2a38b83311bb35de6711ec37 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51635/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin abbb2980398e97616282aa4f272bbf7ed9d84c2d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard abbb2980398e97616282aa4f272bbf7ed9d84c2d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base abbb2980398e97616282aa4f272bbf7ed9d84c2d \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51635/instruction.md b/tasks/spring-projects__spring-boot-51635/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8eb8b45d6c2f125c9afd1adf74455a418cf6996c --- /dev/null +++ b/tasks/spring-projects__spring-boot-51635/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Avoid Gradle deprecation warnings for Project.getProperties + +## Description + +This addresses another Gradle 9.6 deprecation, following #51598 and #51625: + +```text +> Task :documentation:spring-boot-docs:generateAntoraYml +The Project.getProperties method has been deprecated. This will fail with an error in Gradle 10. Consult the upgrading guide for further information: https://docs.gradle.org/9.7.0/userguide/upgrading_version_9.html#deprecated_get_properties +``` + +The deprecated `Project.getProperties()` API is used in two places: + +- `AntoraAsciidocAttributes` captures the project's entire property map to read `nativeBuildToolsVersion`, `graalVersion`, and `protobufGradlePluginVersion` when generating documentation attributes. +- The image system tests build script accesses `project.properties["springBootVersion"]` when `springBootVersion` is set. + +This PR replaces these usages with `providers.gradleProperty(...)`, as recommended by the Gradle upgrading guide. The three documentation versions are defined in the root `gradle.properties`, and the system tests support a build-wide `springBootVersion` override, such as `-PspringBootVersion=4.0.0` + +Missing documentation properties continue to produce `null`, and the system tests continue to fall back to the project version when springBootVersion is not configured. + +Reference: https://docs.gradle.org/9.7.0/userguide/upgrading_version_9.html#deprecated_get_properties + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `abbb2980398e`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51635/solution/patch.diff b/tasks/spring-projects__spring-boot-51635/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ebdc43b5a05498dd72ee63f86a111f1d27d933d4 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51635/solution/patch.diff @@ -0,0 +1,123 @@ +diff --git a/buildSrc/src/main/java/org/springframework/boot/build/antora/AntoraAsciidocAttributes.java b/buildSrc/src/main/java/org/springframework/boot/build/antora/AntoraAsciidocAttributes.java +index 636093a33b8..2061a1fc499 100644 +--- a/buildSrc/src/main/java/org/springframework/boot/build/antora/AntoraAsciidocAttributes.java ++++ b/buildSrc/src/main/java/org/springframework/boot/build/antora/AntoraAsciidocAttributes.java +@@ -26,6 +26,7 @@ import java.util.Properties; + import java.util.TreeMap; + + import org.gradle.api.Project; ++import org.gradle.api.provider.ProviderFactory; + + import org.springframework.boot.build.artifacts.ArtifactRelease; + import org.springframework.boot.build.bom.BomExtension; +@@ -59,7 +60,7 @@ public class AntoraAsciidocAttributes { + + private final ResolvedBom resolvedBom; + +- private final Map<String, ?> projectProperties; ++ private final ProviderFactory providers; + + public AntoraAsciidocAttributes(Project project, BomExtension dependencyBom, ResolvedBom resolvedBom) { + this.version = String.valueOf(project.getVersion()); +@@ -68,7 +69,7 @@ public class AntoraAsciidocAttributes { + this.artifactRelease = ArtifactRelease.forProject(project); + this.libraries = dependencyBom.getLibraries(); + this.resolvedBom = resolvedBom; +- this.projectProperties = project.getProperties(); ++ this.providers = project.getProviders(); + } + + public Map<String, String> get() { +@@ -108,8 +109,9 @@ public class AntoraAsciidocAttributes { + + private void addVersionAttributes(Map<String, String> attributes, Map<String, String> internal) { + this.libraries.forEach((library) -> addVersionAttributes(attributes, library)); +- attributes.put("version-native-build-tools", (String) this.projectProperties.get("nativeBuildToolsVersion")); +- attributes.put("version-graal", (String) this.projectProperties.get("graalVersion")); ++ attributes.put("version-native-build-tools", ++ this.providers.gradleProperty("nativeBuildToolsVersion").getOrNull()); ++ attributes.put("version-graal", this.providers.gradleProperty("graalVersion").getOrNull()); + } + + private void addVersionAttributes(Map<String, String> attributes, Library library) { +diff --git a/buildSrc/src/test/java/org/springframework/boot/build/antora/AntoraAsciidocAttributesTests.java b/buildSrc/src/test/java/org/springframework/boot/build/antora/AntoraAsciidocAttributesTests.java +index 8d13b3f36ad..8935b58c634 100644 +--- a/buildSrc/src/test/java/org/springframework/boot/build/antora/AntoraAsciidocAttributesTests.java ++++ b/buildSrc/src/test/java/org/springframework/boot/build/antora/AntoraAsciidocAttributesTests.java +@@ -26,6 +26,8 @@ import java.util.function.Function; + import org.gradle.api.Project; + import org.gradle.api.plugins.ExtensionContainer; + import org.gradle.api.plugins.ExtraPropertiesExtension; ++import org.gradle.api.provider.Provider; ++import org.gradle.api.provider.ProviderFactory; + import org.junit.jupiter.api.Test; + + import org.springframework.boot.build.bom.BomExtension; +@@ -115,6 +117,13 @@ class AntoraAsciidocAttributesTests { + assertThat(attributes.get()).containsEntry("version-native-build-tools", "3.4.5"); + } + ++ @Test ++ void versionGraal() { ++ AntoraAsciidocAttributes attributes = attributes("1.2.3", true, BuildType.OPEN_SOURCE, null, ++ mockDependencyVersions(), Map.of("graalVersion", "25")); ++ assertThat(attributes.get()).containsEntry("version-graal", "25"); ++ } ++ + @Test + void urlArtifactRepositoryWhenRelease() { + AntoraAsciidocAttributes attributes = attributes("1.2.3", true, BuildType.OPEN_SOURCE, null, +@@ -234,7 +243,6 @@ class AntoraAsciidocAttributesTests { + assertThat(keys.indexOf("include-java")).isLessThan(keys.indexOf("code-spring-boot-latest")); + } + +- @SuppressWarnings({ "unchecked", "rawtypes" }) + private AntoraAsciidocAttributes attributes(String version, boolean latestVersion, BuildType buildType, + List<Library> libraries, Map<String, String> dependencyVersions, Map<String, ?> projectProperties) { + libraries = (libraries != null) ? libraries : Collections.emptyList(); +@@ -246,7 +254,8 @@ class AntoraAsciidocAttributesTests { + given(project.findProperty("latestVersion")).willReturn(String.valueOf(latestVersion)); + given(project.findProperty("spring.build-type")) + .willReturn((buildType == BuildType.OPEN_SOURCE) ? "oss" : "commercial"); +- given(project.getProperties()).willReturn((Map) projectProperties); ++ ProviderFactory providers = mockProviders(projectProperties); ++ given(project.getProviders()).willReturn(providers); + given(project.getExtensions()).willReturn(extensions); + given(extensions.getExtraProperties()).willReturn(extraPropertiesExtension); + BomExtension dependencyBom = mock(); +@@ -262,6 +271,17 @@ class AntoraAsciidocAttributesTests { + return new AntoraAsciidocAttributes(project, dependencyBom, resolvedBom); + } + ++ private ProviderFactory mockProviders(Map<String, ?> projectProperties) { ++ ProviderFactory providers = mock(); ++ given(providers.gradleProperty(any(String.class))).willAnswer((invocation) -> { ++ String propertyName = invocation.getArgument(0); ++ Provider<Object> provider = mock(); ++ given(provider.getOrNull()).willReturn(projectProperties.get(propertyName)); ++ return provider; ++ }); ++ return providers; ++ } ++ + private Library mockLibrary(Map<LinkType, List<Link>> links) { + return mockLibrary(new Links(links), Collections.emptyMap()); + } +diff --git a/system-test/spring-boot-image-system-tests/build.gradle b/system-test/spring-boot-image-system-tests/build.gradle +index 3532f0e826d..dd1080273de 100644 +--- a/system-test/spring-boot-image-system-tests/build.gradle ++++ b/system-test/spring-boot-image-system-tests/build.gradle +@@ -35,11 +35,8 @@ tasks.register("syncMavenRepository", Sync) { + + systemTest { + dependsOn syncMavenRepository +- if (project.hasProperty("springBootVersion")) { +- systemProperty "springBootVersion", project.properties["springBootVersion"] +- } else { +- systemProperty "springBootVersion", project.getVersion() +- } ++ systemProperty "springBootVersion", ++ providers.gradleProperty("springBootVersion").getOrElse(project.getVersion().toString()) + } + + dependencies { diff --git a/tasks/spring-projects__spring-boot-51635/solution/solve.sh b/tasks/spring-projects__spring-boot-51635/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51635/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51635/task.toml b/tasks/spring-projects__spring-boot-51635/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4bab22c800a59da7e8203e6b7df55c6d5ea027cc --- /dev/null +++ b/tasks/spring-projects__spring-boot-51635/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51635" +description = "Avoid Gradle deprecation warnings for Project.getProperties" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "abbb2980398e97616282aa4f272bbf7ed9d84c2d" +reference = "https://github.com/spring-projects/spring-boot/pull/51635" +source_access = "auto" +built_at = "2026-11-16T16:09:44.763026+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3d6bc66c6099708c57ec8cfa9219dedb5e16ac8699eda4d2fd39ae1186ac4070" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-09T10:01:10Z" +diff_format = "unified" +context_files = [ + "buildSrc/src/main/java/org/springframework/boot/build/antora/AntoraAsciidocAttributes.java", + "buildSrc/src/test/java/org/springframework/boot/build/antora/AntoraAsciidocAttributesTests.java", + "system-test/spring-boot-image-system-tests/build.gradle", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 41 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.171521+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9c5ba8e3523bec3268b9e768712160a600f14dfa7634d9e025e7b1864626a050" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51635/tests/capture.py b/tasks/spring-projects__spring-boot-51635/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51635/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51635/tests/instruction.md b/tasks/spring-projects__spring-boot-51635/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8eb8b45d6c2f125c9afd1adf74455a418cf6996c --- /dev/null +++ b/tasks/spring-projects__spring-boot-51635/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Avoid Gradle deprecation warnings for Project.getProperties + +## Description + +This addresses another Gradle 9.6 deprecation, following #51598 and #51625: + +```text +> Task :documentation:spring-boot-docs:generateAntoraYml +The Project.getProperties method has been deprecated. This will fail with an error in Gradle 10. Consult the upgrading guide for further information: https://docs.gradle.org/9.7.0/userguide/upgrading_version_9.html#deprecated_get_properties +``` + +The deprecated `Project.getProperties()` API is used in two places: + +- `AntoraAsciidocAttributes` captures the project's entire property map to read `nativeBuildToolsVersion`, `graalVersion`, and `protobufGradlePluginVersion` when generating documentation attributes. +- The image system tests build script accesses `project.properties["springBootVersion"]` when `springBootVersion` is set. + +This PR replaces these usages with `providers.gradleProperty(...)`, as recommended by the Gradle upgrading guide. The three documentation versions are defined in the root `gradle.properties`, and the system tests support a build-wide `springBootVersion` override, such as `-PspringBootVersion=4.0.0` + +Missing documentation properties continue to produce `null`, and the system tests continue to fall back to the project version when springBootVersion is not configured. + +Reference: https://docs.gradle.org/9.7.0/userguide/upgrading_version_9.html#deprecated_get_properties + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `abbb2980398e`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51635/tests/oracle.patch b/tasks/spring-projects__spring-boot-51635/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ebdc43b5a05498dd72ee63f86a111f1d27d933d4 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51635/tests/oracle.patch @@ -0,0 +1,123 @@ +diff --git a/buildSrc/src/main/java/org/springframework/boot/build/antora/AntoraAsciidocAttributes.java b/buildSrc/src/main/java/org/springframework/boot/build/antora/AntoraAsciidocAttributes.java +index 636093a33b8..2061a1fc499 100644 +--- a/buildSrc/src/main/java/org/springframework/boot/build/antora/AntoraAsciidocAttributes.java ++++ b/buildSrc/src/main/java/org/springframework/boot/build/antora/AntoraAsciidocAttributes.java +@@ -26,6 +26,7 @@ import java.util.Properties; + import java.util.TreeMap; + + import org.gradle.api.Project; ++import org.gradle.api.provider.ProviderFactory; + + import org.springframework.boot.build.artifacts.ArtifactRelease; + import org.springframework.boot.build.bom.BomExtension; +@@ -59,7 +60,7 @@ public class AntoraAsciidocAttributes { + + private final ResolvedBom resolvedBom; + +- private final Map<String, ?> projectProperties; ++ private final ProviderFactory providers; + + public AntoraAsciidocAttributes(Project project, BomExtension dependencyBom, ResolvedBom resolvedBom) { + this.version = String.valueOf(project.getVersion()); +@@ -68,7 +69,7 @@ public class AntoraAsciidocAttributes { + this.artifactRelease = ArtifactRelease.forProject(project); + this.libraries = dependencyBom.getLibraries(); + this.resolvedBom = resolvedBom; +- this.projectProperties = project.getProperties(); ++ this.providers = project.getProviders(); + } + + public Map<String, String> get() { +@@ -108,8 +109,9 @@ public class AntoraAsciidocAttributes { + + private void addVersionAttributes(Map<String, String> attributes, Map<String, String> internal) { + this.libraries.forEach((library) -> addVersionAttributes(attributes, library)); +- attributes.put("version-native-build-tools", (String) this.projectProperties.get("nativeBuildToolsVersion")); +- attributes.put("version-graal", (String) this.projectProperties.get("graalVersion")); ++ attributes.put("version-native-build-tools", ++ this.providers.gradleProperty("nativeBuildToolsVersion").getOrNull()); ++ attributes.put("version-graal", this.providers.gradleProperty("graalVersion").getOrNull()); + } + + private void addVersionAttributes(Map<String, String> attributes, Library library) { +diff --git a/buildSrc/src/test/java/org/springframework/boot/build/antora/AntoraAsciidocAttributesTests.java b/buildSrc/src/test/java/org/springframework/boot/build/antora/AntoraAsciidocAttributesTests.java +index 8d13b3f36ad..8935b58c634 100644 +--- a/buildSrc/src/test/java/org/springframework/boot/build/antora/AntoraAsciidocAttributesTests.java ++++ b/buildSrc/src/test/java/org/springframework/boot/build/antora/AntoraAsciidocAttributesTests.java +@@ -26,6 +26,8 @@ import java.util.function.Function; + import org.gradle.api.Project; + import org.gradle.api.plugins.ExtensionContainer; + import org.gradle.api.plugins.ExtraPropertiesExtension; ++import org.gradle.api.provider.Provider; ++import org.gradle.api.provider.ProviderFactory; + import org.junit.jupiter.api.Test; + + import org.springframework.boot.build.bom.BomExtension; +@@ -115,6 +117,13 @@ class AntoraAsciidocAttributesTests { + assertThat(attributes.get()).containsEntry("version-native-build-tools", "3.4.5"); + } + ++ @Test ++ void versionGraal() { ++ AntoraAsciidocAttributes attributes = attributes("1.2.3", true, BuildType.OPEN_SOURCE, null, ++ mockDependencyVersions(), Map.of("graalVersion", "25")); ++ assertThat(attributes.get()).containsEntry("version-graal", "25"); ++ } ++ + @Test + void urlArtifactRepositoryWhenRelease() { + AntoraAsciidocAttributes attributes = attributes("1.2.3", true, BuildType.OPEN_SOURCE, null, +@@ -234,7 +243,6 @@ class AntoraAsciidocAttributesTests { + assertThat(keys.indexOf("include-java")).isLessThan(keys.indexOf("code-spring-boot-latest")); + } + +- @SuppressWarnings({ "unchecked", "rawtypes" }) + private AntoraAsciidocAttributes attributes(String version, boolean latestVersion, BuildType buildType, + List<Library> libraries, Map<String, String> dependencyVersions, Map<String, ?> projectProperties) { + libraries = (libraries != null) ? libraries : Collections.emptyList(); +@@ -246,7 +254,8 @@ class AntoraAsciidocAttributesTests { + given(project.findProperty("latestVersion")).willReturn(String.valueOf(latestVersion)); + given(project.findProperty("spring.build-type")) + .willReturn((buildType == BuildType.OPEN_SOURCE) ? "oss" : "commercial"); +- given(project.getProperties()).willReturn((Map) projectProperties); ++ ProviderFactory providers = mockProviders(projectProperties); ++ given(project.getProviders()).willReturn(providers); + given(project.getExtensions()).willReturn(extensions); + given(extensions.getExtraProperties()).willReturn(extraPropertiesExtension); + BomExtension dependencyBom = mock(); +@@ -262,6 +271,17 @@ class AntoraAsciidocAttributesTests { + return new AntoraAsciidocAttributes(project, dependencyBom, resolvedBom); + } + ++ private ProviderFactory mockProviders(Map<String, ?> projectProperties) { ++ ProviderFactory providers = mock(); ++ given(providers.gradleProperty(any(String.class))).willAnswer((invocation) -> { ++ String propertyName = invocation.getArgument(0); ++ Provider<Object> provider = mock(); ++ given(provider.getOrNull()).willReturn(projectProperties.get(propertyName)); ++ return provider; ++ }); ++ return providers; ++ } ++ + private Library mockLibrary(Map<LinkType, List<Link>> links) { + return mockLibrary(new Links(links), Collections.emptyMap()); + } +diff --git a/system-test/spring-boot-image-system-tests/build.gradle b/system-test/spring-boot-image-system-tests/build.gradle +index 3532f0e826d..dd1080273de 100644 +--- a/system-test/spring-boot-image-system-tests/build.gradle ++++ b/system-test/spring-boot-image-system-tests/build.gradle +@@ -35,11 +35,8 @@ tasks.register("syncMavenRepository", Sync) { + + systemTest { + dependsOn syncMavenRepository +- if (project.hasProperty("springBootVersion")) { +- systemProperty "springBootVersion", project.properties["springBootVersion"] +- } else { +- systemProperty "springBootVersion", project.getVersion() +- } ++ systemProperty "springBootVersion", ++ providers.gradleProperty("springBootVersion").getOrElse(project.getVersion().toString()) + } + + dependencies { diff --git a/tasks/spring-projects__spring-boot-51635/tests/test.sh b/tasks/spring-projects__spring-boot-51635/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d390f15535883f5fb216cf0d8b585684f389f47a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51635/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace abbb2980398e97616282aa4f272bbf7ed9d84c2d > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51635/tests/verifier.py b/tasks/spring-projects__spring-boot-51635/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51635/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51653/environment/Dockerfile b/tasks/spring-projects__spring-boot-51653/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e9768b516a0cb529ccb5adba1e3367c64f823014 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51653/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 59379ae449f15a6d17a333f5505941f4165ab3b2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 59379ae449f15a6d17a333f5505941f4165ab3b2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 59379ae449f15a6d17a333f5505941f4165ab3b2 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51653/instruction.md b/tasks/spring-projects__spring-boot-51653/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..33e4d878935fce5371b3ef56698279a851acd5b8 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51653/instruction.md @@ -0,0 +1,56 @@ +# Issue + +**Title:** Speed up layer lookups when extracting a layered jar + +## Description + +`IndexedLayers.getLayer()` is called once for every entry of a layered jar while `java -Djarmode=tools extract` unpacks it, and each call walks `layers.idx` from the top: + +```java +for (Map.Entry<String, List<String>> entry : this.layers.entrySet()) { + for (String candidate : entry.getValue()) { + if (candidate.equals(name) || (candidate.endsWith("/") && name.startsWith(candidate))) { + return entry.getKey(); + } + } +} +``` + +That makes extraction `O(entries x index size)`. The layout of the index makes it worse than the formula suggests: dependencies are listed one line per jar and come first, while the application classes are covered by a single `BOOT-INF/classes/` entry near the end. The most numerous entries therefore consistently scan the longest — for a 700 dependency jar every application class walks past all 700 dependency lines before reaching the line that matches it. + +This indexes the candidates once, when the index file is read, splitting them by kind: + +* names that do not end in `/` go into a `HashMap`, so a file name is resolved with a single lookup +* names that end in `/` go into a `LinkedHashMap` that preserves index order, so only the handful of directory candidates has to be scanned + +`candidate.endsWith("/")` is now evaluated once per index line instead of once per lookup. + +### Measurements + +Realistic indexes and entry lists, median of 15 runs after 40 warm-up runs, JDK 25. Comparison counts are deterministic. + +| Entries | Dependencies | Before | After | String comparisons | +| --- | --- | --- | --- | --- | +| 903 | 80 | 0.76ms | 0.05ms | 70,612 → 2,426 | +| 4,173 | 250 | 5.36ms | 0.13ms | 1,019,857 → 11,896 | +| 24,823 | 700 | 106.92ms | 2.51ms | 17,179,582 → 72,946 | + +The absolute saving is around 100ms on the largest jar, so this is not something most builds will notice. The point is that the cost stops growing with the product of jar size and index size. + +### Behaviour + +Lookups resolve to the same layer as before. + +The only reordering is that exact file names are now consulted before directory prefixes, where previously both kinds were interleaved in index order. That cannot change an answer, because `LayersIndex.Node.buildIndex` only writes a name once its whole subtree belongs to a single layer and otherwise recurses into the children. No indexed name can therefore be a prefix of another indexed name, and at most one candidate can match any given entry. + +`putIfAbsent` keeps the first occurrence of a repeated name, matching the first-match-wins behaviour of the loop it replaces. + +Verified with: + +* the existing `IndexedLayersTests`, unchanged, plus one added test covering a name that appears in more than one layer. That test passes against the current implementation as well, so it is a regression guard rather than a new expectation +* a differential harness running both implementations side by side over randomly generated indexes — 218,963 lookups, including the thrown `IllegalStateException` messages, with no differences +* `./gradlew :loader:spring-boot-jarmode-tools:test checkFormatMain checkFormatTest checkstyleMain checkstyleTest` — 95 tests, no format or Checkstyle violations + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `59379ae449f1`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51653/solution/patch.diff b/tasks/spring-projects__spring-boot-51653/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9e3d3e4104446746377c5cf9392b098fb5abd21c --- /dev/null +++ b/tasks/spring-projects__spring-boot-51653/solution/patch.diff @@ -0,0 +1,103 @@ +diff --git a/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/IndexedLayers.java b/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/IndexedLayers.java +index 7f560d0656d..df2cc7eba84 100644 +--- a/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/IndexedLayers.java ++++ b/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/IndexedLayers.java +@@ -22,6 +22,7 @@ import java.nio.charset.StandardCharsets; + import java.nio.file.NoSuchFileException; + import java.util.ArrayList; + import java.util.Arrays; ++import java.util.HashMap; + import java.util.Iterator; + import java.util.LinkedHashMap; + import java.util.List; +@@ -42,11 +43,16 @@ import org.springframework.util.StringUtils; + * @author Phillip Webb + * @author Madhura Bhave + * @author Moritz Halbritter ++ * @author Junggi Kim + */ + class IndexedLayers implements Layers { + + private final Map<String, List<String>> layers = new LinkedHashMap<>(); + ++ private final Map<String, String> layerByFileName = new HashMap<>(); ++ ++ private final Map<String, String> layerByDirectoryName = new LinkedHashMap<>(); ++ + private final String indexFileLocation; + + IndexedLayers(String indexFile, String indexFileLocation) { +@@ -70,6 +76,10 @@ class IndexedLayers implements Layers { + } + } + Assert.state(!this.layers.isEmpty(), "Empty layer index file loaded"); ++ this.layers.forEach((layer, candidates) -> candidates.forEach((candidate) -> { ++ Map<String, String> index = candidate.endsWith("/") ? this.layerByDirectoryName : this.layerByFileName; ++ index.putIfAbsent(candidate, layer); ++ })); + } + + @Override +@@ -84,11 +94,13 @@ class IndexedLayers implements Layers { + + @Override + public String getLayer(String name) { +- for (Map.Entry<String, List<String>> entry : this.layers.entrySet()) { +- for (String candidate : entry.getValue()) { +- if (candidate.equals(name) || (candidate.endsWith("/") && name.startsWith(candidate))) { +- return entry.getKey(); +- } ++ String layer = this.layerByFileName.get(name); ++ if (layer != null) { ++ return layer; ++ } ++ for (Map.Entry<String, String> entry : this.layerByDirectoryName.entrySet()) { ++ if (name.startsWith(entry.getKey())) { ++ return entry.getValue(); + } + } + throw new IllegalStateException("No layer defined in index for file '" + name + "'"); +diff --git a/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/IndexedLayersTests.java b/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/IndexedLayersTests.java +index 50053fb1a7b..f21d4444bbc 100644 +--- a/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/IndexedLayersTests.java ++++ b/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/IndexedLayersTests.java +@@ -38,6 +38,7 @@ import static org.mockito.Mockito.mock; + * + * @author Phillip Webb + * @author Madhura Bhave ++ * @author Junggi Kim + */ + class IndexedLayersTests { + +@@ -83,6 +84,13 @@ class IndexedLayersTests { + assertThat(layers.getLayer(mockEntry("META-INF/a/sub/directory/and/a/file"))).isEqualTo("application"); + } + ++ @Test ++ void getLayerWhenNameIsInMultipleLayersReturnsFirstLayer() { ++ IndexedLayers layers = new IndexedLayers(createIndexWithDuplicateName(), "BOOT-INF/classes"); ++ assertThat(layers.getLayer(mockEntry("BOOT-INF/lib/a.jar"))).isEqualTo("first"); ++ assertThat(layers.getLayer(mockEntry("META-INF/MANIFEST.MF"))).isEqualTo("first"); ++ } ++ + @Test + void getLayerWhenFileHasSpaceReturnsLayer() throws Exception { + IndexedLayers layers = new IndexedLayers(getIndex(), "BOOT-INF/classes"); +@@ -102,6 +110,17 @@ class IndexedLayersTests { + return getFile("test-layers.idx"); + } + ++ private String createIndexWithDuplicateName() { ++ return """ ++ - "first": ++ - "BOOT-INF/lib/a.jar" ++ - "META-INF/" ++ - "second": ++ - "BOOT-INF/lib/a.jar" ++ - "META-INF/" ++ """; ++ } ++ + private String getFile(String fileName) throws Exception { + ClassPathResource resource = new ClassPathResource(fileName, getClass()); + InputStreamReader reader = new InputStreamReader(resource.getInputStream()); diff --git a/tasks/spring-projects__spring-boot-51653/solution/solve.sh b/tasks/spring-projects__spring-boot-51653/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51653/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51653/task.toml b/tasks/spring-projects__spring-boot-51653/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ac85bcb17c04d917a0b8f947499bd8a49ce07d29 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51653/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51653" +description = "Speed up layer lookups when extracting a layered jar" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "59379ae449f15a6d17a333f5505941f4165ab3b2" +reference = "https://github.com/spring-projects/spring-boot/pull/51653" +source_access = "auto" +built_at = "2026-11-16T16:09:44.759171+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e38ffb4eee82087d870b16e49f8a2aca7145892878885174bc48fdcab563b12c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T14:28:26Z" +diff_format = "unified" +context_files = [ + "loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/IndexedLayers.java", + "loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/IndexedLayersTests.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 41 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.172106+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:74364d435c7851387aae3e43db0aa995a13d80ba3701edb4f214de71864e044d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51653/tests/capture.py b/tasks/spring-projects__spring-boot-51653/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51653/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51653/tests/instruction.md b/tasks/spring-projects__spring-boot-51653/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..33e4d878935fce5371b3ef56698279a851acd5b8 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51653/tests/instruction.md @@ -0,0 +1,56 @@ +# Issue + +**Title:** Speed up layer lookups when extracting a layered jar + +## Description + +`IndexedLayers.getLayer()` is called once for every entry of a layered jar while `java -Djarmode=tools extract` unpacks it, and each call walks `layers.idx` from the top: + +```java +for (Map.Entry<String, List<String>> entry : this.layers.entrySet()) { + for (String candidate : entry.getValue()) { + if (candidate.equals(name) || (candidate.endsWith("/") && name.startsWith(candidate))) { + return entry.getKey(); + } + } +} +``` + +That makes extraction `O(entries x index size)`. The layout of the index makes it worse than the formula suggests: dependencies are listed one line per jar and come first, while the application classes are covered by a single `BOOT-INF/classes/` entry near the end. The most numerous entries therefore consistently scan the longest — for a 700 dependency jar every application class walks past all 700 dependency lines before reaching the line that matches it. + +This indexes the candidates once, when the index file is read, splitting them by kind: + +* names that do not end in `/` go into a `HashMap`, so a file name is resolved with a single lookup +* names that end in `/` go into a `LinkedHashMap` that preserves index order, so only the handful of directory candidates has to be scanned + +`candidate.endsWith("/")` is now evaluated once per index line instead of once per lookup. + +### Measurements + +Realistic indexes and entry lists, median of 15 runs after 40 warm-up runs, JDK 25. Comparison counts are deterministic. + +| Entries | Dependencies | Before | After | String comparisons | +| --- | --- | --- | --- | --- | +| 903 | 80 | 0.76ms | 0.05ms | 70,612 → 2,426 | +| 4,173 | 250 | 5.36ms | 0.13ms | 1,019,857 → 11,896 | +| 24,823 | 700 | 106.92ms | 2.51ms | 17,179,582 → 72,946 | + +The absolute saving is around 100ms on the largest jar, so this is not something most builds will notice. The point is that the cost stops growing with the product of jar size and index size. + +### Behaviour + +Lookups resolve to the same layer as before. + +The only reordering is that exact file names are now consulted before directory prefixes, where previously both kinds were interleaved in index order. That cannot change an answer, because `LayersIndex.Node.buildIndex` only writes a name once its whole subtree belongs to a single layer and otherwise recurses into the children. No indexed name can therefore be a prefix of another indexed name, and at most one candidate can match any given entry. + +`putIfAbsent` keeps the first occurrence of a repeated name, matching the first-match-wins behaviour of the loop it replaces. + +Verified with: + +* the existing `IndexedLayersTests`, unchanged, plus one added test covering a name that appears in more than one layer. That test passes against the current implementation as well, so it is a regression guard rather than a new expectation +* a differential harness running both implementations side by side over randomly generated indexes — 218,963 lookups, including the thrown `IllegalStateException` messages, with no differences +* `./gradlew :loader:spring-boot-jarmode-tools:test checkFormatMain checkFormatTest checkstyleMain checkstyleTest` — 95 tests, no format or Checkstyle violations + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `59379ae449f1`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51653/tests/oracle.patch b/tasks/spring-projects__spring-boot-51653/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9e3d3e4104446746377c5cf9392b098fb5abd21c --- /dev/null +++ b/tasks/spring-projects__spring-boot-51653/tests/oracle.patch @@ -0,0 +1,103 @@ +diff --git a/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/IndexedLayers.java b/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/IndexedLayers.java +index 7f560d0656d..df2cc7eba84 100644 +--- a/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/IndexedLayers.java ++++ b/loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/IndexedLayers.java +@@ -22,6 +22,7 @@ import java.nio.charset.StandardCharsets; + import java.nio.file.NoSuchFileException; + import java.util.ArrayList; + import java.util.Arrays; ++import java.util.HashMap; + import java.util.Iterator; + import java.util.LinkedHashMap; + import java.util.List; +@@ -42,11 +43,16 @@ import org.springframework.util.StringUtils; + * @author Phillip Webb + * @author Madhura Bhave + * @author Moritz Halbritter ++ * @author Junggi Kim + */ + class IndexedLayers implements Layers { + + private final Map<String, List<String>> layers = new LinkedHashMap<>(); + ++ private final Map<String, String> layerByFileName = new HashMap<>(); ++ ++ private final Map<String, String> layerByDirectoryName = new LinkedHashMap<>(); ++ + private final String indexFileLocation; + + IndexedLayers(String indexFile, String indexFileLocation) { +@@ -70,6 +76,10 @@ class IndexedLayers implements Layers { + } + } + Assert.state(!this.layers.isEmpty(), "Empty layer index file loaded"); ++ this.layers.forEach((layer, candidates) -> candidates.forEach((candidate) -> { ++ Map<String, String> index = candidate.endsWith("/") ? this.layerByDirectoryName : this.layerByFileName; ++ index.putIfAbsent(candidate, layer); ++ })); + } + + @Override +@@ -84,11 +94,13 @@ class IndexedLayers implements Layers { + + @Override + public String getLayer(String name) { +- for (Map.Entry<String, List<String>> entry : this.layers.entrySet()) { +- for (String candidate : entry.getValue()) { +- if (candidate.equals(name) || (candidate.endsWith("/") && name.startsWith(candidate))) { +- return entry.getKey(); +- } ++ String layer = this.layerByFileName.get(name); ++ if (layer != null) { ++ return layer; ++ } ++ for (Map.Entry<String, String> entry : this.layerByDirectoryName.entrySet()) { ++ if (name.startsWith(entry.getKey())) { ++ return entry.getValue(); + } + } + throw new IllegalStateException("No layer defined in index for file '" + name + "'"); +diff --git a/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/IndexedLayersTests.java b/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/IndexedLayersTests.java +index 50053fb1a7b..f21d4444bbc 100644 +--- a/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/IndexedLayersTests.java ++++ b/loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/IndexedLayersTests.java +@@ -38,6 +38,7 @@ import static org.mockito.Mockito.mock; + * + * @author Phillip Webb + * @author Madhura Bhave ++ * @author Junggi Kim + */ + class IndexedLayersTests { + +@@ -83,6 +84,13 @@ class IndexedLayersTests { + assertThat(layers.getLayer(mockEntry("META-INF/a/sub/directory/and/a/file"))).isEqualTo("application"); + } + ++ @Test ++ void getLayerWhenNameIsInMultipleLayersReturnsFirstLayer() { ++ IndexedLayers layers = new IndexedLayers(createIndexWithDuplicateName(), "BOOT-INF/classes"); ++ assertThat(layers.getLayer(mockEntry("BOOT-INF/lib/a.jar"))).isEqualTo("first"); ++ assertThat(layers.getLayer(mockEntry("META-INF/MANIFEST.MF"))).isEqualTo("first"); ++ } ++ + @Test + void getLayerWhenFileHasSpaceReturnsLayer() throws Exception { + IndexedLayers layers = new IndexedLayers(getIndex(), "BOOT-INF/classes"); +@@ -102,6 +110,17 @@ class IndexedLayersTests { + return getFile("test-layers.idx"); + } + ++ private String createIndexWithDuplicateName() { ++ return """ ++ - "first": ++ - "BOOT-INF/lib/a.jar" ++ - "META-INF/" ++ - "second": ++ - "BOOT-INF/lib/a.jar" ++ - "META-INF/" ++ """; ++ } ++ + private String getFile(String fileName) throws Exception { + ClassPathResource resource = new ClassPathResource(fileName, getClass()); + InputStreamReader reader = new InputStreamReader(resource.getInputStream()); diff --git a/tasks/spring-projects__spring-boot-51653/tests/test.sh b/tasks/spring-projects__spring-boot-51653/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9fc55ec9671acecdd011adbff90e898ec50ec5ee --- /dev/null +++ b/tasks/spring-projects__spring-boot-51653/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 59379ae449f15a6d17a333f5505941f4165ab3b2 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51653/tests/verifier.py b/tasks/spring-projects__spring-boot-51653/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51653/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51654/environment/Dockerfile b/tasks/spring-projects__spring-boot-51654/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1a0e31f29057b79245ebdb52aaf2f115347cec47 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51654/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c966eca3e7467c2524df980aa52bac517b59a40b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c966eca3e7467c2524df980aa52bac517b59a40b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c966eca3e7467c2524df980aa52bac517b59a40b \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51654/instruction.md b/tasks/spring-projects__spring-boot-51654/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a111bf2f6132981667a9f031228c0f92f7b7163a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51654/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Improve the performance of layer index creation + +## Description + +`LayersIndex.add(...)` is called once for every file entry written into the jar, and walks one node per path segment. Each node holds its children in a `List`, and `updateOrAddNode(...)` finds the child for a segment by comparing names one at a time, so building the index costs `O(entries x siblings)` rather than `O(entries)`. + +What decides how much that costs is the largest flat directory in the jar rather than the entry count. Application classes are spread over a package tree, so each of those directories holds relatively few children, and `BOOT-INF/lib/` holds one entry per dependency. The problem case is a genuinely flat directory: an application that bundles a front-end build has thousands of hashed files sitting directly under `BOOT-INF/classes/static/`. Filling a directory with n children by scanning costs n(n-1)/2 name comparisons, so 12,000 files in one directory is around 72 million comparisons for that directory alone, against 12,000 lookups if the children are indexed by name. + +This keeps the children in a `LinkedHashMap` keyed by the segment name, so the lookup is a single hash lookup rather than a scan and the index is built in `O(entries)`. Insertion order is preserved, so `buildIndex(...)` walks the tree exactly as before. `Node(String name, Layer layer)` becomes `Node(String name)` so that the layer is recorded on one code path whether or not the node already existed. + +The output is unchanged. Replaying every entry of a real `bootJar` output through `LayersIndex`, with each entry's layer taken from that jar's own `layers.idx`, produces a file that is byte for byte identical to the one the plugin originally wrote, and 300,000 randomly generated indexes produce identical output before and after, including segments that are duplicated, contain spaces or non-ASCII characters, or are used as both a file and a directory. Existing tests pass unchanged, as do `checkstyleMain`, `checkstyleTest`, `checkFormatMain` and `checkFormatTest`. + +I have not added a test, since `LayersIndexTests` and the `layersIndex()` test in `AbstractPackagerTests` already fail if the child lookup or the layer accumulation is broken, but I am happy to add one if you would prefer the behaviour pinned explicitly. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c966eca3e746`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51654/solution/patch.diff b/tasks/spring-projects__spring-boot-51654/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..68fdcb84e20159b29ad746c80baddd8fdd034716 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51654/solution/patch.diff @@ -0,0 +1,70 @@ +diff --git a/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/LayersIndex.java b/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/LayersIndex.java +index f2e6bd770cf..7926f5bf4c4 100644 +--- a/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/LayersIndex.java ++++ b/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/LayersIndex.java +@@ -21,11 +21,12 @@ import java.io.IOException; + import java.io.OutputStream; + import java.io.OutputStreamWriter; + import java.nio.charset.StandardCharsets; +-import java.util.ArrayList; + import java.util.Arrays; + import java.util.Collections; + import java.util.HashSet; ++import java.util.LinkedHashMap; + import java.util.List; ++import java.util.Map; + import java.util.Set; + + import org.springframework.util.LinkedMultiValueMap; +@@ -47,6 +48,7 @@ import org.springframework.util.MultiValueMap; + * @author Madhura Bhave + * @author Andy Wilkinson + * @author Phillip Webb ++ * @author Junggi Kim + * @since 2.3.0 + */ + public class LayersIndex { +@@ -116,28 +118,21 @@ public class LayersIndex { + + private final Set<Layer> layers; + +- private final List<Node> children = new ArrayList<>(); ++ private final Map<String, Node> children = new LinkedHashMap<>(); + + Node() { +- this.name = ""; +- this.layers = new HashSet<>(); ++ this(""); + } + +- Node(String name, Layer layer) { ++ Node(String name) { + this.name = name; +- this.layers = new HashSet<>(Collections.singleton(layer)); ++ this.layers = new HashSet<>(); + } + + Node updateOrAddNode(String segment, boolean isDirectory, Layer layer) { + String name = segment + (isDirectory ? "/" : ""); +- for (Node child : this.children) { +- if (name.equals(child.name)) { +- child.layers.add(layer); +- return child; +- } +- } +- Node child = new Node(name, layer); +- this.children.add(child); ++ Node child = this.children.computeIfAbsent(name, Node::new); ++ child.layers.add(layer); + return child; + } + +@@ -147,7 +142,7 @@ public class LayersIndex { + index.add(this.layers.iterator().next(), name); + } + else { +- for (Node child : this.children) { ++ for (Node child : this.children.values()) { + child.buildIndex(name, index); + } + } diff --git a/tasks/spring-projects__spring-boot-51654/solution/solve.sh b/tasks/spring-projects__spring-boot-51654/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51654/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51654/task.toml b/tasks/spring-projects__spring-boot-51654/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..164c9cd2afa2af06fc844d753c7d31c7fbf73113 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51654/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51654" +description = "Improve the performance of layer index creation" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "c966eca3e7467c2524df980aa52bac517b59a40b" +reference = "https://github.com/spring-projects/spring-boot/pull/51654" +source_access = "auto" +built_at = "2026-11-16T16:09:44.756446+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:baa64acc57a7f9ac45b0ba2d1a56270bf868ef0e4b84ffdf7bb7a1de65c41486" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T14:34:20Z" +diff_format = "unified" +context_files = [ + "loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/LayersIndex.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 25 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.172655+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f9f3b6073b1c15984dce7b3aad84556dc9d84e236fb005ba2fed67b76164f21b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51654/tests/capture.py b/tasks/spring-projects__spring-boot-51654/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51654/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51654/tests/instruction.md b/tasks/spring-projects__spring-boot-51654/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a111bf2f6132981667a9f031228c0f92f7b7163a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51654/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** Improve the performance of layer index creation + +## Description + +`LayersIndex.add(...)` is called once for every file entry written into the jar, and walks one node per path segment. Each node holds its children in a `List`, and `updateOrAddNode(...)` finds the child for a segment by comparing names one at a time, so building the index costs `O(entries x siblings)` rather than `O(entries)`. + +What decides how much that costs is the largest flat directory in the jar rather than the entry count. Application classes are spread over a package tree, so each of those directories holds relatively few children, and `BOOT-INF/lib/` holds one entry per dependency. The problem case is a genuinely flat directory: an application that bundles a front-end build has thousands of hashed files sitting directly under `BOOT-INF/classes/static/`. Filling a directory with n children by scanning costs n(n-1)/2 name comparisons, so 12,000 files in one directory is around 72 million comparisons for that directory alone, against 12,000 lookups if the children are indexed by name. + +This keeps the children in a `LinkedHashMap` keyed by the segment name, so the lookup is a single hash lookup rather than a scan and the index is built in `O(entries)`. Insertion order is preserved, so `buildIndex(...)` walks the tree exactly as before. `Node(String name, Layer layer)` becomes `Node(String name)` so that the layer is recorded on one code path whether or not the node already existed. + +The output is unchanged. Replaying every entry of a real `bootJar` output through `LayersIndex`, with each entry's layer taken from that jar's own `layers.idx`, produces a file that is byte for byte identical to the one the plugin originally wrote, and 300,000 randomly generated indexes produce identical output before and after, including segments that are duplicated, contain spaces or non-ASCII characters, or are used as both a file and a directory. Existing tests pass unchanged, as do `checkstyleMain`, `checkstyleTest`, `checkFormatMain` and `checkFormatTest`. + +I have not added a test, since `LayersIndexTests` and the `layersIndex()` test in `AbstractPackagerTests` already fail if the child lookup or the layer accumulation is broken, but I am happy to add one if you would prefer the behaviour pinned explicitly. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c966eca3e746`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51654/tests/oracle.patch b/tasks/spring-projects__spring-boot-51654/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..68fdcb84e20159b29ad746c80baddd8fdd034716 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51654/tests/oracle.patch @@ -0,0 +1,70 @@ +diff --git a/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/LayersIndex.java b/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/LayersIndex.java +index f2e6bd770cf..7926f5bf4c4 100644 +--- a/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/LayersIndex.java ++++ b/loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/LayersIndex.java +@@ -21,11 +21,12 @@ import java.io.IOException; + import java.io.OutputStream; + import java.io.OutputStreamWriter; + import java.nio.charset.StandardCharsets; +-import java.util.ArrayList; + import java.util.Arrays; + import java.util.Collections; + import java.util.HashSet; ++import java.util.LinkedHashMap; + import java.util.List; ++import java.util.Map; + import java.util.Set; + + import org.springframework.util.LinkedMultiValueMap; +@@ -47,6 +48,7 @@ import org.springframework.util.MultiValueMap; + * @author Madhura Bhave + * @author Andy Wilkinson + * @author Phillip Webb ++ * @author Junggi Kim + * @since 2.3.0 + */ + public class LayersIndex { +@@ -116,28 +118,21 @@ public class LayersIndex { + + private final Set<Layer> layers; + +- private final List<Node> children = new ArrayList<>(); ++ private final Map<String, Node> children = new LinkedHashMap<>(); + + Node() { +- this.name = ""; +- this.layers = new HashSet<>(); ++ this(""); + } + +- Node(String name, Layer layer) { ++ Node(String name) { + this.name = name; +- this.layers = new HashSet<>(Collections.singleton(layer)); ++ this.layers = new HashSet<>(); + } + + Node updateOrAddNode(String segment, boolean isDirectory, Layer layer) { + String name = segment + (isDirectory ? "/" : ""); +- for (Node child : this.children) { +- if (name.equals(child.name)) { +- child.layers.add(layer); +- return child; +- } +- } +- Node child = new Node(name, layer); +- this.children.add(child); ++ Node child = this.children.computeIfAbsent(name, Node::new); ++ child.layers.add(layer); + return child; + } + +@@ -147,7 +142,7 @@ public class LayersIndex { + index.add(this.layers.iterator().next(), name); + } + else { +- for (Node child : this.children) { ++ for (Node child : this.children.values()) { + child.buildIndex(name, index); + } + } diff --git a/tasks/spring-projects__spring-boot-51654/tests/test.sh b/tasks/spring-projects__spring-boot-51654/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7f0920c2ab0f68d647ba642748c8fe44c397e0bb --- /dev/null +++ b/tasks/spring-projects__spring-boot-51654/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c966eca3e7467c2524df980aa52bac517b59a40b > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51654/tests/verifier.py b/tasks/spring-projects__spring-boot-51654/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51654/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51655/environment/Dockerfile b/tasks/spring-projects__spring-boot-51655/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..80456f2748a7237b0d609048950d998b5edb0d27 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51655/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 69ad59c413ec8dfbd884ba0e712e8ada89513d29 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 69ad59c413ec8dfbd884ba0e712e8ada89513d29 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 69ad59c413ec8dfbd884ba0e712e8ada89513d29 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51655/instruction.md b/tasks/spring-projects__spring-boot-51655/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d0a124a3a401e4602117481d778616dd31819a6a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51655/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Simplify configuration metadata changelog generation + +## Description + +`Changelog.computeDifferences(...)` is quadratic in the number of configuration properties, in two independent ways. + +Its first loop asks the new repository for its properties on every iteration, and `SimpleConfigurationMetadataRepository.getAllProperties()` is not a plain getter: it allocates a `HashMap` and copies every group's properties into it on each call. A counting decorator around both repositories shows it being called 2,499 times on the new metadata while generating the 3.4.0 to 3.5.0 changelog, once per property of the old version. Separately, `seenIds` is an `ArrayList` that is only ever added to and searched with `contains`, so the second loop scans it from the start for every property of the new version. + +This reads the properties of each repository once. The membership check then no longer needs a collection of its own: `ConfigurationMetadataRepository.getAllProperties()` is documented to return the properties indexed by id, so the map of the old properties already answers what `seenIds` was tracking. + +Measured on my machine (JDK 25, aarch64) against the published metadata jars of the versions below, so the numbers describe that environment rather than a guarantee: generating the 3.4.0 to 3.5.0 changelog (2,498 and 2,555 properties) takes 0.16s instead of 0.38s and peaks at 91MB rather than 302MB, with `computeDifferences` itself going from 203ms to 0.5ms. Both halves have to be fixed before that shows up — with the map still being rebuilt, giving `seenIds` a `HashSet` on its own only reaches 159ms. This only runs when a changelog is generated for a release, so the time saved is a fraction of a second and no build will notice it; the allocation is the more interesting half. + +The generated asciidoc is unchanged. Both 3.4.0 to 3.5.0 and 3.5.0 to 4.1.1 produce a file with an identical SHA-256 before and after. + +I have not added a test. Inverting the new membership check, pointing it at the new properties instead of the old ones, and looking a property up in the old map instead of the new one all fail `ChangelogTests` and `ChangelogGeneratorTests` as they stand, and what is left is not observable through behaviour. Happy to add one if you would prefer it pinned. + +Verified with `./gradlew :configuration-metadata:spring-boot-configuration-metadata-changelog-generator:build checkFormatMain checkFormatTest`: 10 tests, no Checkstyle or format violations. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `69ad59c413ec`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51655/solution/patch.diff b/tasks/spring-projects__spring-boot-51655/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..48aadc8355c9950c57c3fc2263fdac42ee8e78e7 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51655/solution/patch.diff @@ -0,0 +1,46 @@ +diff --git a/configuration-metadata/spring-boot-configuration-metadata-changelog-generator/src/main/java/org/springframework/boot/configurationmetadata/changelog/Changelog.java b/configuration-metadata/spring-boot-configuration-metadata-changelog-generator/src/main/java/org/springframework/boot/configurationmetadata/changelog/Changelog.java +index df46b7fb7e2..d9f3738f9e6 100644 +--- a/configuration-metadata/spring-boot-configuration-metadata-changelog-generator/src/main/java/org/springframework/boot/configurationmetadata/changelog/Changelog.java ++++ b/configuration-metadata/spring-boot-configuration-metadata-changelog-generator/src/main/java/org/springframework/boot/configurationmetadata/changelog/Changelog.java +@@ -18,6 +18,7 @@ package org.springframework.boot.configurationmetadata.changelog; + + import java.util.ArrayList; + import java.util.List; ++import java.util.Map; + + import org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty; + import org.springframework.boot.configurationmetadata.ConfigurationMetadataRepository; +@@ -34,6 +35,7 @@ import org.springframework.boot.configurationmetadata.Deprecation.Level; + * @author Andy Wilkinson + * @author Phillip Webb + * @author Yoobin Yoon ++ * @author Junggi Kim + */ + record Changelog(String oldVersionNumber, String newVersionNumber, List<Difference> differences) { + +@@ -44,19 +46,18 @@ record Changelog(String oldVersionNumber, String newVersionNumber, List<Differen + + static List<Difference> computeDifferences(ConfigurationMetadataRepository oldMetadata, + ConfigurationMetadataRepository newMetadata) { +- List<String> seenIds = new ArrayList<>(); ++ Map<String, ConfigurationMetadataProperty> oldProperties = oldMetadata.getAllProperties(); ++ Map<String, ConfigurationMetadataProperty> newProperties = newMetadata.getAllProperties(); + List<Difference> differences = new ArrayList<>(); +- for (ConfigurationMetadataProperty oldProperty : oldMetadata.getAllProperties().values()) { +- String id = oldProperty.getId(); +- seenIds.add(id); +- ConfigurationMetadataProperty newProperty = newMetadata.getAllProperties().get(id); ++ for (ConfigurationMetadataProperty oldProperty : oldProperties.values()) { ++ ConfigurationMetadataProperty newProperty = newProperties.get(oldProperty.getId()); + Difference difference = Difference.compute(oldProperty, newProperty); + if (difference != null) { + differences.add(difference); + } + } +- for (ConfigurationMetadataProperty newProperty : newMetadata.getAllProperties().values()) { +- if (!seenIds.contains(newProperty.getId())) { ++ for (ConfigurationMetadataProperty newProperty : newProperties.values()) { ++ if (!oldProperties.containsKey(newProperty.getId())) { + if (!newProperty.isDeprecated()) { + differences.add(new Difference(DifferenceType.ADDED, null, newProperty)); + } diff --git a/tasks/spring-projects__spring-boot-51655/solution/solve.sh b/tasks/spring-projects__spring-boot-51655/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51655/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51655/task.toml b/tasks/spring-projects__spring-boot-51655/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3a5bacef6e50b17c7bf7f1b8173c18f79d95691a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51655/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51655" +description = "Simplify configuration metadata changelog generation" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "69ad59c413ec8dfbd884ba0e712e8ada89513d29" +reference = "https://github.com/spring-projects/spring-boot/pull/51655" +source_access = "auto" +built_at = "2026-11-16T16:09:44.754315+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:bdf44c780d0702631972e0f44eb98e046878d7bf77b8bc955f43823a630bd2d5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T14:40:12Z" +diff_format = "unified" +context_files = [ + "configuration-metadata/spring-boot-configuration-metadata-changelog-generator/src/main/java/org/springframework/boot/configurationmetadata/changelog/Changelog.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 15 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.173200+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3e0502a3dceccbd5aedffabedfbdc34d24409f81504c83aac8730eeca279ceac" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51655/tests/capture.py b/tasks/spring-projects__spring-boot-51655/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51655/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51655/tests/instruction.md b/tasks/spring-projects__spring-boot-51655/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d0a124a3a401e4602117481d778616dd31819a6a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51655/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Simplify configuration metadata changelog generation + +## Description + +`Changelog.computeDifferences(...)` is quadratic in the number of configuration properties, in two independent ways. + +Its first loop asks the new repository for its properties on every iteration, and `SimpleConfigurationMetadataRepository.getAllProperties()` is not a plain getter: it allocates a `HashMap` and copies every group's properties into it on each call. A counting decorator around both repositories shows it being called 2,499 times on the new metadata while generating the 3.4.0 to 3.5.0 changelog, once per property of the old version. Separately, `seenIds` is an `ArrayList` that is only ever added to and searched with `contains`, so the second loop scans it from the start for every property of the new version. + +This reads the properties of each repository once. The membership check then no longer needs a collection of its own: `ConfigurationMetadataRepository.getAllProperties()` is documented to return the properties indexed by id, so the map of the old properties already answers what `seenIds` was tracking. + +Measured on my machine (JDK 25, aarch64) against the published metadata jars of the versions below, so the numbers describe that environment rather than a guarantee: generating the 3.4.0 to 3.5.0 changelog (2,498 and 2,555 properties) takes 0.16s instead of 0.38s and peaks at 91MB rather than 302MB, with `computeDifferences` itself going from 203ms to 0.5ms. Both halves have to be fixed before that shows up — with the map still being rebuilt, giving `seenIds` a `HashSet` on its own only reaches 159ms. This only runs when a changelog is generated for a release, so the time saved is a fraction of a second and no build will notice it; the allocation is the more interesting half. + +The generated asciidoc is unchanged. Both 3.4.0 to 3.5.0 and 3.5.0 to 4.1.1 produce a file with an identical SHA-256 before and after. + +I have not added a test. Inverting the new membership check, pointing it at the new properties instead of the old ones, and looking a property up in the old map instead of the new one all fail `ChangelogTests` and `ChangelogGeneratorTests` as they stand, and what is left is not observable through behaviour. Happy to add one if you would prefer it pinned. + +Verified with `./gradlew :configuration-metadata:spring-boot-configuration-metadata-changelog-generator:build checkFormatMain checkFormatTest`: 10 tests, no Checkstyle or format violations. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `69ad59c413ec`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51655/tests/oracle.patch b/tasks/spring-projects__spring-boot-51655/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..48aadc8355c9950c57c3fc2263fdac42ee8e78e7 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51655/tests/oracle.patch @@ -0,0 +1,46 @@ +diff --git a/configuration-metadata/spring-boot-configuration-metadata-changelog-generator/src/main/java/org/springframework/boot/configurationmetadata/changelog/Changelog.java b/configuration-metadata/spring-boot-configuration-metadata-changelog-generator/src/main/java/org/springframework/boot/configurationmetadata/changelog/Changelog.java +index df46b7fb7e2..d9f3738f9e6 100644 +--- a/configuration-metadata/spring-boot-configuration-metadata-changelog-generator/src/main/java/org/springframework/boot/configurationmetadata/changelog/Changelog.java ++++ b/configuration-metadata/spring-boot-configuration-metadata-changelog-generator/src/main/java/org/springframework/boot/configurationmetadata/changelog/Changelog.java +@@ -18,6 +18,7 @@ package org.springframework.boot.configurationmetadata.changelog; + + import java.util.ArrayList; + import java.util.List; ++import java.util.Map; + + import org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty; + import org.springframework.boot.configurationmetadata.ConfigurationMetadataRepository; +@@ -34,6 +35,7 @@ import org.springframework.boot.configurationmetadata.Deprecation.Level; + * @author Andy Wilkinson + * @author Phillip Webb + * @author Yoobin Yoon ++ * @author Junggi Kim + */ + record Changelog(String oldVersionNumber, String newVersionNumber, List<Difference> differences) { + +@@ -44,19 +46,18 @@ record Changelog(String oldVersionNumber, String newVersionNumber, List<Differen + + static List<Difference> computeDifferences(ConfigurationMetadataRepository oldMetadata, + ConfigurationMetadataRepository newMetadata) { +- List<String> seenIds = new ArrayList<>(); ++ Map<String, ConfigurationMetadataProperty> oldProperties = oldMetadata.getAllProperties(); ++ Map<String, ConfigurationMetadataProperty> newProperties = newMetadata.getAllProperties(); + List<Difference> differences = new ArrayList<>(); +- for (ConfigurationMetadataProperty oldProperty : oldMetadata.getAllProperties().values()) { +- String id = oldProperty.getId(); +- seenIds.add(id); +- ConfigurationMetadataProperty newProperty = newMetadata.getAllProperties().get(id); ++ for (ConfigurationMetadataProperty oldProperty : oldProperties.values()) { ++ ConfigurationMetadataProperty newProperty = newProperties.get(oldProperty.getId()); + Difference difference = Difference.compute(oldProperty, newProperty); + if (difference != null) { + differences.add(difference); + } + } +- for (ConfigurationMetadataProperty newProperty : newMetadata.getAllProperties().values()) { +- if (!seenIds.contains(newProperty.getId())) { ++ for (ConfigurationMetadataProperty newProperty : newProperties.values()) { ++ if (!oldProperties.containsKey(newProperty.getId())) { + if (!newProperty.isDeprecated()) { + differences.add(new Difference(DifferenceType.ADDED, null, newProperty)); + } diff --git a/tasks/spring-projects__spring-boot-51655/tests/test.sh b/tasks/spring-projects__spring-boot-51655/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e161ccacdc35aae3467d0d066dcf9a9b10c6738f --- /dev/null +++ b/tasks/spring-projects__spring-boot-51655/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 69ad59c413ec8dfbd884ba0e712e8ada89513d29 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51655/tests/verifier.py b/tasks/spring-projects__spring-boot-51655/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51655/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51656/environment/Dockerfile b/tasks/spring-projects__spring-boot-51656/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..67b41d64ce7b82eac3e2f0bcf1c4a4bcb104563f --- /dev/null +++ b/tasks/spring-projects__spring-boot-51656/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 924d10733e3c084ff0b7c97856d20d1259415ae8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 924d10733e3c084ff0b7c97856d20d1259415ae8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 924d10733e3c084ff0b7c97856d20d1259415ae8 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51656/instruction.md b/tasks/spring-projects__spring-boot-51656/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f23a5647e0712701958a3984b2c598aaa28b540e --- /dev/null +++ b/tasks/spring-projects__spring-boot-51656/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Add auto-configured BaggageTaggingSpanProcessor for OpenTelemetry tag fields + +## Description + +Split out of #51597 as requested by @wilkinsona there: this PR carries only the enhancement, #51597 now carries only the documentation of the existing gRPC propagation support (targeting 4.1.x). + +### Problem + +With OpenTelemetry, `management.tracing.baggage.tag-fields` are not applied to the span of an incoming request unless the application itself calls `tracer.getBaggage(...)`. The baggage is extracted and propagated correctly, only the tags are missing. This is micrometer-metrics/tracing#933; the root cause is in the OTel bridge, which starts the span with a parent `Context` built from `Context.current()` and drops the baggage extracted into the trace context, so `SpanProcessor#onStart` never sees it (fix proposed in micrometer-metrics/tracing#1548). + +### Change + +`OpenTelemetryPropagationConfigurations.PropagationWithBaggage` registers Micrometer Tracing's `BaggageTaggingSpanProcessor` when baggage is enabled and at least one tag field is configured (`OnPropertyListCondition` on `management.tracing.baggage.tag-fields`). A custom `BaggageTaggingSpanProcessor` bean backs off the auto-configured one. Spans that start while baggage is current (client and internal spans) are tagged right away; server spans of incoming requests are covered once the bridge fix lands, without further changes here. The `tag-fields` property is also mentioned in the baggage section of the tracing documentation. + +### Tests + +Bean present with tag fields, absent without them or with baggage disabled, back-off on a custom bean, and a functional check that a span started with baggage in scope carries the configured tag and not other baggage entries. Module tests, Checkstyle and format are green on `main`. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `924d10733e3c`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51656/solution/patch.diff b/tasks/spring-projects__spring-boot-51656/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..dbb16d27b234f1eeea71d6775b7870a96c27e567 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51656/solution/patch.diff @@ -0,0 +1,190 @@ +diff --git a/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/tracing.adoc b/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/tracing.adoc +index e0cccc30931..6cdd91017dd 100644 +--- a/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/tracing.adoc ++++ b/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/tracing.adoc +@@ -236,6 +236,9 @@ Baggage is propagated wherever Micrometer Observation instruments the transport, + If you want to propagate the baggage to the MDC, use the configprop:management.tracing.baggage.correlation.fields[] configuration property. + For the example above, setting this property to `baggage1` results in an MDC entry named `baggage1`. + ++If you want baggage values to be added as tags on spans, use the configprop:management.tracing.baggage.tag-fields[] configuration property. ++For the example above, setting this property to `baggage1` results in spans that are tagged with `baggage1=value1`. ++ + + + [[actuator.micrometer-tracing.tests]] +diff --git a/module/spring-boot-micrometer-tracing-opentelemetry/src/main/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryPropagationConfigurations.java b/module/spring-boot-micrometer-tracing-opentelemetry/src/main/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryPropagationConfigurations.java +index 4f9fb4dbb01..540fc9053a2 100644 +--- a/module/spring-boot-micrometer-tracing-opentelemetry/src/main/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryPropagationConfigurations.java ++++ b/module/spring-boot-micrometer-tracing-opentelemetry/src/main/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryPropagationConfigurations.java +@@ -18,18 +18,22 @@ package org.springframework.boot.micrometer.tracing.opentelemetry.autoconfigure; + + import java.util.List; + ++import io.micrometer.tracing.otel.bridge.BaggageTaggingSpanProcessor; + import io.micrometer.tracing.otel.bridge.OtelBaggageManager; + import io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext; + import io.micrometer.tracing.otel.bridge.Slf4JBaggageEventListener; + import io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator; + import io.opentelemetry.context.propagation.TextMapPropagator; + ++import org.springframework.boot.autoconfigure.condition.ConditionMessage; + import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty; + import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; ++import org.springframework.boot.autoconfigure.condition.OnPropertyListCondition; + import org.springframework.boot.context.properties.EnableConfigurationProperties; + import org.springframework.boot.micrometer.tracing.autoconfigure.ConditionalOnEnabledTracingExport; + import org.springframework.boot.micrometer.tracing.autoconfigure.TracingProperties; + import org.springframework.context.annotation.Bean; ++import org.springframework.context.annotation.Conditional; + import org.springframework.context.annotation.Configuration; + + /** +@@ -37,6 +41,7 @@ import org.springframework.context.annotation.Configuration; + * {@link OpenTelemetryTracingAutoConfiguration}. + * + * @author Moritz Halbritter ++ * @author Oleksandr Shevchenko + */ + class OpenTelemetryPropagationConfigurations { + +@@ -87,6 +92,26 @@ class OpenTelemetryPropagationConfigurations { + return new Slf4JBaggageEventListener(this.tracingProperties.getBaggage().getCorrelation().getFields()); + } + ++ @Bean ++ @ConditionalOnMissingBean ++ @Conditional(OnBaggageTagFieldsCondition.class) ++ BaggageTaggingSpanProcessor otelBaggageTaggingSpanProcessor() { ++ return new BaggageTaggingSpanProcessor(this.tracingProperties.getBaggage().getTagFields()); ++ } ++ ++ /** ++ * Condition that matches when {@code management.tracing.baggage.tag-fields} has ++ * at least one entry. ++ */ ++ static class OnBaggageTagFieldsCondition extends OnPropertyListCondition { ++ ++ OnBaggageTagFieldsCondition() { ++ super("management.tracing.baggage.tag-fields", ++ () -> ConditionMessage.forCondition("Baggage tag fields")); ++ } ++ ++ } ++ + } + + /** +diff --git a/module/spring-boot-micrometer-tracing-opentelemetry/src/test/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryTracingAutoConfigurationTests.java b/module/spring-boot-micrometer-tracing-opentelemetry/src/test/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryTracingAutoConfigurationTests.java +index 9e86db47034..4c79a1b6ece 100644 +--- a/module/spring-boot-micrometer-tracing-opentelemetry/src/test/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryTracingAutoConfigurationTests.java ++++ b/module/spring-boot-micrometer-tracing-opentelemetry/src/test/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryTracingAutoConfigurationTests.java +@@ -30,6 +30,7 @@ import io.micrometer.tracing.SpanCustomizer; + import io.micrometer.tracing.Tracer.SpanInScope; + import io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler; + import io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler; ++import io.micrometer.tracing.otel.bridge.BaggageTaggingSpanProcessor; + import io.micrometer.tracing.otel.bridge.EventListener; + import io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext; + import io.micrometer.tracing.otel.bridge.OtelPropagator; +@@ -40,18 +41,21 @@ import io.micrometer.tracing.otel.bridge.Slf4JBaggageEventListener; + import io.micrometer.tracing.otel.bridge.Slf4JEventListener; + import io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator; + import io.micrometer.tracing.propagation.Propagator; ++import io.opentelemetry.api.baggage.Baggage; + import io.opentelemetry.api.common.AttributeKey; + import io.opentelemetry.api.common.Attributes; + import io.opentelemetry.api.metrics.MeterProvider; + import io.opentelemetry.api.trace.Span; + import io.opentelemetry.api.trace.Tracer; + import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; ++import io.opentelemetry.context.Scope; + import io.opentelemetry.context.propagation.ContextPropagators; + import io.opentelemetry.context.propagation.TextMapPropagator; + import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; + import io.opentelemetry.extension.trace.propagation.B3Propagator; + import io.opentelemetry.sdk.common.CompletableResultCode; + import io.opentelemetry.sdk.resources.Resource; ++import io.opentelemetry.sdk.trace.ReadableSpan; + import io.opentelemetry.sdk.trace.SdkTracerProvider; + import io.opentelemetry.sdk.trace.SpanLimits; + import io.opentelemetry.sdk.trace.SpanProcessor; +@@ -91,6 +95,7 @@ import static org.mockito.Mockito.mock; + * @author Moritz Halbritter + * @author Andy Wilkinson + * @author Yanming Zhou ++ * @author Oleksandr Shevchenko + */ + class OpenTelemetryTracingAutoConfigurationTests { + +@@ -390,6 +395,54 @@ class OpenTelemetryTracingAutoConfigurationTests { + }); + } + ++ @Test ++ void shouldSupplyBaggageTaggingSpanProcessorWhenTagFieldsAreConfigured() { ++ this.contextRunner.withPropertyValues("management.tracing.baggage.tag-fields=t1,t2").run((context) -> { ++ assertThat(context).hasSingleBean(BaggageTaggingSpanProcessor.class); ++ SpanProcessors spanProcessors = context.getBean(SpanProcessors.class); ++ assertThat(spanProcessors).anyMatch(BaggageTaggingSpanProcessor.class::isInstance); ++ }); ++ } ++ ++ @Test ++ void shouldNotSupplyBaggageTaggingSpanProcessorWhenTagFieldsAreNotConfigured() { ++ this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(BaggageTaggingSpanProcessor.class)); ++ } ++ ++ @Test ++ void shouldNotSupplyBaggageTaggingSpanProcessorWhenBaggageDisabled() { ++ this.contextRunner ++ .withPropertyValues("management.tracing.baggage.enabled=false", "management.tracing.baggage.tag-fields=t1") ++ .run((context) -> assertThat(context).doesNotHaveBean(BaggageTaggingSpanProcessor.class)); ++ } ++ ++ @Test ++ void shouldBackOffOnCustomBaggageTaggingSpanProcessor() { ++ this.contextRunner.withPropertyValues("management.tracing.baggage.tag-fields=t1") ++ .withUserConfiguration(CustomBaggageTaggingSpanProcessorConfiguration.class) ++ .run((context) -> { ++ assertThat(context).hasBean("customBaggageTaggingSpanProcessor"); ++ assertThat(context).hasSingleBean(BaggageTaggingSpanProcessor.class); ++ }); ++ } ++ ++ @Test ++ void baggageTaggingSpanProcessorShouldTagSpansWithBaggageFromParentContext() { ++ this.contextRunner ++ .withPropertyValues("management.tracing.baggage.tag-fields=t1", ++ "management.tracing.sampling.probability=1.0") ++ .run((context) -> { ++ Tracer tracer = context.getBean(Tracer.class); ++ try (Scope scope = Baggage.builder().put("t1", "v1").put("other", "v2").build().makeCurrent()) { ++ Span span = tracer.spanBuilder("test").startSpan(); ++ span.end(); ++ assertThat(span).isInstanceOf(ReadableSpan.class); ++ assertThat(((ReadableSpan) span).getAttribute(AttributeKey.stringKey("t1"))).isEqualTo("v1"); ++ assertThat(((ReadableSpan) span).getAttribute(AttributeKey.stringKey("other"))).isNull(); ++ } ++ }); ++ } ++ + @Test + void spanLimitsShouldBeConfiguredWithCustomProperties() { + this.contextRunner +@@ -608,6 +661,16 @@ class OpenTelemetryTracingAutoConfigurationTests { + + } + ++ @Configuration(proxyBeanMethods = false) ++ private static final class CustomBaggageTaggingSpanProcessorConfiguration { ++ ++ @Bean ++ BaggageTaggingSpanProcessor customBaggageTaggingSpanProcessor() { ++ return new BaggageTaggingSpanProcessor(List.of("custom")); ++ } ++ ++ } ++ + @Configuration(proxyBeanMethods = false) + private static final class AdditionalSpanProcessorConfiguration { + diff --git a/tasks/spring-projects__spring-boot-51656/solution/solve.sh b/tasks/spring-projects__spring-boot-51656/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51656/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51656/task.toml b/tasks/spring-projects__spring-boot-51656/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5b4e356d03f0ce8c5b8a6336e21bc5a3071b10a6 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51656/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51656" +description = "Add auto-configured BaggageTaggingSpanProcessor for OpenTelemetry tag fields" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "924d10733e3c084ff0b7c97856d20d1259415ae8" +reference = "https://github.com/spring-projects/spring-boot/pull/51656" +source_access = "auto" +built_at = "2026-11-16T16:09:44.595433+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:921b69136b8363ed4e60a880a8cec2ed228ef2336609c92740e3e045097e5545" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-11T10:21:50Z" +diff_format = "unified" +context_files = [ + "documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/tracing.adoc", + "module/spring-boot-micrometer-tracing-opentelemetry/src/main/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryPropagationConfigurations.java", + "module/spring-boot-micrometer-tracing-opentelemetry/src/test/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryTracingAutoConfigurationTests.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 91 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.173788+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:50e63d05b77e342de46aaadf7ea9a3f91375d91d50089a4f9e5450f3063f6c55" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51656/tests/capture.py b/tasks/spring-projects__spring-boot-51656/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51656/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51656/tests/instruction.md b/tasks/spring-projects__spring-boot-51656/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f23a5647e0712701958a3984b2c598aaa28b540e --- /dev/null +++ b/tasks/spring-projects__spring-boot-51656/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** Add auto-configured BaggageTaggingSpanProcessor for OpenTelemetry tag fields + +## Description + +Split out of #51597 as requested by @wilkinsona there: this PR carries only the enhancement, #51597 now carries only the documentation of the existing gRPC propagation support (targeting 4.1.x). + +### Problem + +With OpenTelemetry, `management.tracing.baggage.tag-fields` are not applied to the span of an incoming request unless the application itself calls `tracer.getBaggage(...)`. The baggage is extracted and propagated correctly, only the tags are missing. This is micrometer-metrics/tracing#933; the root cause is in the OTel bridge, which starts the span with a parent `Context` built from `Context.current()` and drops the baggage extracted into the trace context, so `SpanProcessor#onStart` never sees it (fix proposed in micrometer-metrics/tracing#1548). + +### Change + +`OpenTelemetryPropagationConfigurations.PropagationWithBaggage` registers Micrometer Tracing's `BaggageTaggingSpanProcessor` when baggage is enabled and at least one tag field is configured (`OnPropertyListCondition` on `management.tracing.baggage.tag-fields`). A custom `BaggageTaggingSpanProcessor` bean backs off the auto-configured one. Spans that start while baggage is current (client and internal spans) are tagged right away; server spans of incoming requests are covered once the bridge fix lands, without further changes here. The `tag-fields` property is also mentioned in the baggage section of the tracing documentation. + +### Tests + +Bean present with tag fields, absent without them or with baggage disabled, back-off on a custom bean, and a functional check that a span started with baggage in scope carries the configured tag and not other baggage entries. Module tests, Checkstyle and format are green on `main`. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `924d10733e3c`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51656/tests/oracle.patch b/tasks/spring-projects__spring-boot-51656/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..dbb16d27b234f1eeea71d6775b7870a96c27e567 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51656/tests/oracle.patch @@ -0,0 +1,190 @@ +diff --git a/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/tracing.adoc b/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/tracing.adoc +index e0cccc30931..6cdd91017dd 100644 +--- a/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/tracing.adoc ++++ b/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/tracing.adoc +@@ -236,6 +236,9 @@ Baggage is propagated wherever Micrometer Observation instruments the transport, + If you want to propagate the baggage to the MDC, use the configprop:management.tracing.baggage.correlation.fields[] configuration property. + For the example above, setting this property to `baggage1` results in an MDC entry named `baggage1`. + ++If you want baggage values to be added as tags on spans, use the configprop:management.tracing.baggage.tag-fields[] configuration property. ++For the example above, setting this property to `baggage1` results in spans that are tagged with `baggage1=value1`. ++ + + + [[actuator.micrometer-tracing.tests]] +diff --git a/module/spring-boot-micrometer-tracing-opentelemetry/src/main/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryPropagationConfigurations.java b/module/spring-boot-micrometer-tracing-opentelemetry/src/main/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryPropagationConfigurations.java +index 4f9fb4dbb01..540fc9053a2 100644 +--- a/module/spring-boot-micrometer-tracing-opentelemetry/src/main/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryPropagationConfigurations.java ++++ b/module/spring-boot-micrometer-tracing-opentelemetry/src/main/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryPropagationConfigurations.java +@@ -18,18 +18,22 @@ package org.springframework.boot.micrometer.tracing.opentelemetry.autoconfigure; + + import java.util.List; + ++import io.micrometer.tracing.otel.bridge.BaggageTaggingSpanProcessor; + import io.micrometer.tracing.otel.bridge.OtelBaggageManager; + import io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext; + import io.micrometer.tracing.otel.bridge.Slf4JBaggageEventListener; + import io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator; + import io.opentelemetry.context.propagation.TextMapPropagator; + ++import org.springframework.boot.autoconfigure.condition.ConditionMessage; + import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty; + import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; ++import org.springframework.boot.autoconfigure.condition.OnPropertyListCondition; + import org.springframework.boot.context.properties.EnableConfigurationProperties; + import org.springframework.boot.micrometer.tracing.autoconfigure.ConditionalOnEnabledTracingExport; + import org.springframework.boot.micrometer.tracing.autoconfigure.TracingProperties; + import org.springframework.context.annotation.Bean; ++import org.springframework.context.annotation.Conditional; + import org.springframework.context.annotation.Configuration; + + /** +@@ -37,6 +41,7 @@ import org.springframework.context.annotation.Configuration; + * {@link OpenTelemetryTracingAutoConfiguration}. + * + * @author Moritz Halbritter ++ * @author Oleksandr Shevchenko + */ + class OpenTelemetryPropagationConfigurations { + +@@ -87,6 +92,26 @@ class OpenTelemetryPropagationConfigurations { + return new Slf4JBaggageEventListener(this.tracingProperties.getBaggage().getCorrelation().getFields()); + } + ++ @Bean ++ @ConditionalOnMissingBean ++ @Conditional(OnBaggageTagFieldsCondition.class) ++ BaggageTaggingSpanProcessor otelBaggageTaggingSpanProcessor() { ++ return new BaggageTaggingSpanProcessor(this.tracingProperties.getBaggage().getTagFields()); ++ } ++ ++ /** ++ * Condition that matches when {@code management.tracing.baggage.tag-fields} has ++ * at least one entry. ++ */ ++ static class OnBaggageTagFieldsCondition extends OnPropertyListCondition { ++ ++ OnBaggageTagFieldsCondition() { ++ super("management.tracing.baggage.tag-fields", ++ () -> ConditionMessage.forCondition("Baggage tag fields")); ++ } ++ ++ } ++ + } + + /** +diff --git a/module/spring-boot-micrometer-tracing-opentelemetry/src/test/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryTracingAutoConfigurationTests.java b/module/spring-boot-micrometer-tracing-opentelemetry/src/test/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryTracingAutoConfigurationTests.java +index 9e86db47034..4c79a1b6ece 100644 +--- a/module/spring-boot-micrometer-tracing-opentelemetry/src/test/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryTracingAutoConfigurationTests.java ++++ b/module/spring-boot-micrometer-tracing-opentelemetry/src/test/java/org/springframework/boot/micrometer/tracing/opentelemetry/autoconfigure/OpenTelemetryTracingAutoConfigurationTests.java +@@ -30,6 +30,7 @@ import io.micrometer.tracing.SpanCustomizer; + import io.micrometer.tracing.Tracer.SpanInScope; + import io.micrometer.tracing.handler.PropagatingReceiverTracingObservationHandler; + import io.micrometer.tracing.handler.PropagatingSenderTracingObservationHandler; ++import io.micrometer.tracing.otel.bridge.BaggageTaggingSpanProcessor; + import io.micrometer.tracing.otel.bridge.EventListener; + import io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext; + import io.micrometer.tracing.otel.bridge.OtelPropagator; +@@ -40,18 +41,21 @@ import io.micrometer.tracing.otel.bridge.Slf4JBaggageEventListener; + import io.micrometer.tracing.otel.bridge.Slf4JEventListener; + import io.micrometer.tracing.otel.propagation.BaggageTextMapPropagator; + import io.micrometer.tracing.propagation.Propagator; ++import io.opentelemetry.api.baggage.Baggage; + import io.opentelemetry.api.common.AttributeKey; + import io.opentelemetry.api.common.Attributes; + import io.opentelemetry.api.metrics.MeterProvider; + import io.opentelemetry.api.trace.Span; + import io.opentelemetry.api.trace.Tracer; + import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; ++import io.opentelemetry.context.Scope; + import io.opentelemetry.context.propagation.ContextPropagators; + import io.opentelemetry.context.propagation.TextMapPropagator; + import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; + import io.opentelemetry.extension.trace.propagation.B3Propagator; + import io.opentelemetry.sdk.common.CompletableResultCode; + import io.opentelemetry.sdk.resources.Resource; ++import io.opentelemetry.sdk.trace.ReadableSpan; + import io.opentelemetry.sdk.trace.SdkTracerProvider; + import io.opentelemetry.sdk.trace.SpanLimits; + import io.opentelemetry.sdk.trace.SpanProcessor; +@@ -91,6 +95,7 @@ import static org.mockito.Mockito.mock; + * @author Moritz Halbritter + * @author Andy Wilkinson + * @author Yanming Zhou ++ * @author Oleksandr Shevchenko + */ + class OpenTelemetryTracingAutoConfigurationTests { + +@@ -390,6 +395,54 @@ class OpenTelemetryTracingAutoConfigurationTests { + }); + } + ++ @Test ++ void shouldSupplyBaggageTaggingSpanProcessorWhenTagFieldsAreConfigured() { ++ this.contextRunner.withPropertyValues("management.tracing.baggage.tag-fields=t1,t2").run((context) -> { ++ assertThat(context).hasSingleBean(BaggageTaggingSpanProcessor.class); ++ SpanProcessors spanProcessors = context.getBean(SpanProcessors.class); ++ assertThat(spanProcessors).anyMatch(BaggageTaggingSpanProcessor.class::isInstance); ++ }); ++ } ++ ++ @Test ++ void shouldNotSupplyBaggageTaggingSpanProcessorWhenTagFieldsAreNotConfigured() { ++ this.contextRunner.run((context) -> assertThat(context).doesNotHaveBean(BaggageTaggingSpanProcessor.class)); ++ } ++ ++ @Test ++ void shouldNotSupplyBaggageTaggingSpanProcessorWhenBaggageDisabled() { ++ this.contextRunner ++ .withPropertyValues("management.tracing.baggage.enabled=false", "management.tracing.baggage.tag-fields=t1") ++ .run((context) -> assertThat(context).doesNotHaveBean(BaggageTaggingSpanProcessor.class)); ++ } ++ ++ @Test ++ void shouldBackOffOnCustomBaggageTaggingSpanProcessor() { ++ this.contextRunner.withPropertyValues("management.tracing.baggage.tag-fields=t1") ++ .withUserConfiguration(CustomBaggageTaggingSpanProcessorConfiguration.class) ++ .run((context) -> { ++ assertThat(context).hasBean("customBaggageTaggingSpanProcessor"); ++ assertThat(context).hasSingleBean(BaggageTaggingSpanProcessor.class); ++ }); ++ } ++ ++ @Test ++ void baggageTaggingSpanProcessorShouldTagSpansWithBaggageFromParentContext() { ++ this.contextRunner ++ .withPropertyValues("management.tracing.baggage.tag-fields=t1", ++ "management.tracing.sampling.probability=1.0") ++ .run((context) -> { ++ Tracer tracer = context.getBean(Tracer.class); ++ try (Scope scope = Baggage.builder().put("t1", "v1").put("other", "v2").build().makeCurrent()) { ++ Span span = tracer.spanBuilder("test").startSpan(); ++ span.end(); ++ assertThat(span).isInstanceOf(ReadableSpan.class); ++ assertThat(((ReadableSpan) span).getAttribute(AttributeKey.stringKey("t1"))).isEqualTo("v1"); ++ assertThat(((ReadableSpan) span).getAttribute(AttributeKey.stringKey("other"))).isNull(); ++ } ++ }); ++ } ++ + @Test + void spanLimitsShouldBeConfiguredWithCustomProperties() { + this.contextRunner +@@ -608,6 +661,16 @@ class OpenTelemetryTracingAutoConfigurationTests { + + } + ++ @Configuration(proxyBeanMethods = false) ++ private static final class CustomBaggageTaggingSpanProcessorConfiguration { ++ ++ @Bean ++ BaggageTaggingSpanProcessor customBaggageTaggingSpanProcessor() { ++ return new BaggageTaggingSpanProcessor(List.of("custom")); ++ } ++ ++ } ++ + @Configuration(proxyBeanMethods = false) + private static final class AdditionalSpanProcessorConfiguration { + diff --git a/tasks/spring-projects__spring-boot-51656/tests/test.sh b/tasks/spring-projects__spring-boot-51656/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e1002f4a6472e64b9525e1e05b552479cbc3c1ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51656/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 924d10733e3c084ff0b7c97856d20d1259415ae8 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51656/tests/verifier.py b/tasks/spring-projects__spring-boot-51656/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51656/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51660/environment/Dockerfile b/tasks/spring-projects__spring-boot-51660/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ad05f98ed8dafed379634f8eeb67ea33fdc6cc5d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51660/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a7d90d353266b33e534eb382a903242486f7ecea 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a7d90d353266b33e534eb382a903242486f7ecea \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a7d90d353266b33e534eb382a903242486f7ecea \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51660/instruction.md b/tasks/spring-projects__spring-boot-51660/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c18df5842d756cbf17eed57262ea9a285f91a114 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51660/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Correct Jackson 3 Javadoc links + +## Description + +Reference + +https://docs.spring.io/spring-boot/4.2-SNAPSHOT/how-to/spring-mvc.html#howto.spring-mvc.customize-jackson-jsonmapper + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a7d90d353266`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51660/solution/patch.diff b/tasks/spring-projects__spring-boot-51660/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2897624798a649ba3a425978eb6946e75082dcf0 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51660/solution/patch.diff @@ -0,0 +1,21 @@ +diff --git a/platform/spring-boot-dependencies/build.gradle b/platform/spring-boot-dependencies/build.gradle +index c946625a295..165a62a5aa0 100644 +--- a/platform/spring-boot-dependencies/build.gradle ++++ b/platform/spring-boot-dependencies/build.gradle +@@ -726,13 +726,13 @@ bom { + javadoc("https://javadoc.io/doc/com.fasterxml.jackson.core/jackson-annotations/{version}", "com.fasterxml.jackson.annotation") + } + module("jackson-core") { +- javadoc("https://javadoc.io/doc/tools.jackson.core/jackson-core//{version}", "tools.jackson.core") ++ javadoc("https://javadoc.io/doc/tools.jackson.core/jackson-core/{version}/tools.jackson.core", "tools.jackson.core") + } + module("jackson-databind") { +- javadoc("https://javadoc.io/doc/tools.jackson.core/jackson-databind/{version}", "tools.jackson.databind") ++ javadoc("https://javadoc.io/doc/tools.jackson.core/jackson-databind/{version}/tools.jackson.databind", "tools.jackson.databind") + } + module("jackson-dataformat-xml") { +- javadoc("https://javadoc.io/doc/tools.jackson.dataformat/jackson-dataformat-xml//{version}", "tools.jackson.dataformat.xml") ++ javadoc("https://javadoc.io/doc/tools.jackson.dataformat/jackson-dataformat-xml/{version}/tools.jackson.dataformat.xml", "tools.jackson.dataformat.xml") + } + } + } diff --git a/tasks/spring-projects__spring-boot-51660/solution/solve.sh b/tasks/spring-projects__spring-boot-51660/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51660/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51660/task.toml b/tasks/spring-projects__spring-boot-51660/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1d8a533d3bb3187ad34024bc52add9c2b172c5e1 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51660/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51660" +description = "Correct Jackson 3 Javadoc links" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "a7d90d353266b33e534eb382a903242486f7ecea" +reference = "https://github.com/spring-projects/spring-boot/pull/51660" +source_access = "auto" +built_at = "2026-11-16T16:09:44.752593+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6f4ca6e3801a841fa2a909faf2f82de683da4a8bd8e91e7a7274f3c49e286881" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-11T07:19:13Z" +diff_format = "unified" +context_files = [ + "platform/spring-boot-dependencies/build.gradle", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 6 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.174409+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:33e680ec06307d0c1c93b380c0da9c17993e00f7e6bf1cb4aa8b8e7f7993bd05" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51660/tests/capture.py b/tasks/spring-projects__spring-boot-51660/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51660/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51660/tests/instruction.md b/tasks/spring-projects__spring-boot-51660/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c18df5842d756cbf17eed57262ea9a285f91a114 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51660/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** Correct Jackson 3 Javadoc links + +## Description + +Reference + +https://docs.spring.io/spring-boot/4.2-SNAPSHOT/how-to/spring-mvc.html#howto.spring-mvc.customize-jackson-jsonmapper + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a7d90d353266`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51660/tests/oracle.patch b/tasks/spring-projects__spring-boot-51660/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2897624798a649ba3a425978eb6946e75082dcf0 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51660/tests/oracle.patch @@ -0,0 +1,21 @@ +diff --git a/platform/spring-boot-dependencies/build.gradle b/platform/spring-boot-dependencies/build.gradle +index c946625a295..165a62a5aa0 100644 +--- a/platform/spring-boot-dependencies/build.gradle ++++ b/platform/spring-boot-dependencies/build.gradle +@@ -726,13 +726,13 @@ bom { + javadoc("https://javadoc.io/doc/com.fasterxml.jackson.core/jackson-annotations/{version}", "com.fasterxml.jackson.annotation") + } + module("jackson-core") { +- javadoc("https://javadoc.io/doc/tools.jackson.core/jackson-core//{version}", "tools.jackson.core") ++ javadoc("https://javadoc.io/doc/tools.jackson.core/jackson-core/{version}/tools.jackson.core", "tools.jackson.core") + } + module("jackson-databind") { +- javadoc("https://javadoc.io/doc/tools.jackson.core/jackson-databind/{version}", "tools.jackson.databind") ++ javadoc("https://javadoc.io/doc/tools.jackson.core/jackson-databind/{version}/tools.jackson.databind", "tools.jackson.databind") + } + module("jackson-dataformat-xml") { +- javadoc("https://javadoc.io/doc/tools.jackson.dataformat/jackson-dataformat-xml//{version}", "tools.jackson.dataformat.xml") ++ javadoc("https://javadoc.io/doc/tools.jackson.dataformat/jackson-dataformat-xml/{version}/tools.jackson.dataformat.xml", "tools.jackson.dataformat.xml") + } + } + } diff --git a/tasks/spring-projects__spring-boot-51660/tests/test.sh b/tasks/spring-projects__spring-boot-51660/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..282365ff9ed07aa689741eb6e90d70b35e89fdf2 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51660/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a7d90d353266b33e534eb382a903242486f7ecea > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51660/tests/verifier.py b/tasks/spring-projects__spring-boot-51660/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51660/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51661/environment/Dockerfile b/tasks/spring-projects__spring-boot-51661/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dcff207cfcb2faf2e709da2e906fb4fd4842a504 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51661/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 042c69a4f9c7e7bfb7be14dff6a5dd5af5ff3e72 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 042c69a4f9c7e7bfb7be14dff6a5dd5af5ff3e72 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 042c69a4f9c7e7bfb7be14dff6a5dd5af5ff3e72 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51661/instruction.md b/tasks/spring-projects__spring-boot-51661/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f29b478bffb0bb97aaef74a1297d705723ffc404 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51661/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Resolve property placeholders in constructor binding default values + +## Description + +Resolve property placeholders in `@DefaultValue` before converting constructor arguments, following the team decision in + +For example, with `defaults.duration=3d`, a constructor parameter annotated with `@DefaultValue("${defaults.duration:1d}")` now receives `Duration.ofDays(3)` when no explicit value is configured for that parameter. Without `defaults.duration`, it receives `Duration.ofDays(1)`. + +The change uses the Binder's existing `PlaceholdersResolver` for each default value and `String.valueOf` to return the resolved values as a `String[]`, consistently with `PropertySourcesPlaceholdersResolver`. Explicit property values still take precedence; empty `@DefaultValue` handling and ordinary field initializers are unchanged. Update the annotation's Javadoc accordingly. + +Verification (Java 25): + +- Added real application-context tests using `@EnableConfigurationProperties`, checking the constructed bean's string, Duration, primitive-array and collection values. The initial reproduction failed before the production change (2 failing default-value cases, with the explicit-override control passing). +- The application-context tests pass with the fix, including placeholder fallback values and explicit overrides. +- Added Binder tests for no resolver, unresolved placeholders, and a custom resolver returning a non-string value. +- Ran all core tests matching `*context.properties.*` and `*boot.convert.*`: 1,220 tests, 0 failures/errors, 1 skipped. +- `:core:spring-boot:checkstyleMain`, `checkstyleTest`, `checkFormatMain`, and `checkFormatTest` passed. + +This targets `main`, not a maintenance branch: resolving placeholders in defaults is an intentional behavior change for applications that previously received the literal placeholder. This does not change default-value collection conversion rules or resolve placeholders in ordinary field initializers. The entire repository test suite was not run. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `042c69a4f9c7`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51661/solution/patch.diff b/tasks/spring-projects__spring-boot-51661/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8e2bcfdb114638c98df900b588df35a773eec03c --- /dev/null +++ b/tasks/spring-projects__spring-boot-51661/solution/patch.diff @@ -0,0 +1,213 @@ +diff --git a/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DefaultValue.java b/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DefaultValue.java +index 238406cddf8..49f0618324b 100644 +--- a/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DefaultValue.java ++++ b/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DefaultValue.java +@@ -33,11 +33,12 @@ import java.lang.annotation.Target; + * the default value for the property will not be used even if the property value is + * empty. + * <p> +- * NOTE: This annotation does not support property placeholder resolution and the value +- * must be constant. ++ * Property placeholders in the default value are resolved using the {@link Binder}'s ++ * {@link PlaceholdersResolver} before the value is converted to the property's type. + * + * @author Madhura Bhave + * @author Pavel Anisimov ++ * @author Wan bin yu + * @since 2.2.0 + */ + @Retention(RetentionPolicy.RUNTIME) +diff --git a/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java b/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java +index 9bdab548996..a1e4c92694a 100644 +--- a/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java ++++ b/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java +@@ -62,6 +62,7 @@ import org.springframework.util.Assert; + * @author Phillip Webb + * @author Scott Frederick + * @author Ondřej Světlík ++ * @author Wan bin yu + */ + class ValueObjectBinder implements DataObjectBinder { + +@@ -135,12 +136,22 @@ class ValueObjectBinder implements DataObjectBinder { + if (defaultValue.length == 0) { + return getNewDefaultValueInstanceIfPossible(context, type); + } +- return convertDefaultValue(context.getConverter(), defaultValue, type, annotations); ++ return convertDefaultValue(context.getConverter(), ++ resolveDefaultValue(context.getPlaceholdersResolver(), defaultValue), type, annotations); + } + } + return context.getConverter().convert(null, type); + } + ++ private String[] resolveDefaultValue(PlaceholdersResolver resolver, String[] defaultValue) { ++ String[] resolved = new String[defaultValue.length]; ++ for (int i = 0; i < defaultValue.length; i++) { ++ Object value = resolver.resolvePlaceholders(defaultValue[i]); ++ resolved[i] = String.valueOf(value); ++ } ++ return resolved; ++ } ++ + private <T> @Nullable T convertDefaultValue(BindConverter converter, String[] defaultValue, ResolvableType type, + Annotation[] annotations) { + try { +diff --git a/core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java b/core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java +index 9dfb957b7cf..1d8b533ff63 100644 +--- a/core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java ++++ b/core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java +@@ -132,6 +132,7 @@ import static org.mockito.Mockito.mock; + * @author Stephane Nicoll + * @author Madhura Bhave + * @author Vladislav Kisel ++ * @author Wan bin yu + */ + @ExtendWith(OutputCaptureExtension.class) + class ConfigurationPropertiesTests { +@@ -1016,6 +1017,38 @@ class ConfigurationPropertiesTests { + assertThat(bean.getOptional()).isEmpty(); + } + ++ @Test ++ void loadWhenDefaultValuesContainPlaceholdersShouldResolveAndConvert() { ++ load(PlaceholderDefaultsConfiguration.class, "defaults.name=resolved", "defaults.duration=3d", ++ "defaults.count=7"); ++ PlaceholderDefaultsProperties bean = this.context.getBean(PlaceholderDefaultsProperties.class); ++ assertThat(bean.name).isEqualTo("resolved/suffix"); ++ assertThat(bean.duration).isEqualTo(Duration.ofDays(3)); ++ assertThat(bean.counts).containsExactly(7, 2); ++ assertThat(bean.names).containsExactly("resolved", "fallback"); ++ } ++ ++ @Test ++ void loadWhenDefaultValuesContainPlaceholdersShouldUsePlaceholderDefaults() { ++ load(PlaceholderDefaultsConfiguration.class); ++ PlaceholderDefaultsProperties bean = this.context.getBean(PlaceholderDefaultsProperties.class); ++ assertThat(bean.name).isEqualTo("default/suffix"); ++ assertThat(bean.duration).isEqualTo(Duration.ofDays(1)); ++ assertThat(bean.counts).containsExactly(1, 2); ++ assertThat(bean.names).containsExactly("default", "fallback"); ++ } ++ ++ @Test ++ void loadWhenExplicitValuesOverridePlaceholderDefaultsShouldUseExplicitValues() { ++ load(PlaceholderDefaultsConfiguration.class, "test.name=explicit", "test.duration=5d", "test.counts=8,9", ++ "test.names=one,two"); ++ PlaceholderDefaultsProperties bean = this.context.getBean(PlaceholderDefaultsProperties.class); ++ assertThat(bean.name).isEqualTo("explicit"); ++ assertThat(bean.duration).isEqualTo(Duration.ofDays(5)); ++ assertThat(bean.counts).containsExactly(8, 9); ++ assertThat(bean.names).containsExactly("one", "two"); ++ } ++ + @Test + void loadWhenBindingToConstructorParametersWithDefaultDataUnitShouldBind() { + load(ConstructorParameterWithUnitConfiguration.class); +@@ -2467,6 +2500,35 @@ class ConfigurationPropertiesTests { + + } + ++ @Configuration(proxyBeanMethods = false) ++ @EnableConfigurationProperties(PlaceholderDefaultsProperties.class) ++ static class PlaceholderDefaultsConfiguration { ++ ++ } ++ ++ @ConfigurationProperties("test") ++ static class PlaceholderDefaultsProperties { ++ ++ private final String name; ++ ++ private final Duration duration; ++ ++ private final int[] counts; ++ ++ private final List<String> names; ++ ++ PlaceholderDefaultsProperties(@DefaultValue("${defaults.name:default}/suffix") String name, ++ @DefaultValue("${defaults.duration:1d}") Duration duration, ++ @DefaultValue({ "${defaults.count:1}", "2" }) int[] counts, ++ @DefaultValue({ "${defaults.name:default}", "${defaults.other:fallback}" }) List<String> names) { ++ this.name = name; ++ this.duration = duration; ++ this.counts = counts; ++ this.names = names; ++ } ++ ++ } ++ + @ConfigurationProperties("test") + static class ConstructorParameterEmptyDefaultValueProperties { + +diff --git a/core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java b/core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java +index 5295b778571..9fad957a9e4 100644 +--- a/core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java ++++ b/core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java +@@ -21,6 +21,7 @@ import java.nio.file.Path; + import java.nio.file.Paths; + import java.time.LocalDate; + import java.util.ArrayList; ++import java.util.Collections; + import java.util.EnumMap; + import java.util.List; + import java.util.Map; +@@ -52,6 +53,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + * @author Pavel Anisimov + * @author Yanming Zhou + * @author Ondřej Světlík ++ * @author Wan bin yu + */ + class ValueObjectBinderTests { + +@@ -307,6 +309,26 @@ class ValueObjectBinderTests { + assertThat(bean.getDate()).hasToString("2019-05-10"); + } + ++ @Test ++ void createWithDefaultValuePlaceholderAndNoResolverShouldRetainPlaceholder() { ++ PlaceholderDefaultValue bean = this.binder.bindOrCreate("foo", PlaceholderDefaultValue.class); ++ assertThat(bean.value()).isEqualTo("${value}"); ++ } ++ ++ @Test ++ void createWithUnresolvedDefaultValuePlaceholderShouldRetainPlaceholder() { ++ Binder binder = new Binder(this.sources, new PropertySourcesPlaceholdersResolver(Collections.emptyList())); ++ PlaceholderDefaultValue bean = binder.bindOrCreate("foo", PlaceholderDefaultValue.class); ++ assertThat(bean.value()).isEqualTo("${value}"); ++ } ++ ++ @Test ++ void createWithDefaultValuePlaceholderResolvingToNonStringShouldConvert() { ++ Binder binder = new Binder(this.sources, (value) -> 42); ++ PlaceholderDefaultValue bean = binder.bindOrCreate("foo", PlaceholderDefaultValue.class); ++ assertThat(bean.value()).isEqualTo("42"); ++ } ++ + @Test + void bindWhenAllPropertiesBoundShouldClearConfigurationProperty() { // gh-18704 + MockConfigurationPropertySource source = new MockConfigurationPropertySource(); +@@ -639,6 +661,10 @@ class ValueObjectBinderTests { + + } + ++ record PlaceholderDefaultValue(@DefaultValue("${value}") String value) { ++ ++ } ++ + static class ExampleDefaultValueBean { + + private final int intValue; +diff --git a/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc b/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc +index 1f3ab5cec2d..7884401d8fb 100644 +--- a/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc ++++ b/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc +@@ -884,7 +884,7 @@ TIP: To use a reserved keyword in the name of a property, such as `my.service.im + ==== @DefaultValue and Binding + + Default values can be specified using javadoc:org.springframework.boot.context.properties.bind.DefaultValue[format=annotation] on constructor parameters and record components. +-The conversion service will be applied to coerce the annotation's javadoc:java.lang.String[] value to the target type of a missing property. ++Property placeholders in the annotation's javadoc:java.lang.String[] value are replaced and the conversion service is applied to coerce it to the target type of a missing property. + + In the `MyProperties` example above, you can see the nested `Security` class uses `@DefaultValue("USER")` for the `roles` parameter. + This means that if `security` properties are defined, but `roles` is not, the default of `"USER"` will be bound. diff --git a/tasks/spring-projects__spring-boot-51661/solution/solve.sh b/tasks/spring-projects__spring-boot-51661/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51661/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51661/task.toml b/tasks/spring-projects__spring-boot-51661/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..07f6a0e433b252baa9cbf092f568b0244ad260a5 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51661/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51661" +description = "Resolve property placeholders in constructor binding default values" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "042c69a4f9c7e7bfb7be14dff6a5dd5af5ff3e72" +reference = "https://github.com/spring-projects/spring-boot/pull/51661" +source_access = "auto" +built_at = "2026-11-16T16:09:44.748449+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a8587b0798cfeb3d2cf477b01bd74eb47b351cb7939de33c8d2b3ba48e57c5f8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-11T16:31:11Z" +diff_format = "unified" +context_files = [ + "core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DefaultValue.java", + "core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java", + "core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java", + "core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java", + "documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 108 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.174977+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:12774f1eda903409d7858e526c481f6dbffac864b2f4d0237e212361b716d305" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51661/tests/capture.py b/tasks/spring-projects__spring-boot-51661/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51661/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51661/tests/instruction.md b/tasks/spring-projects__spring-boot-51661/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f29b478bffb0bb97aaef74a1297d705723ffc404 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51661/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Resolve property placeholders in constructor binding default values + +## Description + +Resolve property placeholders in `@DefaultValue` before converting constructor arguments, following the team decision in + +For example, with `defaults.duration=3d`, a constructor parameter annotated with `@DefaultValue("${defaults.duration:1d}")` now receives `Duration.ofDays(3)` when no explicit value is configured for that parameter. Without `defaults.duration`, it receives `Duration.ofDays(1)`. + +The change uses the Binder's existing `PlaceholdersResolver` for each default value and `String.valueOf` to return the resolved values as a `String[]`, consistently with `PropertySourcesPlaceholdersResolver`. Explicit property values still take precedence; empty `@DefaultValue` handling and ordinary field initializers are unchanged. Update the annotation's Javadoc accordingly. + +Verification (Java 25): + +- Added real application-context tests using `@EnableConfigurationProperties`, checking the constructed bean's string, Duration, primitive-array and collection values. The initial reproduction failed before the production change (2 failing default-value cases, with the explicit-override control passing). +- The application-context tests pass with the fix, including placeholder fallback values and explicit overrides. +- Added Binder tests for no resolver, unresolved placeholders, and a custom resolver returning a non-string value. +- Ran all core tests matching `*context.properties.*` and `*boot.convert.*`: 1,220 tests, 0 failures/errors, 1 skipped. +- `:core:spring-boot:checkstyleMain`, `checkstyleTest`, `checkFormatMain`, and `checkFormatTest` passed. + +This targets `main`, not a maintenance branch: resolving placeholders in defaults is an intentional behavior change for applications that previously received the literal placeholder. This does not change default-value collection conversion rules or resolve placeholders in ordinary field initializers. The entire repository test suite was not run. + +. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `042c69a4f9c7`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51661/tests/oracle.patch b/tasks/spring-projects__spring-boot-51661/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8e2bcfdb114638c98df900b588df35a773eec03c --- /dev/null +++ b/tasks/spring-projects__spring-boot-51661/tests/oracle.patch @@ -0,0 +1,213 @@ +diff --git a/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DefaultValue.java b/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DefaultValue.java +index 238406cddf8..49f0618324b 100644 +--- a/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DefaultValue.java ++++ b/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/DefaultValue.java +@@ -33,11 +33,12 @@ import java.lang.annotation.Target; + * the default value for the property will not be used even if the property value is + * empty. + * <p> +- * NOTE: This annotation does not support property placeholder resolution and the value +- * must be constant. ++ * Property placeholders in the default value are resolved using the {@link Binder}'s ++ * {@link PlaceholdersResolver} before the value is converted to the property's type. + * + * @author Madhura Bhave + * @author Pavel Anisimov ++ * @author Wan bin yu + * @since 2.2.0 + */ + @Retention(RetentionPolicy.RUNTIME) +diff --git a/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java b/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java +index 9bdab548996..a1e4c92694a 100644 +--- a/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java ++++ b/core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java +@@ -62,6 +62,7 @@ import org.springframework.util.Assert; + * @author Phillip Webb + * @author Scott Frederick + * @author Ondřej Světlík ++ * @author Wan bin yu + */ + class ValueObjectBinder implements DataObjectBinder { + +@@ -135,12 +136,22 @@ class ValueObjectBinder implements DataObjectBinder { + if (defaultValue.length == 0) { + return getNewDefaultValueInstanceIfPossible(context, type); + } +- return convertDefaultValue(context.getConverter(), defaultValue, type, annotations); ++ return convertDefaultValue(context.getConverter(), ++ resolveDefaultValue(context.getPlaceholdersResolver(), defaultValue), type, annotations); + } + } + return context.getConverter().convert(null, type); + } + ++ private String[] resolveDefaultValue(PlaceholdersResolver resolver, String[] defaultValue) { ++ String[] resolved = new String[defaultValue.length]; ++ for (int i = 0; i < defaultValue.length; i++) { ++ Object value = resolver.resolvePlaceholders(defaultValue[i]); ++ resolved[i] = String.valueOf(value); ++ } ++ return resolved; ++ } ++ + private <T> @Nullable T convertDefaultValue(BindConverter converter, String[] defaultValue, ResolvableType type, + Annotation[] annotations) { + try { +diff --git a/core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java b/core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java +index 9dfb957b7cf..1d8b533ff63 100644 +--- a/core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java ++++ b/core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java +@@ -132,6 +132,7 @@ import static org.mockito.Mockito.mock; + * @author Stephane Nicoll + * @author Madhura Bhave + * @author Vladislav Kisel ++ * @author Wan bin yu + */ + @ExtendWith(OutputCaptureExtension.class) + class ConfigurationPropertiesTests { +@@ -1016,6 +1017,38 @@ class ConfigurationPropertiesTests { + assertThat(bean.getOptional()).isEmpty(); + } + ++ @Test ++ void loadWhenDefaultValuesContainPlaceholdersShouldResolveAndConvert() { ++ load(PlaceholderDefaultsConfiguration.class, "defaults.name=resolved", "defaults.duration=3d", ++ "defaults.count=7"); ++ PlaceholderDefaultsProperties bean = this.context.getBean(PlaceholderDefaultsProperties.class); ++ assertThat(bean.name).isEqualTo("resolved/suffix"); ++ assertThat(bean.duration).isEqualTo(Duration.ofDays(3)); ++ assertThat(bean.counts).containsExactly(7, 2); ++ assertThat(bean.names).containsExactly("resolved", "fallback"); ++ } ++ ++ @Test ++ void loadWhenDefaultValuesContainPlaceholdersShouldUsePlaceholderDefaults() { ++ load(PlaceholderDefaultsConfiguration.class); ++ PlaceholderDefaultsProperties bean = this.context.getBean(PlaceholderDefaultsProperties.class); ++ assertThat(bean.name).isEqualTo("default/suffix"); ++ assertThat(bean.duration).isEqualTo(Duration.ofDays(1)); ++ assertThat(bean.counts).containsExactly(1, 2); ++ assertThat(bean.names).containsExactly("default", "fallback"); ++ } ++ ++ @Test ++ void loadWhenExplicitValuesOverridePlaceholderDefaultsShouldUseExplicitValues() { ++ load(PlaceholderDefaultsConfiguration.class, "test.name=explicit", "test.duration=5d", "test.counts=8,9", ++ "test.names=one,two"); ++ PlaceholderDefaultsProperties bean = this.context.getBean(PlaceholderDefaultsProperties.class); ++ assertThat(bean.name).isEqualTo("explicit"); ++ assertThat(bean.duration).isEqualTo(Duration.ofDays(5)); ++ assertThat(bean.counts).containsExactly(8, 9); ++ assertThat(bean.names).containsExactly("one", "two"); ++ } ++ + @Test + void loadWhenBindingToConstructorParametersWithDefaultDataUnitShouldBind() { + load(ConstructorParameterWithUnitConfiguration.class); +@@ -2467,6 +2500,35 @@ class ConfigurationPropertiesTests { + + } + ++ @Configuration(proxyBeanMethods = false) ++ @EnableConfigurationProperties(PlaceholderDefaultsProperties.class) ++ static class PlaceholderDefaultsConfiguration { ++ ++ } ++ ++ @ConfigurationProperties("test") ++ static class PlaceholderDefaultsProperties { ++ ++ private final String name; ++ ++ private final Duration duration; ++ ++ private final int[] counts; ++ ++ private final List<String> names; ++ ++ PlaceholderDefaultsProperties(@DefaultValue("${defaults.name:default}/suffix") String name, ++ @DefaultValue("${defaults.duration:1d}") Duration duration, ++ @DefaultValue({ "${defaults.count:1}", "2" }) int[] counts, ++ @DefaultValue({ "${defaults.name:default}", "${defaults.other:fallback}" }) List<String> names) { ++ this.name = name; ++ this.duration = duration; ++ this.counts = counts; ++ this.names = names; ++ } ++ ++ } ++ + @ConfigurationProperties("test") + static class ConstructorParameterEmptyDefaultValueProperties { + +diff --git a/core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java b/core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java +index 5295b778571..9fad957a9e4 100644 +--- a/core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java ++++ b/core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java +@@ -21,6 +21,7 @@ import java.nio.file.Path; + import java.nio.file.Paths; + import java.time.LocalDate; + import java.util.ArrayList; ++import java.util.Collections; + import java.util.EnumMap; + import java.util.List; + import java.util.Map; +@@ -52,6 +53,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + * @author Pavel Anisimov + * @author Yanming Zhou + * @author Ondřej Světlík ++ * @author Wan bin yu + */ + class ValueObjectBinderTests { + +@@ -307,6 +309,26 @@ class ValueObjectBinderTests { + assertThat(bean.getDate()).hasToString("2019-05-10"); + } + ++ @Test ++ void createWithDefaultValuePlaceholderAndNoResolverShouldRetainPlaceholder() { ++ PlaceholderDefaultValue bean = this.binder.bindOrCreate("foo", PlaceholderDefaultValue.class); ++ assertThat(bean.value()).isEqualTo("${value}"); ++ } ++ ++ @Test ++ void createWithUnresolvedDefaultValuePlaceholderShouldRetainPlaceholder() { ++ Binder binder = new Binder(this.sources, new PropertySourcesPlaceholdersResolver(Collections.emptyList())); ++ PlaceholderDefaultValue bean = binder.bindOrCreate("foo", PlaceholderDefaultValue.class); ++ assertThat(bean.value()).isEqualTo("${value}"); ++ } ++ ++ @Test ++ void createWithDefaultValuePlaceholderResolvingToNonStringShouldConvert() { ++ Binder binder = new Binder(this.sources, (value) -> 42); ++ PlaceholderDefaultValue bean = binder.bindOrCreate("foo", PlaceholderDefaultValue.class); ++ assertThat(bean.value()).isEqualTo("42"); ++ } ++ + @Test + void bindWhenAllPropertiesBoundShouldClearConfigurationProperty() { // gh-18704 + MockConfigurationPropertySource source = new MockConfigurationPropertySource(); +@@ -639,6 +661,10 @@ class ValueObjectBinderTests { + + } + ++ record PlaceholderDefaultValue(@DefaultValue("${value}") String value) { ++ ++ } ++ + static class ExampleDefaultValueBean { + + private final int intValue; +diff --git a/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc b/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc +index 1f3ab5cec2d..7884401d8fb 100644 +--- a/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc ++++ b/documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc +@@ -884,7 +884,7 @@ TIP: To use a reserved keyword in the name of a property, such as `my.service.im + ==== @DefaultValue and Binding + + Default values can be specified using javadoc:org.springframework.boot.context.properties.bind.DefaultValue[format=annotation] on constructor parameters and record components. +-The conversion service will be applied to coerce the annotation's javadoc:java.lang.String[] value to the target type of a missing property. ++Property placeholders in the annotation's javadoc:java.lang.String[] value are replaced and the conversion service is applied to coerce it to the target type of a missing property. + + In the `MyProperties` example above, you can see the nested `Security` class uses `@DefaultValue("USER")` for the `roles` parameter. + This means that if `security` properties are defined, but `roles` is not, the default of `"USER"` will be bound. diff --git a/tasks/spring-projects__spring-boot-51661/tests/test.sh b/tasks/spring-projects__spring-boot-51661/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ef21c3b4f2198bcef19afa97109e55efdb534045 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51661/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 042c69a4f9c7e7bfb7be14dff6a5dd5af5ff3e72 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51661/tests/verifier.py b/tasks/spring-projects__spring-boot-51661/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51661/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51666/environment/Dockerfile b/tasks/spring-projects__spring-boot-51666/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..01b300b0ff592a4b3c31db33afd05b67fffd0759 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51666/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 5541ab2424137e775097d1c7286e011da7dcb3ab 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 5541ab2424137e775097d1c7286e011da7dcb3ab \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 5541ab2424137e775097d1c7286e011da7dcb3ab \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51666/instruction.md b/tasks/spring-projects__spring-boot-51666/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8b1bc6361374fdf27b409b2794e3ee0dfad3e0a4 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51666/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** Connection fails when rabbitmq Docker Compose service is configured to use SSL + +## Description + +When a `rabbitmq` Docker Compose service is labelled with `org.springframework.boot.sslbundle.*`, `RabbitDockerComposeConnectionDetailsFactory` creates an `SslBundle` but still + resolves the address from container port 5672, the plain AMQP listener. `RabbitConnectionFactoryBeanConfigurer` enables SSL on the connection factory when an `SslBundle` is + present, so the client attempts a TLS handshake against the non-TLS listener and the connection fails with: + + javax.net.ssl.SSLException: Unsupported or unrecognized SSL message + + This PR resolves the address from container port 5671 (AMQPS) when an `SslBundle` is present, matching what `RabbitStreamDockerComposeConnectionDetailsFactory` does with + `STREAMS_TLS_PORT` and what the Testcontainers-based `RabbitContainerConnectionDetailsFactory` does by switching to `getAmqpsUrl()`. + + The existing `runWithSslCreatesConnectionDetails` integration test only asserted that the port was greater than zero, so it passed with either port. It now also opens a real + connection using the resolved address and the `SslBundle`. The test fails on the current code with the exception above and passes with this change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5541ab242413`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51666/solution/patch.diff b/tasks/spring-projects__spring-boot-51666/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..08d8e00724736d9680fa0a2c66dafcf04d5cd496 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51666/solution/patch.diff @@ -0,0 +1,87 @@ +diff --git a/module/spring-boot-amqp/src/dockerTest/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactoryIntegrationTests.java b/module/spring-boot-amqp/src/dockerTest/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactoryIntegrationTests.java +index cab917ea4c5..ed8f07ea4ad 100644 +--- a/module/spring-boot-amqp/src/dockerTest/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactoryIntegrationTests.java ++++ b/module/spring-boot-amqp/src/dockerTest/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactoryIntegrationTests.java +@@ -16,6 +16,9 @@ + + package org.springframework.boot.amqp.docker.compose; + ++import com.rabbitmq.client.Connection; ++import com.rabbitmq.client.ConnectionFactory; ++ + import org.springframework.boot.amqp.autoconfigure.RabbitConnectionDetails; + import org.springframework.boot.amqp.autoconfigure.RabbitConnectionDetails.Address; + import org.springframework.boot.docker.compose.service.connection.test.DockerComposeTest; +@@ -35,20 +38,19 @@ import static org.assertj.core.api.Assertions.assertThat; + class RabbitDockerComposeConnectionDetailsFactoryIntegrationTests { + + @DockerComposeTest(composeFile = "rabbit-compose.yaml", image = TestImage.RABBITMQ) +- void runCreatesConnectionDetails(RabbitConnectionDetails connectionDetails) { ++ void runCreatesConnectionDetails(RabbitConnectionDetails connectionDetails) throws Exception { + assertConnectionDetails(connectionDetails); + assertThat(connectionDetails.getSslBundle()).isNull(); + } + + @DockerComposeTest(composeFile = "rabbit-ssl-compose.yaml", image = TestImage.RABBITMQ, + additionalResources = { "ca.crt", "server.crt", "server.key", "client.crt", "client.key", "rabbitmq.conf" }) +- void runWithSslCreatesConnectionDetails(RabbitConnectionDetails connectionDetails) { ++ void runWithSslCreatesConnectionDetails(RabbitConnectionDetails connectionDetails) throws Exception { + assertConnectionDetails(connectionDetails); +- SslBundle sslBundle = connectionDetails.getSslBundle(); +- assertThat(sslBundle).isNotNull(); ++ assertThat(connectionDetails.getSslBundle()).isNotNull(); + } + +- private void assertConnectionDetails(RabbitConnectionDetails connectionDetails) { ++ private void assertConnectionDetails(RabbitConnectionDetails connectionDetails) throws Exception { + assertThat(connectionDetails.getUsername()).isEqualTo("myuser"); + assertThat(connectionDetails.getPassword()).isEqualTo("secret"); + assertThat(connectionDetails.getVirtualHost()).isEqualTo("/"); +@@ -56,6 +58,24 @@ class RabbitDockerComposeConnectionDetailsFactoryIntegrationTests { + Address address = connectionDetails.getFirstAddress(); + assertThat(address.host()).isNotNull(); + assertThat(address.port()).isGreaterThan(0); ++ assertThatConnectionCanBeMade(connectionDetails); ++ } ++ ++ private void assertThatConnectionCanBeMade(RabbitConnectionDetails connectionDetails) throws Exception { ++ ConnectionFactory connectionFactory = new ConnectionFactory(); ++ Address address = connectionDetails.getFirstAddress(); ++ connectionFactory.setHost(address.host()); ++ connectionFactory.setPort(address.port()); ++ connectionFactory.setUsername(connectionDetails.getUsername()); ++ connectionFactory.setPassword(connectionDetails.getPassword()); ++ connectionFactory.setVirtualHost(connectionDetails.getVirtualHost()); ++ SslBundle sslBundle = connectionDetails.getSslBundle(); ++ if (sslBundle != null) { ++ connectionFactory.useSslProtocol(sslBundle.createSslContext()); ++ } ++ try (Connection connection = connectionFactory.newConnection()) { ++ assertThat(connection.isOpen()).isTrue(); ++ } + } + + } +diff --git a/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactory.java b/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactory.java +index a601ab093c3..31b1cfdc35e 100644 +--- a/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactory.java ++++ b/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactory.java +@@ -40,6 +40,8 @@ class RabbitDockerComposeConnectionDetailsFactory + + private static final int RABBITMQ_PORT = 5672; + ++ private static final int RABBITMQ_TLS_PORT = 5671; ++ + protected RabbitDockerComposeConnectionDetailsFactory() { + super("rabbitmq"); + } +@@ -66,7 +68,8 @@ class RabbitDockerComposeConnectionDetailsFactory + super(service); + this.environment = new RabbitEnvironment(service.env()); + this.sslBundle = getSslBundle(service); +- this.addresses = List.of(new Address(service.host(), service.ports().get(RABBITMQ_PORT))); ++ int containerPort = (this.sslBundle != null) ? RABBITMQ_TLS_PORT : RABBITMQ_PORT; ++ this.addresses = List.of(new Address(service.host(), service.ports().get(containerPort))); + } + + @Override diff --git a/tasks/spring-projects__spring-boot-51666/solution/solve.sh b/tasks/spring-projects__spring-boot-51666/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51666/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51666/task.toml b/tasks/spring-projects__spring-boot-51666/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fb51b260393798f0a005b3954aa0e554b81a5634 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51666/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51666" +description = "Connection fails when rabbitmq Docker Compose service is configured to use SSL" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "5541ab2424137e775097d1c7286e011da7dcb3ab" +reference = "https://github.com/spring-projects/spring-boot/pull/51666" +source_access = "auto" +built_at = "2026-11-16T16:09:44.750880+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:03fc0393c5cff642ef48521ff4a3924c0f564e39abc487dfd25354b53a955e51" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-11T13:22:50Z" +diff_format = "unified" +context_files = [ + "module/spring-boot-amqp/src/dockerTest/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactoryIntegrationTests.java", + "module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactory.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 35 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.175550+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:09a721701b387d383bc42b136a05c1bd6adc180710c7c2a322a0a8e0474eec6a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51666/tests/capture.py b/tasks/spring-projects__spring-boot-51666/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51666/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51666/tests/instruction.md b/tasks/spring-projects__spring-boot-51666/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8b1bc6361374fdf27b409b2794e3ee0dfad3e0a4 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51666/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** Connection fails when rabbitmq Docker Compose service is configured to use SSL + +## Description + +When a `rabbitmq` Docker Compose service is labelled with `org.springframework.boot.sslbundle.*`, `RabbitDockerComposeConnectionDetailsFactory` creates an `SslBundle` but still + resolves the address from container port 5672, the plain AMQP listener. `RabbitConnectionFactoryBeanConfigurer` enables SSL on the connection factory when an `SslBundle` is + present, so the client attempts a TLS handshake against the non-TLS listener and the connection fails with: + + javax.net.ssl.SSLException: Unsupported or unrecognized SSL message + + This PR resolves the address from container port 5671 (AMQPS) when an `SslBundle` is present, matching what `RabbitStreamDockerComposeConnectionDetailsFactory` does with + `STREAMS_TLS_PORT` and what the Testcontainers-based `RabbitContainerConnectionDetailsFactory` does by switching to `getAmqpsUrl()`. + + The existing `runWithSslCreatesConnectionDetails` integration test only asserted that the port was greater than zero, so it passed with either port. It now also opens a real + connection using the resolved address and the `SslBundle`. The test fails on the current code with the exception above and passes with this change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5541ab242413`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51666/tests/oracle.patch b/tasks/spring-projects__spring-boot-51666/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..08d8e00724736d9680fa0a2c66dafcf04d5cd496 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51666/tests/oracle.patch @@ -0,0 +1,87 @@ +diff --git a/module/spring-boot-amqp/src/dockerTest/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactoryIntegrationTests.java b/module/spring-boot-amqp/src/dockerTest/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactoryIntegrationTests.java +index cab917ea4c5..ed8f07ea4ad 100644 +--- a/module/spring-boot-amqp/src/dockerTest/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactoryIntegrationTests.java ++++ b/module/spring-boot-amqp/src/dockerTest/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactoryIntegrationTests.java +@@ -16,6 +16,9 @@ + + package org.springframework.boot.amqp.docker.compose; + ++import com.rabbitmq.client.Connection; ++import com.rabbitmq.client.ConnectionFactory; ++ + import org.springframework.boot.amqp.autoconfigure.RabbitConnectionDetails; + import org.springframework.boot.amqp.autoconfigure.RabbitConnectionDetails.Address; + import org.springframework.boot.docker.compose.service.connection.test.DockerComposeTest; +@@ -35,20 +38,19 @@ import static org.assertj.core.api.Assertions.assertThat; + class RabbitDockerComposeConnectionDetailsFactoryIntegrationTests { + + @DockerComposeTest(composeFile = "rabbit-compose.yaml", image = TestImage.RABBITMQ) +- void runCreatesConnectionDetails(RabbitConnectionDetails connectionDetails) { ++ void runCreatesConnectionDetails(RabbitConnectionDetails connectionDetails) throws Exception { + assertConnectionDetails(connectionDetails); + assertThat(connectionDetails.getSslBundle()).isNull(); + } + + @DockerComposeTest(composeFile = "rabbit-ssl-compose.yaml", image = TestImage.RABBITMQ, + additionalResources = { "ca.crt", "server.crt", "server.key", "client.crt", "client.key", "rabbitmq.conf" }) +- void runWithSslCreatesConnectionDetails(RabbitConnectionDetails connectionDetails) { ++ void runWithSslCreatesConnectionDetails(RabbitConnectionDetails connectionDetails) throws Exception { + assertConnectionDetails(connectionDetails); +- SslBundle sslBundle = connectionDetails.getSslBundle(); +- assertThat(sslBundle).isNotNull(); ++ assertThat(connectionDetails.getSslBundle()).isNotNull(); + } + +- private void assertConnectionDetails(RabbitConnectionDetails connectionDetails) { ++ private void assertConnectionDetails(RabbitConnectionDetails connectionDetails) throws Exception { + assertThat(connectionDetails.getUsername()).isEqualTo("myuser"); + assertThat(connectionDetails.getPassword()).isEqualTo("secret"); + assertThat(connectionDetails.getVirtualHost()).isEqualTo("/"); +@@ -56,6 +58,24 @@ class RabbitDockerComposeConnectionDetailsFactoryIntegrationTests { + Address address = connectionDetails.getFirstAddress(); + assertThat(address.host()).isNotNull(); + assertThat(address.port()).isGreaterThan(0); ++ assertThatConnectionCanBeMade(connectionDetails); ++ } ++ ++ private void assertThatConnectionCanBeMade(RabbitConnectionDetails connectionDetails) throws Exception { ++ ConnectionFactory connectionFactory = new ConnectionFactory(); ++ Address address = connectionDetails.getFirstAddress(); ++ connectionFactory.setHost(address.host()); ++ connectionFactory.setPort(address.port()); ++ connectionFactory.setUsername(connectionDetails.getUsername()); ++ connectionFactory.setPassword(connectionDetails.getPassword()); ++ connectionFactory.setVirtualHost(connectionDetails.getVirtualHost()); ++ SslBundle sslBundle = connectionDetails.getSslBundle(); ++ if (sslBundle != null) { ++ connectionFactory.useSslProtocol(sslBundle.createSslContext()); ++ } ++ try (Connection connection = connectionFactory.newConnection()) { ++ assertThat(connection.isOpen()).isTrue(); ++ } + } + + } +diff --git a/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactory.java b/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactory.java +index a601ab093c3..31b1cfdc35e 100644 +--- a/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactory.java ++++ b/module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/docker/compose/RabbitDockerComposeConnectionDetailsFactory.java +@@ -40,6 +40,8 @@ class RabbitDockerComposeConnectionDetailsFactory + + private static final int RABBITMQ_PORT = 5672; + ++ private static final int RABBITMQ_TLS_PORT = 5671; ++ + protected RabbitDockerComposeConnectionDetailsFactory() { + super("rabbitmq"); + } +@@ -66,7 +68,8 @@ class RabbitDockerComposeConnectionDetailsFactory + super(service); + this.environment = new RabbitEnvironment(service.env()); + this.sslBundle = getSslBundle(service); +- this.addresses = List.of(new Address(service.host(), service.ports().get(RABBITMQ_PORT))); ++ int containerPort = (this.sslBundle != null) ? RABBITMQ_TLS_PORT : RABBITMQ_PORT; ++ this.addresses = List.of(new Address(service.host(), service.ports().get(containerPort))); + } + + @Override diff --git a/tasks/spring-projects__spring-boot-51666/tests/test.sh b/tasks/spring-projects__spring-boot-51666/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..15a7c4783d397b8c13549fc47823f090d35dc0d5 --- /dev/null +++ b/tasks/spring-projects__spring-boot-51666/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 5541ab2424137e775097d1c7286e011da7dcb3ab > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/spring-projects__spring-boot-51666/tests/verifier.py b/tasks/spring-projects__spring-boot-51666/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/spring-projects__spring-boot-51666/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``<endpoint>/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/<path>`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # <https://harborframework.com/docs/tasks>); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/spring-projects__spring-boot-51708/environment/Dockerfile b/tasks/spring-projects__spring-boot-51708/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..af2bd15a6d99ac2bec419b595fd20daf023ae8ec --- /dev/null +++ b/tasks/spring-projects__spring-boot-51708/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/spring-projects/spring-boot.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/spring-projects/spring-boot.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/spring-projects/spring-boot.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 96f5c74b03045d83367d09908f1194c30bd4af4e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 96f5c74b03045d83367d09908f1194c30bd4af4e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 96f5c74b03045d83367d09908f1194c30bd4af4e \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/spring-projects__spring-boot-51708/instruction.md b/tasks/spring-projects__spring-boot-51708/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..461a7f7c2fec633c6ac50d1bb05174957a6c0c1f --- /dev/null +++ b/tasks/spring-projects__spring-boot-51708/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** DevTools does not detect a reactive web environment + +## Description + +`DevToolsPropertyDefaultsPostProcessor` decides whether the application is a web application by checking the `Environment` against two class names. The reactive one, +`org.springframework.boot.web.reactive.context.ConfigurableReactiveWebEnvironment`, is stale: the class moved to `org.springframework.boot.web.context.reactive` in 4.0. Because +the lookup silently returns `null` for an unknown class, reactive web applications have not been identified as web applications since 4.0, so the "For additional web related +logging consider setting the 'logging.level.web' property to 'DEBUG'" hint is never logged for them. Servlet applications are unaffected. + +`ConfigurableReactiveWebEnvironment` lives in `spring-boot` itself, which DevTools always depends on, so this PR references it directly with `instanceof` instead of by name. +That way a future move is caught at compile time. The servlet check is left as a by-name lookup because `spring-web` is an optional dependency. + +There were no tests for this class, so this PR adds `DevToolsPropertyDefaultsPostProcessorTests` covering the servlet, reactive, non-web, and `logging.level.web`-already-set +cases. The reactive test fails on the current code and passes with the change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `96f5c74b0304`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51708/solution/patch.diff b/tasks/spring-projects__spring-boot-51708/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..584f229499e2609f74fe4627c25d3b69aff6e20f --- /dev/null +++ b/tasks/spring-projects__spring-boot-51708/solution/patch.diff @@ -0,0 +1,150 @@ +diff --git a/module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java b/module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java +index 8f4d3e949c7..4e2927bc820 100755 +--- a/module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java ++++ b/module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java +@@ -55,9 +55,9 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro + + private static final String WEB_LOGGING = "logging.level.web"; + +- private static final String[] WEB_ENVIRONMENT_CLASSES = { +- "org.springframework.web.context.ConfigurableWebEnvironment", +- "org.springframework.boot.web.reactive.context.ConfigurableReactiveWebEnvironment" }; ++ private static final WebEnvironmentClassResolver[] WEB_ENVIRONMENT_CLASS_RESOLVERS = new WebEnvironmentClassResolver[] { ++ WebEnvironmentClassResolver.fromClassName("org.springframework.web.context.ConfigurableWebEnvironment"), ++ (classloader) -> org.springframework.boot.web.context.reactive.ConfigurableReactiveWebEnvironment.class }; + + private static final Map<String, Object> PROPERTIES; + +@@ -112,8 +112,9 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro + } + + private boolean isWebApplication(Environment environment) { +- for (String candidate : WEB_ENVIRONMENT_CLASSES) { +- Class<?> environmentClass = resolveClassName(candidate, environment.getClass().getClassLoader()); ++ ClassLoader classLoader = environment.getClass().getClassLoader(); ++ for (WebEnvironmentClassResolver resolver : WEB_ENVIRONMENT_CLASS_RESOLVERS) { ++ Class<?> environmentClass = resolver.resolve(classLoader); + if (environmentClass != null && environmentClass.isInstance(environment)) { + return true; + } +@@ -121,13 +122,21 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro + return false; + } + +- private @Nullable Class<?> resolveClassName(String candidate, ClassLoader classLoader) { +- try { +- return ClassUtils.resolveClassName(candidate, classLoader); +- } +- catch (IllegalArgumentException ex) { +- return null; ++ private interface WebEnvironmentClassResolver { ++ ++ @Nullable Class<?> resolve(ClassLoader classLoader); ++ ++ static WebEnvironmentClassResolver fromClassName(String candidate) { ++ return (classLoader) -> { ++ try { ++ return ClassUtils.resolveClassName(candidate, classLoader); ++ } ++ catch (IllegalArgumentException ex) { ++ return null; ++ } ++ }; + } ++ + } + + } +diff --git a/module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessorTests.java b/module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessorTests.java +new file mode 100644 +index 00000000000..6bbad0f88f6 +--- /dev/null ++++ b/module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessorTests.java +@@ -0,0 +1,87 @@ ++/* ++ * Copyright 2012-present the original author or authors. ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * https://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++ ++package org.springframework.boot.devtools.env; ++ ++import org.junit.jupiter.api.Test; ++import org.junit.jupiter.api.extension.ExtendWith; ++ ++import org.springframework.boot.SpringApplication; ++import org.springframework.boot.logging.DeferredLog; ++import org.springframework.boot.test.system.CapturedOutput; ++import org.springframework.boot.test.system.OutputCaptureExtension; ++import org.springframework.boot.test.util.TestPropertyValues; ++import org.springframework.boot.web.context.reactive.StandardReactiveWebEnvironment; ++import org.springframework.core.env.ConfigurableEnvironment; ++import org.springframework.core.env.StandardEnvironment; ++import org.springframework.test.util.ReflectionTestUtils; ++import org.springframework.web.context.support.StandardServletEnvironment; ++ ++import static org.assertj.core.api.Assertions.assertThat; ++ ++/** ++ * Tests for {@link DevToolsPropertyDefaultsPostProcessor}. ++ * ++ * @author ohchanKyu ++ */ ++@ExtendWith(OutputCaptureExtension.class) ++class DevToolsPropertyDefaultsPostProcessorTests { ++ ++ private static final String WEB_LOGGING_HINT = "For additional web related logging consider setting the " ++ + "'logging.level.web' property to 'DEBUG'"; ++ ++ @Test ++ void postProcessWhenServletWebEnvironmentLogsWebLoggingHint(CapturedOutput output) throws Exception { ++ postProcess(new StandardServletEnvironment()); ++ assertThat(output).contains(WEB_LOGGING_HINT); ++ } ++ ++ @Test ++ void postProcessWhenReactiveWebEnvironmentLogsWebLoggingHint(CapturedOutput output) throws Exception { ++ postProcess(new StandardReactiveWebEnvironment()); ++ assertThat(output).contains(WEB_LOGGING_HINT); ++ } ++ ++ @Test ++ void postProcessWhenNonWebEnvironmentDoesNotLogWebLoggingHint(CapturedOutput output) throws Exception { ++ postProcess(new StandardEnvironment()); ++ assertThat(output).doesNotContain(WEB_LOGGING_HINT); ++ } ++ ++ @Test ++ void postProcessWhenWebLoggingIsConfiguredDoesNotLogWebLoggingHint(CapturedOutput output) throws Exception { ++ StandardReactiveWebEnvironment environment = new StandardReactiveWebEnvironment(); ++ TestPropertyValues.of("logging.level.web=DEBUG").applyTo(environment); ++ postProcess(environment); ++ assertThat(output).doesNotContain(WEB_LOGGING_HINT); ++ } ++ ++ private void postProcess(ConfigurableEnvironment environment) throws Exception { ++ DevToolsPropertyDefaultsPostProcessor postProcessor = new DevToolsPropertyDefaultsPostProcessor(); ++ // Run in a new thread so that DevTools is not disabled by the test runner ++ Thread thread = new Thread(() -> postProcessor.postProcessEnvironment(environment, new SpringApplication())); ++ thread.start(); ++ thread.join(); ++ replayDeferredLog(); ++ } ++ ++ private void replayDeferredLog() { ++ Object logger = ReflectionTestUtils.getField(DevToolsPropertyDefaultsPostProcessor.class, "logger"); ++ assertThat(logger).isInstanceOf(DeferredLog.class); ++ ((DeferredLog) logger).switchTo(DevToolsPropertyDefaultsPostProcessor.class); ++ } ++ ++} diff --git a/tasks/spring-projects__spring-boot-51708/solution/solve.sh b/tasks/spring-projects__spring-boot-51708/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/spring-projects__spring-boot-51708/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/spring-projects__spring-boot-51708/task.toml b/tasks/spring-projects__spring-boot-51708/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c9ae6dd8d1a56f9f4b99edbd9aed63628cde1d6e --- /dev/null +++ b/tasks/spring-projects__spring-boot-51708/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/spring-projects__spring-boot-51708" +description = "DevTools does not detect a reactive web environment" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "spring-boot", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "spring-projects/spring-boot" +ref = "96f5c74b03045d83367d09908f1194c30bd4af4e" +reference = "https://github.com/spring-projects/spring-boot/pull/51708" +source_access = "auto" +built_at = "2026-11-16T16:09:44.745237+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4a7bd0056698f39ea430e193b9e393911c070da9bd9bf1829d06cbb456dae2e0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-14T09:42:37Z" +diff_format = "unified" +context_files = [ + "module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java", + "module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessorTests.java", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 118 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:03.176104+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:10a0cab99607f74a57da4ae18daadf5d6d80ebd791a999c76f0ecd796ce6f512" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/spring-projects__spring-boot-51708/tests/capture.py b/tasks/spring-projects__spring-boot-51708/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/spring-projects__spring-boot-51708/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spring-projects__spring-boot-51708/tests/instruction.md b/tasks/spring-projects__spring-boot-51708/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..461a7f7c2fec633c6ac50d1bb05174957a6c0c1f --- /dev/null +++ b/tasks/spring-projects__spring-boot-51708/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** DevTools does not detect a reactive web environment + +## Description + +`DevToolsPropertyDefaultsPostProcessor` decides whether the application is a web application by checking the `Environment` against two class names. The reactive one, +`org.springframework.boot.web.reactive.context.ConfigurableReactiveWebEnvironment`, is stale: the class moved to `org.springframework.boot.web.context.reactive` in 4.0. Because +the lookup silently returns `null` for an unknown class, reactive web applications have not been identified as web applications since 4.0, so the "For additional web related +logging consider setting the 'logging.level.web' property to 'DEBUG'" hint is never logged for them. Servlet applications are unaffected. + +`ConfigurableReactiveWebEnvironment` lives in `spring-boot` itself, which DevTools always depends on, so this PR references it directly with `instanceof` instead of by name. +That way a future move is caught at compile time. The servlet check is left as a by-name lookup because `spring-web` is an optional dependency. + +There were no tests for this class, so this PR adds `DevToolsPropertyDefaultsPostProcessorTests` covering the servlet, reactive, non-web, and `logging.level.web`-already-set +cases. The reactive test fails on the current code and passes with the change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `96f5c74b0304`. 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. \ No newline at end of file diff --git a/tasks/spring-projects__spring-boot-51708/tests/oracle.patch b/tasks/spring-projects__spring-boot-51708/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..584f229499e2609f74fe4627c25d3b69aff6e20f --- /dev/null +++ b/tasks/spring-projects__spring-boot-51708/tests/oracle.patch @@ -0,0 +1,150 @@ +diff --git a/module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java b/module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java +index 8f4d3e949c7..4e2927bc820 100755 +--- a/module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java ++++ b/module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessor.java +@@ -55,9 +55,9 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro + + private static final String WEB_LOGGING = "logging.level.web"; + +- private static final String[] WEB_ENVIRONMENT_CLASSES = { +- "org.springframework.web.context.ConfigurableWebEnvironment", +- "org.springframework.boot.web.reactive.context.ConfigurableReactiveWebEnvironment" }; ++ private static final WebEnvironmentClassResolver[] WEB_ENVIRONMENT_CLASS_RESOLVERS = new WebEnvironmentClassResolver[] { ++ WebEnvironmentClassResolver.fromClassName("org.springframework.web.context.ConfigurableWebEnvironment"), ++ (classloader) -> org.springframework.boot.web.context.reactive.ConfigurableReactiveWebEnvironment.class }; + + private static final Map<String, Object> PROPERTIES; + +@@ -112,8 +112,9 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro + } + + private boolean isWebApplication(Environment environment) { +- for (String candidate : WEB_ENVIRONMENT_CLASSES) { +- Class<?> environmentClass = resolveClassName(candidate, environment.getClass().getClassLoader()); ++ ClassLoader classLoader = environment.getClass().getClassLoader(); ++ for (WebEnvironmentClassResolver resolver : WEB_ENVIRONMENT_CLASS_RESOLVERS) { ++ Class<?> environmentClass = resolver.resolve(classLoader); + if (environmentClass != null && environmentClass.isInstance(environment)) { + return true; + } +@@ -121,13 +122,21 @@ public class DevToolsPropertyDefaultsPostProcessor implements EnvironmentPostPro + return false; + } + +- private @Nullable Class<?> resolveClassName(String candidate, ClassLoader classLoader) { +- try { +- return ClassUtils.resolveClassName(candidate, classLoader); +- } +- catch (IllegalArgumentException ex) { +- return null; ++ private interface WebEnvironmentClassResolver { ++ ++ @Nullable Class<?> resolve(ClassLoader classLoader); ++ ++ static WebEnvironmentClassResolver fromClassName(String candidate) { ++ return (classLoader) -> { ++ try { ++ return ClassUtils.resolveClassName(candidate, classLoader); ++ } ++ catch (IllegalArgumentException ex) { ++ return null; ++ } ++ }; + } ++ + } + + } +diff --git a/module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessorTests.java b/module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessorTests.java +new file mode 100644 +index 00000000000..6bbad0f88f6 +--- /dev/null ++++ b/module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/env/DevToolsPropertyDefaultsPostProcessorTests.java +@@ -0,0 +1,87 @@ ++/* ++ * Copyright 2012-present the original author or authors. ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * https://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++ ++package org.springframework.boot.devtools.env; ++ ++import org.junit.jupiter.api.Test; ++import org.junit.jupiter.api.extension.ExtendWith; ++ ++import org.springframework.boot.SpringApplication; ++import org.springframework.boot.logging.DeferredLog; ++import org.springframework.boot.test.system.CapturedOutput; ++import org.springframework.boot.test.system.OutputCaptureExtension; ++import org.springframework.boot.test.util.TestPropertyValues; ++import org.springframework.boot.web.context.reactive.StandardReactiveWebEnvironment; ++import org.springframework.core.env.ConfigurableEnvironment; ++import org.springframework.core.env.StandardEnvironment; ++import org.springframework.test.util.ReflectionTestUtils; ++import org.springframework.web.context.support.StandardServletEnvironment; ++ ++import static org.assertj.core.api.Assertions.assertThat; ++ ++/** ++ * Tests for {@link DevToolsPropertyDefaultsPostProcessor}. ++ * ++ * @author ohchanKyu ++ */ ++@ExtendWith(OutputCaptureExtension.class) ++class DevToolsPropertyDefaultsPostProcessorTests { ++ ++ private static final String WEB_LOGGING_HINT = "For additional web related logging consider setting the " ++ + "'logging.level.web' property to 'DEBUG'"; ++ ++ @Test ++ void postProcessWhenServletWebEnvironmentLogsWebLoggingHint(CapturedOutput output) throws Exception { ++ postProcess(new StandardServletEnvironment()); ++ assertThat(output).contains(WEB_LOGGING_HINT); ++ } ++ ++ @Test ++ void postProcessWhenReactiveWebEnvironmentLogsWebLoggingHint(CapturedOutput output) throws Exception { ++ postProcess(new StandardReactiveWebEnvironment()); ++ assertThat(output).contains(WEB_LOGGING_HINT); ++ } ++ ++ @Test ++ void postProcessWhenNonWebEnvironmentDoesNotLogWebLoggingHint(CapturedOutput output) throws Exception { ++ postProcess(new StandardEnvironment()); ++ assertThat(output).doesNotContain(WEB_LOGGING_HINT); ++ } ++ ++ @Test ++ void postProcessWhenWebLoggingIsConfiguredDoesNotLogWebLoggingHint(CapturedOutput output) throws Exception { ++ StandardReactiveWebEnvironment environment = new StandardReactiveWebEnvironment(); ++ TestPropertyValues.of("logging.level.web=DEBUG").applyTo(environment); ++ postProcess(environment); ++ assertThat(output).doesNotContain(WEB_LOGGING_HINT); ++ } ++ ++ private void postProcess(ConfigurableEnvironment environment) throws Exception { ++ DevToolsPropertyDefaultsPostProcessor postProcessor = new DevToolsPropertyDefaultsPostProcessor(); ++ // Run in a new thread so that DevTools is not disabled by the test runner ++ Thread thread = new Thread(() -> postProcessor.postProcessEnvironment(environment, new SpringApplication())); ++ thread.start(); ++ thread.join(); ++ replayDeferredLog(); ++ } ++ ++ private void replayDeferredLog() { ++ Object logger = ReflectionTestUtils.getField(DevToolsPropertyDefaultsPostProcessor.class, "logger"); ++ assertThat(logger).isInstanceOf(DeferredLog.class); ++ ((DeferredLog) logger).switchTo(DevToolsPropertyDefaultsPostProcessor.class); ++ } ++ ++}