diff --git a/tasks/hadolint__hadolint-834/tests/test.sh b/tasks/hadolint__hadolint-834/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3ffa3efd65d679b413612760c1cfb5db1aa0975 --- /dev/null +++ b/tasks/hadolint__hadolint-834/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 6b30d652d5cd23a6b86c0eb2e1589101ea269f84 > "$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/hadolint__hadolint-834/tests/verifier.py b/tasks/hadolint__hadolint-834/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-834/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/hadolint__hadolint-844/environment/Dockerfile b/tasks/hadolint__hadolint-844/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b965b856667ecd9eb24b0564edbd3dcc58513502 --- /dev/null +++ b/tasks/hadolint__hadolint-844/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 321ffc1e00b5e97ec6b516775dae32b616fccc33 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 321ffc1e00b5e97ec6b516775dae32b616fccc33 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 321ffc1e00b5e97ec6b516775dae32b616fccc33 \ + && 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/hadolint__hadolint-844/instruction.md b/tasks/hadolint__hadolint-844/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..193112b4e9b66f45b648fe952af50692d433db14 --- /dev/null +++ b/tasks/hadolint__hadolint-844/instruction.md @@ -0,0 +1,83 @@ +# Issue + +**Title:** build(deps): bump actions/cache from 3.0.2 to 3.0.4 + +## Description + +Bumps [actions/cache](https://github.com/actions/cache) from 3.0.2 to 3.0.4. +
+Release notes +

Sourced from actions/cache's releases.

+
+

v3.0.4

+

In this release, we have fixed the tar creation error while trying to create it with path as ~/ home folder on ubuntu-latest.

+

v3.0.3

+

Fixed avoiding empty cache save when no files are available for caching. (actions/cache#624)

+
+
+
+Changelog +

Sourced from actions/cache's changelog.

+
+

3.0.2

+
    +
  • Added support for dynamic cache size cap on GHES.
  • +
+

3.0.3

+
    +
  • Fixed avoiding empty cache save when no files are available for caching. (issue)
  • +
+

3.0.4

+
    +
  • Fixed tar creation error while trying to create tar with path as ~/ home folder on ubuntu-latest. (issue)
  • +
+
+
+
+Commits +
    +
  • c3f1317 Merge pull request #813 from actions/users/kotewar/upgrading-cache-to-v2.0.6
  • +
  • d0a54b9 Fixed typo
  • +
  • 8c5bd0c Updated README file with release info
  • +
  • c9c0f73 Merge pull request #812 from actions/users/kotewar/upgrading-cache-to-v2.0.6
  • +
  • 2b6caae Merge pull request #495 from ostera/patch-1
  • +
  • dd58d13 Added release info and upgraded version
  • +
  • acace7f Merge branch 'main' into patch-1
  • +
  • 438628a Merge pull request #554 from albertstill/improve-restore-key-docs
  • +
  • c296e6a Updated @​actions/cache version in license file
  • +
  • 7ed7f22 Updated actions/cache to v2.0.6
  • +
  • Additional commits viewable in compare view
  • +
+
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/cache&package-manager=github_actions&previous-version=3.0.2&new-version=3.0.4)](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) + +--- + +
+Dependabot commands and options +
+ +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 merge` will merge this PR after your CI passes on it +- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it +- `@dependabot cancel merge` will cancel a previously requested merge and block automerging +- `@dependabot reopen` will reopen this PR if it is closed +- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually +- `@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) + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `321ffc1e00b5`. 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/hadolint__hadolint-844/solution/patch.diff b/tasks/hadolint__hadolint-844/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..be0c032638aca855226bb2ec2238886dac2ac8a2 --- /dev/null +++ b/tasks/hadolint__hadolint-844/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml +index fbbf1ab..f15856d 100644 +--- a/.github/workflows/haskell.yml ++++ b/.github/workflows/haskell.yml +@@ -53,7 +53,7 @@ jobs: + # cache + + - name: Cache store +- uses: actions/cache@v3.0.2 ++ uses: actions/cache@v3.0.4 + with: + path: ${{ steps.setup-haskell-cabal.outputs.cabal-store }} + key: ${{ runner.os }}-${{ hashFiles('cabal.project.freeze') }} +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index 894698d..714d7b8 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -235,7 +235,7 @@ jobs: + run: cabal freeze + + - name: Cache store +- uses: actions/cache@v3.0.2 ++ uses: actions/cache@v3.0.4 + with: + path: ${{ steps.setup-haskell-cabal.outputs.cabal-store }} + key: ${{ runner.os }}-${{ hashFiles('cabal.project.freeze') }} diff --git a/tasks/hadolint__hadolint-844/solution/solve.sh b/tasks/hadolint__hadolint-844/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-844/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/hadolint__hadolint-844/task.toml b/tasks/hadolint__hadolint-844/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..abea9bd7b8e6b4752b0e406a328e1e020588d7c7 --- /dev/null +++ b/tasks/hadolint__hadolint-844/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-844" +description = "build(deps): bump actions/cache from 3.0.2 to 3.0.4" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "321ffc1e00b5e97ec6b516775dae32b616fccc33" +reference = "https://github.com/hadolint/hadolint/pull/844" +source_access = "auto" +built_at = "2026-11-16T16:09:53.746031+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6ef869bdf3a35f912dd5c549458802d47bda1d1db55875b8d9526c2de91dfa2e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-07-09T16:38:27Z" +diff_format = "unified" +context_files = [ + ".github/workflows/haskell.yml", + ".github/workflows/release.yml", +] +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:00.798600+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:886fe9a55d740dc107f770de841f3ceb4ca32c1a42fb56c2c0280cd6b1e728f4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-844/tests/capture.py b/tasks/hadolint__hadolint-844/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-844/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/hadolint__hadolint-844/tests/instruction.md b/tasks/hadolint__hadolint-844/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..193112b4e9b66f45b648fe952af50692d433db14 --- /dev/null +++ b/tasks/hadolint__hadolint-844/tests/instruction.md @@ -0,0 +1,83 @@ +# Issue + +**Title:** build(deps): bump actions/cache from 3.0.2 to 3.0.4 + +## Description + +Bumps [actions/cache](https://github.com/actions/cache) from 3.0.2 to 3.0.4. +
+Release notes +

Sourced from actions/cache's releases.

+
+

v3.0.4

+

In this release, we have fixed the tar creation error while trying to create it with path as ~/ home folder on ubuntu-latest.

+

v3.0.3

+

Fixed avoiding empty cache save when no files are available for caching. (actions/cache#624)

+
+
+
+Changelog +

Sourced from actions/cache's changelog.

+
+

3.0.2

+
    +
  • Added support for dynamic cache size cap on GHES.
  • +
+

3.0.3

+
    +
  • Fixed avoiding empty cache save when no files are available for caching. (issue)
  • +
+

3.0.4

+
    +
  • Fixed tar creation error while trying to create tar with path as ~/ home folder on ubuntu-latest. (issue)
  • +
+
+
+
+Commits +
    +
  • c3f1317 Merge pull request #813 from actions/users/kotewar/upgrading-cache-to-v2.0.6
  • +
  • d0a54b9 Fixed typo
  • +
  • 8c5bd0c Updated README file with release info
  • +
  • c9c0f73 Merge pull request #812 from actions/users/kotewar/upgrading-cache-to-v2.0.6
  • +
  • 2b6caae Merge pull request #495 from ostera/patch-1
  • +
  • dd58d13 Added release info and upgraded version
  • +
  • acace7f Merge branch 'main' into patch-1
  • +
  • 438628a Merge pull request #554 from albertstill/improve-restore-key-docs
  • +
  • c296e6a Updated @​actions/cache version in license file
  • +
  • 7ed7f22 Updated actions/cache to v2.0.6
  • +
  • Additional commits viewable in compare view
  • +
+
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/cache&package-manager=github_actions&previous-version=3.0.2&new-version=3.0.4)](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) + +--- + +
+Dependabot commands and options +
+ +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 merge` will merge this PR after your CI passes on it +- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it +- `@dependabot cancel merge` will cancel a previously requested merge and block automerging +- `@dependabot reopen` will reopen this PR if it is closed +- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually +- `@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) + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `321ffc1e00b5`. 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/hadolint__hadolint-844/tests/oracle.patch b/tasks/hadolint__hadolint-844/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..be0c032638aca855226bb2ec2238886dac2ac8a2 --- /dev/null +++ b/tasks/hadolint__hadolint-844/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml +index fbbf1ab..f15856d 100644 +--- a/.github/workflows/haskell.yml ++++ b/.github/workflows/haskell.yml +@@ -53,7 +53,7 @@ jobs: + # cache + + - name: Cache store +- uses: actions/cache@v3.0.2 ++ uses: actions/cache@v3.0.4 + with: + path: ${{ steps.setup-haskell-cabal.outputs.cabal-store }} + key: ${{ runner.os }}-${{ hashFiles('cabal.project.freeze') }} +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index 894698d..714d7b8 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -235,7 +235,7 @@ jobs: + run: cabal freeze + + - name: Cache store +- uses: actions/cache@v3.0.2 ++ uses: actions/cache@v3.0.4 + with: + path: ${{ steps.setup-haskell-cabal.outputs.cabal-store }} + key: ${{ runner.os }}-${{ hashFiles('cabal.project.freeze') }} diff --git a/tasks/hadolint__hadolint-844/tests/test.sh b/tasks/hadolint__hadolint-844/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a3c2b2826f7b1f6a893e7a7e895bfee9f36f01f --- /dev/null +++ b/tasks/hadolint__hadolint-844/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 321ffc1e00b5e97ec6b516775dae32b616fccc33 > "$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/hadolint__hadolint-844/tests/verifier.py b/tasks/hadolint__hadolint-844/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-844/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/hadolint__hadolint-845/environment/Dockerfile b/tasks/hadolint__hadolint-845/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b965b856667ecd9eb24b0564edbd3dcc58513502 --- /dev/null +++ b/tasks/hadolint__hadolint-845/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 321ffc1e00b5e97ec6b516775dae32b616fccc33 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 321ffc1e00b5e97ec6b516775dae32b616fccc33 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 321ffc1e00b5e97ec6b516775dae32b616fccc33 \ + && 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/hadolint__hadolint-845/instruction.md b/tasks/hadolint__hadolint-845/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4100becc14cdee61a8276dfb1f5d7a40ff76bc6c --- /dev/null +++ b/tasks/hadolint__hadolint-845/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** DL3013: Fix false positives for VCS, http and local path packages + +## Description + +### What I did +- Fix false positive when installing package with other supported VCS + such as: `pip install bzr+ssh://..@1.0.0`, as described in + https://pip.pypa.io/en/stable/topics/vcs-support/. +- Fix false positive when installing package from local directory: + `pip install my/install/path` +- Fix false positive when installing package from http/https url: + `pip install https://foo.bar/baz-1.0.0.zip` + + + +### How I did it +Extended the previous check for a `git+https` vcs scheme to allow any of the supported vcs sources, such as `git+ssh` and `bzr+ssh`, documented in https://pip.pypa.io/en/stable/topics/vcs-support/. Also added passing check if a package source included a forward slash (/) but is not a valid vcs source. + +### How to verify it +Compare the supported VCS in this PR from the VCS supported from the pip documentation https://pip.pypa.io/en/stable/topics/vcs-support/. Also, the following Dockerfile illustrates cases where hadolint now runs without any warnings. + +```Dockerfile +FROM python:3.10 + +RUN pip install --no-cache-dir \ + git+ssh://hello@1.3 \ + hello/bar/baz \ + https://foo.bar/baz-1.0.0.zip +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `321ffc1e00b5`. 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/hadolint__hadolint-845/solution/patch.diff b/tasks/hadolint__hadolint-845/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ccf640aa65b19341944937d629e5f8e4758e0967 --- /dev/null +++ b/tasks/hadolint__hadolint-845/solution/patch.diff @@ -0,0 +1,104 @@ +diff --git a/src/Hadolint/Rule/DL3013.hs b/src/Hadolint/Rule/DL3013.hs +index 6292e79..53c185f 100644 +--- a/src/Hadolint/Rule/DL3013.hs ++++ b/src/Hadolint/Rule/DL3013.hs +@@ -44,12 +44,18 @@ dl3013 = simpleRule code severity message check + || ["."] `isInfixOf` Shell.getArgs cmd + + hasBuildConstraint cmd = Shell.hasFlag "constraint" cmd || Shell.hasFlag "c" cmd +- versionFixed package = hasVersionSymbol package || isVersionedGit package || isLocalPackage package +- isVersionedGit package = "git+http" `Text.isInfixOf` package && "@" `Text.isInfixOf` package ++ versionFixed package = hasVersionSymbol package ++ || isVersionedVcs package ++ || isLocalPackage package ++ || isNoVcsPathSource package ++ isVersionedVcs package = isVcs package ++ && "@" `Text.isInfixOf` package + versionSymbols = ["==", ">=", "<=", ">", "<", "!=", "~=", "==="] + hasVersionSymbol package = or [s `Text.isInfixOf` package | s <- versionSymbols] + localPackageFileExtensions = [".whl", ".tar.gz"] + isLocalPackage package = or [s `Text.isSuffixOf` package | s <- localPackageFileExtensions] ++ isNoVcsPathSource package = not (isVcs package) && "/" `Text.isInfixOf` package ++ isVcs package = any (`Text.isPrefixOf` package) vcsSchemes + {-# INLINEABLE dl3013 #-} + + packages :: Shell.Command -> [Text.Text] +@@ -84,5 +90,34 @@ packages cmd = + ] + cmd + ++-- Supported schemes vcs[+protocol] are found here: ++-- https://pip.pypa.io/en/stable/topics/vcs-support/ ++vcsSchemes :: [Text.Text] ++vcsSchemes = ++ [ ++ "git+file", ++ "git+https", ++ "git+ssh", ++ "git+http", ++ "git+git", ++ "git", ++ "hg+file", ++ "hg+http", ++ "hg+https", ++ "hg+ssh", ++ "hg+static-http", ++ "svn", ++ "svn+svn", ++ "svn+http", ++ "svn+https", ++ "svn+ssh", ++ "bzr+http", ++ "bzr+https", ++ "bzr+ssh", ++ "bzr+sftp", ++ "bzr+ftp", ++ "bzr+lp" ++ ] ++ + stripInstallPrefix :: [Text.Text] -> [Text.Text] + stripInstallPrefix cmd = dropWhile (== "install") (dropWhile (/= "install") cmd) +diff --git a/test/Hadolint/Rule/DL3013Spec.hs b/test/Hadolint/Rule/DL3013Spec.hs +index ebd0c39..a9315f3 100644 +--- a/test/Hadolint/Rule/DL3013Spec.hs ++++ b/test/Hadolint/Rule/DL3013Spec.hs +@@ -76,6 +76,12 @@ spec = do + onBuildRuleCatchesNot + "DL3013" + "RUN pip install git+https://github.com/rtfd/r-ext.git@0.6-alpha#egg=r-ext" ++ ruleCatchesNot ++ "DL3013" ++ "RUN pip install git+ssh://github.com/rtfd/r-ext.git@0.6-alpha#egg=r-ext" ++ onBuildRuleCatchesNot ++ "DL3013" ++ "RUN pip install git+ssh://github.com/rtfd/r-ext.git@0.6-alpha#egg=r-ext" + it "pip install unversioned git" $ do + ruleCatches + "DL3013" +@@ -83,6 +89,26 @@ spec = do + onBuildRuleCatches + "DL3013" + "RUN pip install git+https://github.com/rtfd/read-ext.git#egg=read-ext" ++ ruleCatches ++ "DL3013" ++ "RUN pip install git+ssh://github.com/rtfd/read-ext.git#egg=read-ext" ++ onBuildRuleCatches ++ "DL3013" ++ "RUN pip install git+ssh://github.com/rtfd/read-ext.git#egg=read-ext" ++ it "pip install local dir" $ do ++ ruleCatchesNot ++ "DL3013" ++ "RUN pip install foo/bar" ++ onBuildRuleCatchesNot ++ "DL3013" ++ "RUN pip install foo/bar" ++ it "pip install https url package" $ do ++ ruleCatchesNot ++ "DL3013" ++ "RUN pip install https://foo.bar/baz.zip" ++ onBuildRuleCatchesNot ++ "DL3013" ++ "RUN pip install https://foo.bar/baz.zip" + it "pip install upper bound" $ do + ruleCatchesNot "DL3013" "RUN pip install 'alabaster>=0.7'" + onBuildRuleCatchesNot "DL3013" "RUN pip install 'alabaster>=0.7'" diff --git a/tasks/hadolint__hadolint-845/solution/solve.sh b/tasks/hadolint__hadolint-845/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-845/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/hadolint__hadolint-845/task.toml b/tasks/hadolint__hadolint-845/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4ea8961444630bc6f7d7b145d6484ce645284b96 --- /dev/null +++ b/tasks/hadolint__hadolint-845/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-845" +description = "DL3013: Fix false positives for VCS, http and local path packages (#389)" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "321ffc1e00b5e97ec6b516775dae32b616fccc33" +reference = "https://github.com/hadolint/hadolint/pull/845" +source_access = "auto" +built_at = "2026-11-16T16:09:53.748001+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7acdfd4e97da17e136f879ce595d5a20b4983f31774f693973f0c7ce07cbed45" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-07-09T16:37:53Z" +diff_format = "unified" +context_files = [ + "src/Hadolint/Rule/DL3013.hs", + "test/Hadolint/Rule/DL3013Spec.hs", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 65 +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:00.799050+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:886fe9a55d740dc107f770de841f3ceb4ca32c1a42fb56c2c0280cd6b1e728f4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-845/tests/capture.py b/tasks/hadolint__hadolint-845/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-845/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/hadolint__hadolint-845/tests/instruction.md b/tasks/hadolint__hadolint-845/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4100becc14cdee61a8276dfb1f5d7a40ff76bc6c --- /dev/null +++ b/tasks/hadolint__hadolint-845/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** DL3013: Fix false positives for VCS, http and local path packages + +## Description + +### What I did +- Fix false positive when installing package with other supported VCS + such as: `pip install bzr+ssh://..@1.0.0`, as described in + https://pip.pypa.io/en/stable/topics/vcs-support/. +- Fix false positive when installing package from local directory: + `pip install my/install/path` +- Fix false positive when installing package from http/https url: + `pip install https://foo.bar/baz-1.0.0.zip` + + + +### How I did it +Extended the previous check for a `git+https` vcs scheme to allow any of the supported vcs sources, such as `git+ssh` and `bzr+ssh`, documented in https://pip.pypa.io/en/stable/topics/vcs-support/. Also added passing check if a package source included a forward slash (/) but is not a valid vcs source. + +### How to verify it +Compare the supported VCS in this PR from the VCS supported from the pip documentation https://pip.pypa.io/en/stable/topics/vcs-support/. Also, the following Dockerfile illustrates cases where hadolint now runs without any warnings. + +```Dockerfile +FROM python:3.10 + +RUN pip install --no-cache-dir \ + git+ssh://hello@1.3 \ + hello/bar/baz \ + https://foo.bar/baz-1.0.0.zip +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `321ffc1e00b5`. 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/hadolint__hadolint-845/tests/oracle.patch b/tasks/hadolint__hadolint-845/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ccf640aa65b19341944937d629e5f8e4758e0967 --- /dev/null +++ b/tasks/hadolint__hadolint-845/tests/oracle.patch @@ -0,0 +1,104 @@ +diff --git a/src/Hadolint/Rule/DL3013.hs b/src/Hadolint/Rule/DL3013.hs +index 6292e79..53c185f 100644 +--- a/src/Hadolint/Rule/DL3013.hs ++++ b/src/Hadolint/Rule/DL3013.hs +@@ -44,12 +44,18 @@ dl3013 = simpleRule code severity message check + || ["."] `isInfixOf` Shell.getArgs cmd + + hasBuildConstraint cmd = Shell.hasFlag "constraint" cmd || Shell.hasFlag "c" cmd +- versionFixed package = hasVersionSymbol package || isVersionedGit package || isLocalPackage package +- isVersionedGit package = "git+http" `Text.isInfixOf` package && "@" `Text.isInfixOf` package ++ versionFixed package = hasVersionSymbol package ++ || isVersionedVcs package ++ || isLocalPackage package ++ || isNoVcsPathSource package ++ isVersionedVcs package = isVcs package ++ && "@" `Text.isInfixOf` package + versionSymbols = ["==", ">=", "<=", ">", "<", "!=", "~=", "==="] + hasVersionSymbol package = or [s `Text.isInfixOf` package | s <- versionSymbols] + localPackageFileExtensions = [".whl", ".tar.gz"] + isLocalPackage package = or [s `Text.isSuffixOf` package | s <- localPackageFileExtensions] ++ isNoVcsPathSource package = not (isVcs package) && "/" `Text.isInfixOf` package ++ isVcs package = any (`Text.isPrefixOf` package) vcsSchemes + {-# INLINEABLE dl3013 #-} + + packages :: Shell.Command -> [Text.Text] +@@ -84,5 +90,34 @@ packages cmd = + ] + cmd + ++-- Supported schemes vcs[+protocol] are found here: ++-- https://pip.pypa.io/en/stable/topics/vcs-support/ ++vcsSchemes :: [Text.Text] ++vcsSchemes = ++ [ ++ "git+file", ++ "git+https", ++ "git+ssh", ++ "git+http", ++ "git+git", ++ "git", ++ "hg+file", ++ "hg+http", ++ "hg+https", ++ "hg+ssh", ++ "hg+static-http", ++ "svn", ++ "svn+svn", ++ "svn+http", ++ "svn+https", ++ "svn+ssh", ++ "bzr+http", ++ "bzr+https", ++ "bzr+ssh", ++ "bzr+sftp", ++ "bzr+ftp", ++ "bzr+lp" ++ ] ++ + stripInstallPrefix :: [Text.Text] -> [Text.Text] + stripInstallPrefix cmd = dropWhile (== "install") (dropWhile (/= "install") cmd) +diff --git a/test/Hadolint/Rule/DL3013Spec.hs b/test/Hadolint/Rule/DL3013Spec.hs +index ebd0c39..a9315f3 100644 +--- a/test/Hadolint/Rule/DL3013Spec.hs ++++ b/test/Hadolint/Rule/DL3013Spec.hs +@@ -76,6 +76,12 @@ spec = do + onBuildRuleCatchesNot + "DL3013" + "RUN pip install git+https://github.com/rtfd/r-ext.git@0.6-alpha#egg=r-ext" ++ ruleCatchesNot ++ "DL3013" ++ "RUN pip install git+ssh://github.com/rtfd/r-ext.git@0.6-alpha#egg=r-ext" ++ onBuildRuleCatchesNot ++ "DL3013" ++ "RUN pip install git+ssh://github.com/rtfd/r-ext.git@0.6-alpha#egg=r-ext" + it "pip install unversioned git" $ do + ruleCatches + "DL3013" +@@ -83,6 +89,26 @@ spec = do + onBuildRuleCatches + "DL3013" + "RUN pip install git+https://github.com/rtfd/read-ext.git#egg=read-ext" ++ ruleCatches ++ "DL3013" ++ "RUN pip install git+ssh://github.com/rtfd/read-ext.git#egg=read-ext" ++ onBuildRuleCatches ++ "DL3013" ++ "RUN pip install git+ssh://github.com/rtfd/read-ext.git#egg=read-ext" ++ it "pip install local dir" $ do ++ ruleCatchesNot ++ "DL3013" ++ "RUN pip install foo/bar" ++ onBuildRuleCatchesNot ++ "DL3013" ++ "RUN pip install foo/bar" ++ it "pip install https url package" $ do ++ ruleCatchesNot ++ "DL3013" ++ "RUN pip install https://foo.bar/baz.zip" ++ onBuildRuleCatchesNot ++ "DL3013" ++ "RUN pip install https://foo.bar/baz.zip" + it "pip install upper bound" $ do + ruleCatchesNot "DL3013" "RUN pip install 'alabaster>=0.7'" + onBuildRuleCatchesNot "DL3013" "RUN pip install 'alabaster>=0.7'" diff --git a/tasks/hadolint__hadolint-845/tests/test.sh b/tasks/hadolint__hadolint-845/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a3c2b2826f7b1f6a893e7a7e895bfee9f36f01f --- /dev/null +++ b/tasks/hadolint__hadolint-845/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 321ffc1e00b5e97ec6b516775dae32b616fccc33 > "$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/hadolint__hadolint-845/tests/verifier.py b/tasks/hadolint__hadolint-845/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-845/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/hadolint__hadolint-850/environment/Dockerfile b/tasks/hadolint__hadolint-850/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b965b856667ecd9eb24b0564edbd3dcc58513502 --- /dev/null +++ b/tasks/hadolint__hadolint-850/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 321ffc1e00b5e97ec6b516775dae32b616fccc33 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 321ffc1e00b5e97ec6b516775dae32b616fccc33 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 321ffc1e00b5e97ec6b516775dae32b616fccc33 \ + && 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/hadolint__hadolint-850/instruction.md b/tasks/hadolint__hadolint-850/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e7cd4c98ac500722c81cb4611611d8b0e883d05f --- /dev/null +++ b/tasks/hadolint__hadolint-850/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add SC3046 in hadolint JSON Schema + +## Description + +This avoid an error in IDE when updating .hadolint.yml config file + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `321ffc1e00b5`. 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/hadolint__hadolint-850/solution/patch.diff b/tasks/hadolint__hadolint-850/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..22671947e9d01e49eb41499fbf7b75f465f883c3 --- /dev/null +++ b/tasks/hadolint__hadolint-850/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/contrib/hadolint.json b/contrib/hadolint.json +index 47a85d8..4021330 100644 +--- a/contrib/hadolint.json ++++ b/contrib/hadolint.json +@@ -568,6 +568,11 @@ + "const": "SC2164", + "description": "Use `cd ... || exit` in case `cd` fails.", + "$comment": "https://github.com/koalaman/shellcheck/wiki/SC2164" ++ }, ++ { ++ "const": "SC3046", ++ "description": "In POSIX sh, 'source' in place of '.' is undefined.", ++ "$comment": "https://github.com/koalaman/shellcheck/wiki/SC3046" + } + ] + } diff --git a/tasks/hadolint__hadolint-850/solution/solve.sh b/tasks/hadolint__hadolint-850/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-850/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/hadolint__hadolint-850/task.toml b/tasks/hadolint__hadolint-850/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e09e7e8f78142d327147dd68ac25a108b79ab1e8 --- /dev/null +++ b/tasks/hadolint__hadolint-850/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-850" +description = "Add SC3046 in hadolint JSON Schema" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "321ffc1e00b5e97ec6b516775dae32b616fccc33" +reference = "https://github.com/hadolint/hadolint/pull/850" +source_access = "auto" +built_at = "2026-11-16T16:09:53.749639+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f2656d1963393c21ed7821ba9e196b9f8bd32f6f6535fac3ba4b04b6c57d3fb3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-07-09T16:36:51Z" +diff_format = "unified" +context_files = [ + "contrib/hadolint.json", +] +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:00.799489+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:886fe9a55d740dc107f770de841f3ceb4ca32c1a42fb56c2c0280cd6b1e728f4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-850/tests/capture.py b/tasks/hadolint__hadolint-850/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-850/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/hadolint__hadolint-850/tests/instruction.md b/tasks/hadolint__hadolint-850/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e7cd4c98ac500722c81cb4611611d8b0e883d05f --- /dev/null +++ b/tasks/hadolint__hadolint-850/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add SC3046 in hadolint JSON Schema + +## Description + +This avoid an error in IDE when updating .hadolint.yml config file + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `321ffc1e00b5`. 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/hadolint__hadolint-850/tests/oracle.patch b/tasks/hadolint__hadolint-850/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..22671947e9d01e49eb41499fbf7b75f465f883c3 --- /dev/null +++ b/tasks/hadolint__hadolint-850/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/contrib/hadolint.json b/contrib/hadolint.json +index 47a85d8..4021330 100644 +--- a/contrib/hadolint.json ++++ b/contrib/hadolint.json +@@ -568,6 +568,11 @@ + "const": "SC2164", + "description": "Use `cd ... || exit` in case `cd` fails.", + "$comment": "https://github.com/koalaman/shellcheck/wiki/SC2164" ++ }, ++ { ++ "const": "SC3046", ++ "description": "In POSIX sh, 'source' in place of '.' is undefined.", ++ "$comment": "https://github.com/koalaman/shellcheck/wiki/SC3046" + } + ] + } diff --git a/tasks/hadolint__hadolint-850/tests/test.sh b/tasks/hadolint__hadolint-850/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a3c2b2826f7b1f6a893e7a7e895bfee9f36f01f --- /dev/null +++ b/tasks/hadolint__hadolint-850/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 321ffc1e00b5e97ec6b516775dae32b616fccc33 > "$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/hadolint__hadolint-850/tests/verifier.py b/tasks/hadolint__hadolint-850/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-850/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/hadolint__hadolint-851/environment/Dockerfile b/tasks/hadolint__hadolint-851/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b965b856667ecd9eb24b0564edbd3dcc58513502 --- /dev/null +++ b/tasks/hadolint__hadolint-851/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 321ffc1e00b5e97ec6b516775dae32b616fccc33 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 321ffc1e00b5e97ec6b516775dae32b616fccc33 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 321ffc1e00b5e97ec6b516775dae32b616fccc33 \ + && 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/hadolint__hadolint-851/instruction.md b/tasks/hadolint__hadolint-851/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1ea818691b3c0220582994d3173630526d511b29 --- /dev/null +++ b/tasks/hadolint__hadolint-851/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** DL3057: fix multiple warnings for multistage builds + +## Description + +DL3057 checks that images produced in multistage builds have a +healthcheck (if the rule is enabled). But if one stage already has the +healthcheck instruction, the other stages should not trigger a warning. +If the stage comes earlier, it's obviously not used as a build result, +therefore doesn't need a healthcheck instruction on its own. +If the stage comes later, it will inherit the healthcheck instruction +from the stage that has it. + +This fix works because when a healthcheck is found in a build stage, +that stage is marked as good, but also all stages it inherited from are +also marked as good. Only stages that don't inherit the healthcheck +instruction remain marked as bad, if they don't have the instruction +themselves. Therefore Dockerfiles, which produce multiple images are +also considered. + +fixes: #843 + + +### How to verify it +This does not trigger DL3057 at all anymore: +```Dockerfile +FROM opensuse/leap:15.4 AS base0 +FROM base0 AS base1 +HEALTHCHECK NONE +FROM base1 +``` + +This triggers for the last stage only: +```Dockerfile +FROM opensuse/leap:15.4 AS base0 +FROM base0 AS base1 +FROM base1 AS base2.1 +HEALTHCHECK NONE + +FROM base1 AS base2.2 +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `321ffc1e00b5`. 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/hadolint__hadolint-851/solution/patch.diff b/tasks/hadolint__hadolint-851/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..295b2d0798ff6468927f3f9235b8e8eb07877f0d --- /dev/null +++ b/tasks/hadolint__hadolint-851/solution/patch.diff @@ -0,0 +1,157 @@ +diff --git a/src/Hadolint/Rule/DL3057.hs b/src/Hadolint/Rule/DL3057.hs +index d8a4820..bca55a4 100644 +--- a/src/Hadolint/Rule/DL3057.hs ++++ b/src/Hadolint/Rule/DL3057.hs +@@ -8,7 +8,8 @@ import Language.Docker.Syntax + + + data StageID = StageID +- { name :: Text.Text, ++ { src :: Text.Text, ++ name :: Text.Text, + line :: Linenumber + } deriving (Show, Eq, Ord) + +@@ -25,16 +26,24 @@ rule = veryCustomRule check (emptyState Empty) markFailures + message = "`HEALTHCHECK` instruction missing." + + check line state (From BaseImage {image, alias = Just als}) = +- state |> modify (currentStage (imageName image) (StageID (unImageAlias als) line)) ++ state |> modify ++ ( currentStage ++ (imageName image) ++ (StageID (imageName image) (unImageAlias als) line) ++ ) + check line state (From BaseImage {image, alias = Nothing}) = +- state |> modify (currentStage (imageName image) (StageID (imageName image) line)) ++ state |> modify ++ ( currentStage ++ (imageName image) ++ (StageID (imageName image) (imageName image) line) ++ ) + check _ state (Healthcheck _) = state |> modify goodStage + check _ state _ = state + + markFailures :: State Acc -> Failures + markFailures (State fails (Acc _ _ b)) = Set.foldl' (Seq.|>) fails (Set.map makeFail b) + markFailures st = failures st +- makeFail (StageID _ line) = CheckFailure {..} ++ makeFail (StageID _ _ line) = CheckFailure {..} + {-# INLINEABLE rule #-} + + currentStage :: Text.Text -> StageID -> Acc -> Acc +@@ -46,5 +55,29 @@ currentStage src stageid (Acc _ g b) + currentStage _ stageid Empty = Acc stageid Set.empty (Set.singleton stageid) + + goodStage :: Acc -> Acc +-goodStage (Acc stageid g b) = Acc stageid (g |> Set.insert stageid) (b |> Set.delete stageid) ++goodStage (Acc stageid g b) = do ++ let nowGood = recurseGood b stageid ++ let good = ++ g ++ |> Set.union nowGood ++ |> Set.insert stageid ++ bad = ++ b ++ |> flip Set.difference nowGood ++ |> Set.delete stageid ++ in Acc ++ stageid ++ good ++ bad ++ where ++ predicate StageID { src = s1 } StageID { name = n1 } = n1 == s1 ++ ++ recurseGood :: Set.Set StageID -> StageID -> Set.Set StageID ++ recurseGood bad sid = do ++ let g1 = Set.filter (predicate sid) bad -- bad stages to be marked good ++ b1 = Set.difference bad g1 -- bad stages not to be marked good ++ in if Set.null g1 ++ then g1 ++ else Set.union g1 $ Set.unions $ Set.map (recurseGood b1) g1 ++ + goodStage Empty = Empty +diff --git a/test/Hadolint/Rule/DL3057Spec.hs b/test/Hadolint/Rule/DL3057Spec.hs +index 5c04bcf..cb1eba6 100644 +--- a/test/Hadolint/Rule/DL3057Spec.hs ++++ b/test/Hadolint/Rule/DL3057Spec.hs +@@ -1,6 +1,7 @@ + module Hadolint.Rule.DL3057Spec (spec) where + + import Data.Default ++import Data.Text as Text + import Helpers + import Test.Hspec + +@@ -10,11 +11,63 @@ spec = do + let ?config = def + + describe "DL3057 - `HEALTHCHECK instruction missing" $ do +- it "warn with no HEALTHCHECK instructions" $ +- ruleCatches "DL3057" "FROM scratch" +- it "ok with one HEALTHCHECK instruction" $ +- ruleCatchesNot "DL3057" "FROM scratch\nHEALTHCHECK CMD /bin/bla" +- it "ok with inheriting HEALTHCHECK instruction" $ +- ruleCatchesNot "DL3057" "FROM scratch AS base\nHEALTHCHECK CMD /bin/bla\nFROM base" +- it "warn when not inheriting with no HEALTHCHECK instruction" $ +- ruleCatches "DL3057" "FROM scratch AS base\nHEALTHCHECK CMD /bin/bla\nFROM scratch" ++ ++ it "warn with no HEALTHCHECK instructions" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch" ++ ] ++ in ruleCatches "DL3057" dockerfile ++ ++ it "ok when HEALTHCHECK is explicitly disabled" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch", ++ "HEALTHCHECK NONE" ++ ] ++ in ruleCatchesNot "DL3057" dockerfile ++ ++ it "ok with one HEALTHCHECK instruction" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch", ++ "HEALTHCHECK CMD /bin/bla" ++ ] ++ in ruleCatchesNot "DL3057" dockerfile ++ ++ it "ok with inheriting HEALTHCHECK instruction" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch AS base", ++ "HEALTHCHECK CMD /bin/bla", ++ "FROM base" ++ ] ++ in ruleCatchesNot "DL3057" dockerfile ++ ++ it "ok with ending inheritance chain with HEALTCHECK" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch AS base1", ++ "FROM base1 AS base2", ++ "FROM base2 AS base3", ++ "FROM base3 AS end", ++ "HEALTHCHECK NONE" ++ ] ++ in ruleCatchesNot "DL3057" dockerfile ++ ++ it "warn when inheritance chain bifurcates" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch AS base1", ++ "FROM base1 AS base2", ++ "FROM base2 AS base3.1", ++ "FROM base2 AS base3.2", -- This will trigger DL3057 ++ "", ++ "FROM base3.1 AS end1", ++ "HEALTHCHECK NONE", ++ "", ++ "FROM base3.2 AS end2" -- This will trigger DL3057 ++ ] ++ in ruleCatches "DL3057" dockerfile ++ ++ it "warn when not inheriting with no HEALTHCHECK instruction" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch AS base", ++ "HEALTHCHECK CMD /bin/bla", ++ "FROM scratch" ++ ] ++ in ruleCatches "DL3057" dockerfile diff --git a/tasks/hadolint__hadolint-851/solution/solve.sh b/tasks/hadolint__hadolint-851/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-851/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/hadolint__hadolint-851/task.toml b/tasks/hadolint__hadolint-851/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ae31682e999a26544b32471c61b431764ce7cca6 --- /dev/null +++ b/tasks/hadolint__hadolint-851/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-851" +description = "DL3057: fix multiple warnings for multistage builds" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "321ffc1e00b5e97ec6b516775dae32b616fccc33" +reference = "https://github.com/hadolint/hadolint/pull/851" +source_access = "auto" +built_at = "2026-11-16T16:09:53.751209+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f94d93fbf45b6edb39b7a1dea916ad7d631135f75adfb7c9c61ae250a20cc8f1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-07-09T16:36:06Z" +diff_format = "unified" +context_files = [ + "src/Hadolint/Rule/DL3057.hs", + "test/Hadolint/Rule/DL3057Spec.hs", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 112 +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:00.799949+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:886fe9a55d740dc107f770de841f3ceb4ca32c1a42fb56c2c0280cd6b1e728f4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-851/tests/capture.py b/tasks/hadolint__hadolint-851/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-851/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/hadolint__hadolint-851/tests/instruction.md b/tasks/hadolint__hadolint-851/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1ea818691b3c0220582994d3173630526d511b29 --- /dev/null +++ b/tasks/hadolint__hadolint-851/tests/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** DL3057: fix multiple warnings for multistage builds + +## Description + +DL3057 checks that images produced in multistage builds have a +healthcheck (if the rule is enabled). But if one stage already has the +healthcheck instruction, the other stages should not trigger a warning. +If the stage comes earlier, it's obviously not used as a build result, +therefore doesn't need a healthcheck instruction on its own. +If the stage comes later, it will inherit the healthcheck instruction +from the stage that has it. + +This fix works because when a healthcheck is found in a build stage, +that stage is marked as good, but also all stages it inherited from are +also marked as good. Only stages that don't inherit the healthcheck +instruction remain marked as bad, if they don't have the instruction +themselves. Therefore Dockerfiles, which produce multiple images are +also considered. + +fixes: #843 + + +### How to verify it +This does not trigger DL3057 at all anymore: +```Dockerfile +FROM opensuse/leap:15.4 AS base0 +FROM base0 AS base1 +HEALTHCHECK NONE +FROM base1 +``` + +This triggers for the last stage only: +```Dockerfile +FROM opensuse/leap:15.4 AS base0 +FROM base0 AS base1 +FROM base1 AS base2.1 +HEALTHCHECK NONE + +FROM base1 AS base2.2 +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `321ffc1e00b5`. 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/hadolint__hadolint-851/tests/oracle.patch b/tasks/hadolint__hadolint-851/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..295b2d0798ff6468927f3f9235b8e8eb07877f0d --- /dev/null +++ b/tasks/hadolint__hadolint-851/tests/oracle.patch @@ -0,0 +1,157 @@ +diff --git a/src/Hadolint/Rule/DL3057.hs b/src/Hadolint/Rule/DL3057.hs +index d8a4820..bca55a4 100644 +--- a/src/Hadolint/Rule/DL3057.hs ++++ b/src/Hadolint/Rule/DL3057.hs +@@ -8,7 +8,8 @@ import Language.Docker.Syntax + + + data StageID = StageID +- { name :: Text.Text, ++ { src :: Text.Text, ++ name :: Text.Text, + line :: Linenumber + } deriving (Show, Eq, Ord) + +@@ -25,16 +26,24 @@ rule = veryCustomRule check (emptyState Empty) markFailures + message = "`HEALTHCHECK` instruction missing." + + check line state (From BaseImage {image, alias = Just als}) = +- state |> modify (currentStage (imageName image) (StageID (unImageAlias als) line)) ++ state |> modify ++ ( currentStage ++ (imageName image) ++ (StageID (imageName image) (unImageAlias als) line) ++ ) + check line state (From BaseImage {image, alias = Nothing}) = +- state |> modify (currentStage (imageName image) (StageID (imageName image) line)) ++ state |> modify ++ ( currentStage ++ (imageName image) ++ (StageID (imageName image) (imageName image) line) ++ ) + check _ state (Healthcheck _) = state |> modify goodStage + check _ state _ = state + + markFailures :: State Acc -> Failures + markFailures (State fails (Acc _ _ b)) = Set.foldl' (Seq.|>) fails (Set.map makeFail b) + markFailures st = failures st +- makeFail (StageID _ line) = CheckFailure {..} ++ makeFail (StageID _ _ line) = CheckFailure {..} + {-# INLINEABLE rule #-} + + currentStage :: Text.Text -> StageID -> Acc -> Acc +@@ -46,5 +55,29 @@ currentStage src stageid (Acc _ g b) + currentStage _ stageid Empty = Acc stageid Set.empty (Set.singleton stageid) + + goodStage :: Acc -> Acc +-goodStage (Acc stageid g b) = Acc stageid (g |> Set.insert stageid) (b |> Set.delete stageid) ++goodStage (Acc stageid g b) = do ++ let nowGood = recurseGood b stageid ++ let good = ++ g ++ |> Set.union nowGood ++ |> Set.insert stageid ++ bad = ++ b ++ |> flip Set.difference nowGood ++ |> Set.delete stageid ++ in Acc ++ stageid ++ good ++ bad ++ where ++ predicate StageID { src = s1 } StageID { name = n1 } = n1 == s1 ++ ++ recurseGood :: Set.Set StageID -> StageID -> Set.Set StageID ++ recurseGood bad sid = do ++ let g1 = Set.filter (predicate sid) bad -- bad stages to be marked good ++ b1 = Set.difference bad g1 -- bad stages not to be marked good ++ in if Set.null g1 ++ then g1 ++ else Set.union g1 $ Set.unions $ Set.map (recurseGood b1) g1 ++ + goodStage Empty = Empty +diff --git a/test/Hadolint/Rule/DL3057Spec.hs b/test/Hadolint/Rule/DL3057Spec.hs +index 5c04bcf..cb1eba6 100644 +--- a/test/Hadolint/Rule/DL3057Spec.hs ++++ b/test/Hadolint/Rule/DL3057Spec.hs +@@ -1,6 +1,7 @@ + module Hadolint.Rule.DL3057Spec (spec) where + + import Data.Default ++import Data.Text as Text + import Helpers + import Test.Hspec + +@@ -10,11 +11,63 @@ spec = do + let ?config = def + + describe "DL3057 - `HEALTHCHECK instruction missing" $ do +- it "warn with no HEALTHCHECK instructions" $ +- ruleCatches "DL3057" "FROM scratch" +- it "ok with one HEALTHCHECK instruction" $ +- ruleCatchesNot "DL3057" "FROM scratch\nHEALTHCHECK CMD /bin/bla" +- it "ok with inheriting HEALTHCHECK instruction" $ +- ruleCatchesNot "DL3057" "FROM scratch AS base\nHEALTHCHECK CMD /bin/bla\nFROM base" +- it "warn when not inheriting with no HEALTHCHECK instruction" $ +- ruleCatches "DL3057" "FROM scratch AS base\nHEALTHCHECK CMD /bin/bla\nFROM scratch" ++ ++ it "warn with no HEALTHCHECK instructions" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch" ++ ] ++ in ruleCatches "DL3057" dockerfile ++ ++ it "ok when HEALTHCHECK is explicitly disabled" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch", ++ "HEALTHCHECK NONE" ++ ] ++ in ruleCatchesNot "DL3057" dockerfile ++ ++ it "ok with one HEALTHCHECK instruction" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch", ++ "HEALTHCHECK CMD /bin/bla" ++ ] ++ in ruleCatchesNot "DL3057" dockerfile ++ ++ it "ok with inheriting HEALTHCHECK instruction" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch AS base", ++ "HEALTHCHECK CMD /bin/bla", ++ "FROM base" ++ ] ++ in ruleCatchesNot "DL3057" dockerfile ++ ++ it "ok with ending inheritance chain with HEALTCHECK" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch AS base1", ++ "FROM base1 AS base2", ++ "FROM base2 AS base3", ++ "FROM base3 AS end", ++ "HEALTHCHECK NONE" ++ ] ++ in ruleCatchesNot "DL3057" dockerfile ++ ++ it "warn when inheritance chain bifurcates" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch AS base1", ++ "FROM base1 AS base2", ++ "FROM base2 AS base3.1", ++ "FROM base2 AS base3.2", -- This will trigger DL3057 ++ "", ++ "FROM base3.1 AS end1", ++ "HEALTHCHECK NONE", ++ "", ++ "FROM base3.2 AS end2" -- This will trigger DL3057 ++ ] ++ in ruleCatches "DL3057" dockerfile ++ ++ it "warn when not inheriting with no HEALTHCHECK instruction" $ do ++ let dockerfile = Text.unlines ++ [ "FROM scratch AS base", ++ "HEALTHCHECK CMD /bin/bla", ++ "FROM scratch" ++ ] ++ in ruleCatches "DL3057" dockerfile diff --git a/tasks/hadolint__hadolint-851/tests/test.sh b/tasks/hadolint__hadolint-851/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a3c2b2826f7b1f6a893e7a7e895bfee9f36f01f --- /dev/null +++ b/tasks/hadolint__hadolint-851/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 321ffc1e00b5e97ec6b516775dae32b616fccc33 > "$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/hadolint__hadolint-851/tests/verifier.py b/tasks/hadolint__hadolint-851/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-851/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/hadolint__hadolint-852/environment/Dockerfile b/tasks/hadolint__hadolint-852/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b965b856667ecd9eb24b0564edbd3dcc58513502 --- /dev/null +++ b/tasks/hadolint__hadolint-852/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 321ffc1e00b5e97ec6b516775dae32b616fccc33 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 321ffc1e00b5e97ec6b516775dae32b616fccc33 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 321ffc1e00b5e97ec6b516775dae32b616fccc33 \ + && 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/hadolint__hadolint-852/instruction.md b/tasks/hadolint__hadolint-852/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e4b58c802ceb1c2b0b34527c82d08d0429ae6da --- /dev/null +++ b/tasks/hadolint__hadolint-852/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** DL3049: Fix behaviour with multistage builds + +## Description + +- Fix DL3049 behaviour with multistage builds + +In a multistage build, when a stage has an alias, it is reasonable to +assume that it will not be the last stage in the build process. Rather +there will be another stage inheriting or copying from that stage. +Therefore required labels don't necessarily need to be present in the +stage with the alias. + +fixes: #758 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `321ffc1e00b5`. 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/hadolint__hadolint-852/solution/patch.diff b/tasks/hadolint__hadolint-852/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..dcbda53d5ac37fed85dd4e036c4a24a51a26c369 --- /dev/null +++ b/tasks/hadolint__hadolint-852/solution/patch.diff @@ -0,0 +1,200 @@ +diff --git a/src/Hadolint/Rule/DL3049.hs b/src/Hadolint/Rule/DL3049.hs +index d8f358b..8cd1629 100644 +--- a/src/Hadolint/Rule/DL3049.hs ++++ b/src/Hadolint/Rule/DL3049.hs +@@ -1,4 +1,4 @@ +- module Hadolint.Rule.DL3049 (rule) where ++module Hadolint.Rule.DL3049 (rule) where + + import qualified Data.Map as Map + import qualified Data.Set as Set +@@ -12,16 +12,18 @@ rule :: LabelSchema -> Rule args + rule labelschema = mconcat $ fmap missingLabelRule (Map.keys labelschema) + {-# INLINEABLE rule #-} + ++ + data StageID = StageID +- { name :: Text.Text, ++ { name :: BaseImage, + line :: Linenumber + } deriving (Eq, Ord, Show) + + data Acc +- = Acc StageID (Set.Set StageID) (Set.Set StageID) ++ = Acc StageID (Set.Set StageID) (Set.Set StageID) (Set.Set StageID) + | Empty + deriving (Show) + ++ + -- missingLabelRule + -- + -- triggers on a `FROM` instruction when label `label` is not defined within +@@ -32,29 +34,52 @@ missingLabelRule label = veryCustomRule check (emptyState Empty) markFailure + code = "DL3049" + severity = DLInfoC + message = "Label `" <> label <> "` is missing." +- check line state (From BaseImage {image, alias = Just als}) = +- state |> modify (currentStage (imageName image) (StageID (unImageAlias als) line)) +- check line state (From BaseImage {image, alias = Nothing}) = +- state |> modify (currentStage (imageName image) (StageID (imageName image) line)) ++ check line state (From img) = ++ state |> modify (currentStage (StageID img line)) ++ check _ state (Copy (CopyArgs _ _) (CopyFlags _ _ _ (CopySource src))) = ++ state |> modify (markSilentByAlias src) + check _ state (Label pairs) +- | label `elem` fmap fst pairs = state |> modify goodStage +- | otherwise = state ++ | label `elem` fmap fst pairs = ++ state ++ |> modify (markSilentByAlias (getCurrentStageName state)) ++ |> modify markGood ++ | otherwise = state + check _ state _ = state + + markFailure :: State Acc -> Failures +- markFailure (State fails (Acc _ _ b)) = Set.foldl' (Seq.|>) fails (Set.map markFail b) ++ markFailure (State fails (Acc _ _ _ b)) = Set.foldl' (Seq.|>) fails (Set.map markFail b) + markFailure st = failures st + + markFail (StageID _ line) = CheckFailure {..} + +-currentStage :: Text.Text -> StageID -> Acc -> Acc +-currentStage src stageid (Acc _ g b) +- | not $ Set.null (Set.filter (predicate src) g) = Acc stageid (g |> Set.insert stageid) b +- | otherwise = Acc stageid g (b |> Set.insert stageid) ++ ++currentStage :: StageID -> Acc -> Acc ++currentStage stageid Empty = Acc stageid Set.empty Set.empty (Set.singleton stageid) ++currentStage stageid (Acc _ g s b) ++ | not $ Set.null (Set.filter (predicate stageid) g) = ++ Acc stageid (g |> Set.insert stageid) s b ++ | otherwise = Acc stageid g s (b |> Set.insert stageid) ++ where ++ predicate (StageID _ _) (StageID BaseImage {alias = Nothing} _) = False ++ predicate (StageID BaseImage {image} _) (StageID BaseImage {alias = Just als} _) = ++ unImageAlias als == imageName image ++ ++markGood :: Acc -> Acc ++markGood Empty = Empty ++markGood (Acc stageid good silent bad) = ++ Acc stageid (good |> Set.insert stageid) (silent |> Set.delete stageid) (bad |> Set.delete stageid) ++ ++markSilentByAlias :: Text.Text -> Acc -> Acc ++markSilentByAlias _ Empty = Empty ++markSilentByAlias silentname (Acc stageid good silent bad) = ++ Acc stageid good (silent |> Set.union stages) (bad |> remove stages) + where +- predicate n0 StageID {name = n1} = n1 == n0 +-currentStage _ stageid Empty = Acc stageid Set.empty (Set.singleton stageid) ++ stages = Set.filter byName bad ++ byName (StageID BaseImage {alias = Nothing} _) = False ++ byName (StageID BaseImage {alias = Just als} _) = unImageAlias als == silentname ++ remove set fromThis = Set.difference fromThis set + +-goodStage :: Acc -> Acc +-goodStage (Acc stageid g b) = Acc stageid (g |> Set.insert stageid) (b |> Set.delete stageid) +-goodStage Empty = Empty ++getCurrentStageName :: State Acc -> Text.Text ++getCurrentStageName (State _ (Acc (StageID BaseImage {image, alias = Nothing} _) _ _ _)) = imageName image ++getCurrentStageName (State _ (Acc (StageID BaseImage {alias = Just als} _) _ _ _)) = unImageAlias als ++getCurrentStageName _ = "" +diff --git a/test/Hadolint/Rule/DL3049Spec.hs b/test/Hadolint/Rule/DL3049Spec.hs +index dcacf96..263303f 100644 +--- a/test/Hadolint/Rule/DL3049Spec.hs ++++ b/test/Hadolint/Rule/DL3049Spec.hs +@@ -43,6 +43,15 @@ spec = do + in assertChecks + (Text.unlines dockerFile) + (failsWith 2 "DL3049") ++ it "warn once: two stages, label present in first only" $ ++ let dockerFile = ++ [ "FROM baseimage", ++ "LABEL foo=\"bar\"", ++ "FROM newimage" ++ ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 1 "DL3049") + it "warn once: two stages, label present in second only" $ + let dockerFile = + [ "FROM baseimage", +@@ -62,12 +71,39 @@ spec = do + in assertChecks + (Text.unlines dockerFile) + (failsWith 1 "DL3049") +- it "warn once: two stages, inheritance, label only defined in second stage" $ ++ it "warn twice: two stages, inheritance, no labels" $ ++ let dockerFile = ++ [ "FROM baseimage as base", ++ "FROM base" ++ ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 2 "DL3049") ++ it "don't warn: two stages, inheritance, label defined in second stage" $ + let dockerFile = + [ "FROM baseimage as base", + "FROM base", + "LABEL foo=\"bar\"" + ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 0 "DL3049") ++ it "don't warn: two stages, no inheritance, label in last stage, with copy" $ ++ let dockerFile = ++ [ "FROM baseimage as base", ++ "FROM anotherimage", ++ "LABEL foo=\"bar\"", ++ "COPY --from=base /bar /baz" ++ ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 0 "DL3049") ++ it "warn once: two stages, no inheritance, label in last stage, no connection" $ ++ let dockerFile = ++ [ "FROM baseimage as base", ++ "FROM anotherimage", ++ "LABEL foo=\"bar\"" ++ ] + in assertChecks + (Text.unlines dockerFile) + (failsWith 1 "DL3049") +@@ -80,3 +116,38 @@ spec = do + in assertChecks + (Text.unlines dockerFile) + (failsWith 0 "DL3049") ++ it "warn once: multiple results, no inheritance, label in one result" $ ++ let dockerFile = ++ [ "FROM baseimage as base", ++ "FROM newimage", ++ "LABEL foo=\"bar\"", ++ "COPY --from=base /bar /baz", ++ "", ++ "FROM newimage", ++ "COPY --from=base /bar /baz" ++ ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 1 "DL3049") ++ it "warn once: multiple results, inheritance, label in one result" $ ++ let dockerFile = ++ [ "FROM baseimage as base", ++ "FROM base", ++ "LABEL foo=\"bar\"", ++ "", ++ "FROM base" ++ ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 1 "DL3049") ++ it "warn once: multiple results, inheritance, label in one result" $ ++ let dockerFile = ++ [ "FROM baseimage as base", ++ "FROM base", ++ "", ++ "FROM base", ++ "LABEL foo=\"bar\"" ++ ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 1 "DL3049") diff --git a/tasks/hadolint__hadolint-852/solution/solve.sh b/tasks/hadolint__hadolint-852/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-852/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/hadolint__hadolint-852/task.toml b/tasks/hadolint__hadolint-852/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..635e5b41211f90e099e168d99c00e579d8dc5f62 --- /dev/null +++ b/tasks/hadolint__hadolint-852/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-852" +description = "DL3049: Fix behaviour with multistage builds" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "321ffc1e00b5e97ec6b516775dae32b616fccc33" +reference = "https://github.com/hadolint/hadolint/pull/852" +source_access = "auto" +built_at = "2026-11-16T16:09:53.752757+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d30e02df1c885bd972171f4dda6374728b78644b5de19be920cb00ee08bb30e8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-07-09T16:35:33Z" +diff_format = "unified" +context_files = [ + "src/Hadolint/Rule/DL3049.hs", + "test/Hadolint/Rule/DL3049Spec.hs", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 136 +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:00.800405+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:886fe9a55d740dc107f770de841f3ceb4ca32c1a42fb56c2c0280cd6b1e728f4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-852/tests/capture.py b/tasks/hadolint__hadolint-852/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-852/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/hadolint__hadolint-852/tests/instruction.md b/tasks/hadolint__hadolint-852/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e4b58c802ceb1c2b0b34527c82d08d0429ae6da --- /dev/null +++ b/tasks/hadolint__hadolint-852/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** DL3049: Fix behaviour with multistage builds + +## Description + +- Fix DL3049 behaviour with multistage builds + +In a multistage build, when a stage has an alias, it is reasonable to +assume that it will not be the last stage in the build process. Rather +there will be another stage inheriting or copying from that stage. +Therefore required labels don't necessarily need to be present in the +stage with the alias. + +fixes: #758 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `321ffc1e00b5`. 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/hadolint__hadolint-852/tests/oracle.patch b/tasks/hadolint__hadolint-852/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..dcbda53d5ac37fed85dd4e036c4a24a51a26c369 --- /dev/null +++ b/tasks/hadolint__hadolint-852/tests/oracle.patch @@ -0,0 +1,200 @@ +diff --git a/src/Hadolint/Rule/DL3049.hs b/src/Hadolint/Rule/DL3049.hs +index d8f358b..8cd1629 100644 +--- a/src/Hadolint/Rule/DL3049.hs ++++ b/src/Hadolint/Rule/DL3049.hs +@@ -1,4 +1,4 @@ +- module Hadolint.Rule.DL3049 (rule) where ++module Hadolint.Rule.DL3049 (rule) where + + import qualified Data.Map as Map + import qualified Data.Set as Set +@@ -12,16 +12,18 @@ rule :: LabelSchema -> Rule args + rule labelschema = mconcat $ fmap missingLabelRule (Map.keys labelschema) + {-# INLINEABLE rule #-} + ++ + data StageID = StageID +- { name :: Text.Text, ++ { name :: BaseImage, + line :: Linenumber + } deriving (Eq, Ord, Show) + + data Acc +- = Acc StageID (Set.Set StageID) (Set.Set StageID) ++ = Acc StageID (Set.Set StageID) (Set.Set StageID) (Set.Set StageID) + | Empty + deriving (Show) + ++ + -- missingLabelRule + -- + -- triggers on a `FROM` instruction when label `label` is not defined within +@@ -32,29 +34,52 @@ missingLabelRule label = veryCustomRule check (emptyState Empty) markFailure + code = "DL3049" + severity = DLInfoC + message = "Label `" <> label <> "` is missing." +- check line state (From BaseImage {image, alias = Just als}) = +- state |> modify (currentStage (imageName image) (StageID (unImageAlias als) line)) +- check line state (From BaseImage {image, alias = Nothing}) = +- state |> modify (currentStage (imageName image) (StageID (imageName image) line)) ++ check line state (From img) = ++ state |> modify (currentStage (StageID img line)) ++ check _ state (Copy (CopyArgs _ _) (CopyFlags _ _ _ (CopySource src))) = ++ state |> modify (markSilentByAlias src) + check _ state (Label pairs) +- | label `elem` fmap fst pairs = state |> modify goodStage +- | otherwise = state ++ | label `elem` fmap fst pairs = ++ state ++ |> modify (markSilentByAlias (getCurrentStageName state)) ++ |> modify markGood ++ | otherwise = state + check _ state _ = state + + markFailure :: State Acc -> Failures +- markFailure (State fails (Acc _ _ b)) = Set.foldl' (Seq.|>) fails (Set.map markFail b) ++ markFailure (State fails (Acc _ _ _ b)) = Set.foldl' (Seq.|>) fails (Set.map markFail b) + markFailure st = failures st + + markFail (StageID _ line) = CheckFailure {..} + +-currentStage :: Text.Text -> StageID -> Acc -> Acc +-currentStage src stageid (Acc _ g b) +- | not $ Set.null (Set.filter (predicate src) g) = Acc stageid (g |> Set.insert stageid) b +- | otherwise = Acc stageid g (b |> Set.insert stageid) ++ ++currentStage :: StageID -> Acc -> Acc ++currentStage stageid Empty = Acc stageid Set.empty Set.empty (Set.singleton stageid) ++currentStage stageid (Acc _ g s b) ++ | not $ Set.null (Set.filter (predicate stageid) g) = ++ Acc stageid (g |> Set.insert stageid) s b ++ | otherwise = Acc stageid g s (b |> Set.insert stageid) ++ where ++ predicate (StageID _ _) (StageID BaseImage {alias = Nothing} _) = False ++ predicate (StageID BaseImage {image} _) (StageID BaseImage {alias = Just als} _) = ++ unImageAlias als == imageName image ++ ++markGood :: Acc -> Acc ++markGood Empty = Empty ++markGood (Acc stageid good silent bad) = ++ Acc stageid (good |> Set.insert stageid) (silent |> Set.delete stageid) (bad |> Set.delete stageid) ++ ++markSilentByAlias :: Text.Text -> Acc -> Acc ++markSilentByAlias _ Empty = Empty ++markSilentByAlias silentname (Acc stageid good silent bad) = ++ Acc stageid good (silent |> Set.union stages) (bad |> remove stages) + where +- predicate n0 StageID {name = n1} = n1 == n0 +-currentStage _ stageid Empty = Acc stageid Set.empty (Set.singleton stageid) ++ stages = Set.filter byName bad ++ byName (StageID BaseImage {alias = Nothing} _) = False ++ byName (StageID BaseImage {alias = Just als} _) = unImageAlias als == silentname ++ remove set fromThis = Set.difference fromThis set + +-goodStage :: Acc -> Acc +-goodStage (Acc stageid g b) = Acc stageid (g |> Set.insert stageid) (b |> Set.delete stageid) +-goodStage Empty = Empty ++getCurrentStageName :: State Acc -> Text.Text ++getCurrentStageName (State _ (Acc (StageID BaseImage {image, alias = Nothing} _) _ _ _)) = imageName image ++getCurrentStageName (State _ (Acc (StageID BaseImage {alias = Just als} _) _ _ _)) = unImageAlias als ++getCurrentStageName _ = "" +diff --git a/test/Hadolint/Rule/DL3049Spec.hs b/test/Hadolint/Rule/DL3049Spec.hs +index dcacf96..263303f 100644 +--- a/test/Hadolint/Rule/DL3049Spec.hs ++++ b/test/Hadolint/Rule/DL3049Spec.hs +@@ -43,6 +43,15 @@ spec = do + in assertChecks + (Text.unlines dockerFile) + (failsWith 2 "DL3049") ++ it "warn once: two stages, label present in first only" $ ++ let dockerFile = ++ [ "FROM baseimage", ++ "LABEL foo=\"bar\"", ++ "FROM newimage" ++ ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 1 "DL3049") + it "warn once: two stages, label present in second only" $ + let dockerFile = + [ "FROM baseimage", +@@ -62,12 +71,39 @@ spec = do + in assertChecks + (Text.unlines dockerFile) + (failsWith 1 "DL3049") +- it "warn once: two stages, inheritance, label only defined in second stage" $ ++ it "warn twice: two stages, inheritance, no labels" $ ++ let dockerFile = ++ [ "FROM baseimage as base", ++ "FROM base" ++ ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 2 "DL3049") ++ it "don't warn: two stages, inheritance, label defined in second stage" $ + let dockerFile = + [ "FROM baseimage as base", + "FROM base", + "LABEL foo=\"bar\"" + ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 0 "DL3049") ++ it "don't warn: two stages, no inheritance, label in last stage, with copy" $ ++ let dockerFile = ++ [ "FROM baseimage as base", ++ "FROM anotherimage", ++ "LABEL foo=\"bar\"", ++ "COPY --from=base /bar /baz" ++ ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 0 "DL3049") ++ it "warn once: two stages, no inheritance, label in last stage, no connection" $ ++ let dockerFile = ++ [ "FROM baseimage as base", ++ "FROM anotherimage", ++ "LABEL foo=\"bar\"" ++ ] + in assertChecks + (Text.unlines dockerFile) + (failsWith 1 "DL3049") +@@ -80,3 +116,38 @@ spec = do + in assertChecks + (Text.unlines dockerFile) + (failsWith 0 "DL3049") ++ it "warn once: multiple results, no inheritance, label in one result" $ ++ let dockerFile = ++ [ "FROM baseimage as base", ++ "FROM newimage", ++ "LABEL foo=\"bar\"", ++ "COPY --from=base /bar /baz", ++ "", ++ "FROM newimage", ++ "COPY --from=base /bar /baz" ++ ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 1 "DL3049") ++ it "warn once: multiple results, inheritance, label in one result" $ ++ let dockerFile = ++ [ "FROM baseimage as base", ++ "FROM base", ++ "LABEL foo=\"bar\"", ++ "", ++ "FROM base" ++ ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 1 "DL3049") ++ it "warn once: multiple results, inheritance, label in one result" $ ++ let dockerFile = ++ [ "FROM baseimage as base", ++ "FROM base", ++ "", ++ "FROM base", ++ "LABEL foo=\"bar\"" ++ ] ++ in assertChecks ++ (Text.unlines dockerFile) ++ (failsWith 1 "DL3049") diff --git a/tasks/hadolint__hadolint-852/tests/test.sh b/tasks/hadolint__hadolint-852/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a3c2b2826f7b1f6a893e7a7e895bfee9f36f01f --- /dev/null +++ b/tasks/hadolint__hadolint-852/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 321ffc1e00b5e97ec6b516775dae32b616fccc33 > "$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/hadolint__hadolint-852/tests/verifier.py b/tasks/hadolint__hadolint-852/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-852/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/hadolint__hadolint-867/environment/Dockerfile b/tasks/hadolint__hadolint-867/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..95cd6092444c6cd3d0a9d75321fa9c9d3452d8ba --- /dev/null +++ b/tasks/hadolint__hadolint-867/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9b380653b78fbea928af9210cb3823a3e0dfe130 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9b380653b78fbea928af9210cb3823a3e0dfe130 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9b380653b78fbea928af9210cb3823a3e0dfe130 \ + && 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/hadolint__hadolint-867/instruction.md b/tasks/hadolint__hadolint-867/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7ae59ed4e53a3a7febd1cf0e6d7a50f221d0f47a --- /dev/null +++ b/tasks/hadolint__hadolint-867/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(DL3029): allow BUILDPLATFORM and TARGETPLATFORM variables + +## Description + +### What I did + +Allowed `BUILDPLATFORM` and `TARGETPLATFORM` in `FROM --plaform=` + +### How I did it + +Updated the existing rule to check if the value contains one of the variables. This is the lazy way without getting into complex regex. + +### How to verify it + +I added new tests, but I have not been able to run anything. I tried to use `nix-shell` to get a development environment, but the compilation is never ending. This is also my first time touching Haskell code, so I barely understand a quarter of the changes I made :sweat_smile: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9b380653b78f`. 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/hadolint__hadolint-867/solution/patch.diff b/tasks/hadolint__hadolint-867/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bc4de8c7195733c24d057538041aadd9c6fa3f4e --- /dev/null +++ b/tasks/hadolint__hadolint-867/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/src/Hadolint/Rule/DL3029.hs b/src/Hadolint/Rule/DL3029.hs +index 1dea33d..dca0cb7 100644 +--- a/src/Hadolint/Rule/DL3029.hs ++++ b/src/Hadolint/Rule/DL3029.hs +@@ -1,5 +1,6 @@ + module Hadolint.Rule.DL3029 (rule) where + ++import qualified Data.Text as Text + import Hadolint.Rule + import Language.Docker.Syntax + +@@ -10,6 +11,6 @@ rule = simpleRule code severity message check + severity = DLWarningC + message = "Do not use --platform flag with FROM" + +- check (From BaseImage {platform = Just p}) = p == "$BUILDPLATFORM" ++ check (From BaseImage {platform = Just p}) = "BUILDPLATFORM" `Text.isInfixOf` p || "TARGETPLATFORM" `Text.isInfixOf` p + check _ = True + {-# INLINEABLE rule #-} +diff --git a/test/Hadolint/Rule/DL3029Spec.hs b/test/Hadolint/Rule/DL3029Spec.hs +index 6589859..efa6bb2 100644 +--- a/test/Hadolint/Rule/DL3029Spec.hs ++++ b/test/Hadolint/Rule/DL3029Spec.hs +@@ -12,4 +12,9 @@ spec = do + describe "DL3029 - Do not use --platform flag with FROM." $ do + it "explicit platform flag" $ ruleCatches "DL3029" "FROM --platform=linux debian:jessie" + it "no platform flag" $ ruleCatchesNot "DL3029" "FROM debian:jessie" +- it "allow platform $BUILDPLATFORM flag" $ ruleCatchesNot "DL3029" "FROM --platform=$BUILDPLATFORM debian:jessie" ++ it "allows platform $BUILDPLATFORM flag" $ ruleCatchesNot "DL3029" "FROM --platform=$BUILDPLATFORM debian:jessie" ++ it "allows platform \"$BUILDPLATFORM\" flag" $ ruleCatchesNot "DL3029" "FROM --platform=\"$BUILDPLATFORM\" debian:jessie" ++ it "allows platform ${BUILDPLATFORM} flag" $ ruleCatchesNot "DL3029" "FROM --platform=${BUILDPLATFORM} debian:jessie" ++ it "allows platform ${BUILDPLATFORM:-} flag" $ ruleCatchesNot "DL3029" "FROM --platform=${BUILDPLATFORM:-} debian:jessie" ++ it "allows platform \"${BUILDPLATFORM:-}\" flag" $ ruleCatchesNot "DL3029" "FROM --platform=\"${BUILDPLATFORM:-}\" debian:jessie" ++ it "allows platform $TARGETPLATFORM flag" $ ruleCatchesNot "DL3029" "FROM --platform=$TARGETPLATFORM debian:jessie" diff --git a/tasks/hadolint__hadolint-867/solution/solve.sh b/tasks/hadolint__hadolint-867/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-867/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/hadolint__hadolint-867/task.toml b/tasks/hadolint__hadolint-867/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..084fd8c361f22891a9fd157d7ffa5f2b1559ded0 --- /dev/null +++ b/tasks/hadolint__hadolint-867/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-867" +description = "fix(DL3029): allow BUILDPLATFORM and TARGETPLATFORM variables" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "9b380653b78fbea928af9210cb3823a3e0dfe130" +reference = "https://github.com/hadolint/hadolint/pull/867" +source_access = "auto" +built_at = "2026-11-16T16:09:53.727712+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2aebd34b41ba45caf5c524a0999de9882ccb93345fcd6c2aae69cd6bab6676bb" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-11-07T10:09:56Z" +diff_format = "unified" +context_files = [ + "src/Hadolint/Rule/DL3029.hs", + "test/Hadolint/Rule/DL3029Spec.hs", +] +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:00.800858+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:805c3691c4b81c4a537371f786137ebd77e68b7524be144fedada9a1fd67f332" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-867/tests/capture.py b/tasks/hadolint__hadolint-867/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-867/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/hadolint__hadolint-867/tests/instruction.md b/tasks/hadolint__hadolint-867/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7ae59ed4e53a3a7febd1cf0e6d7a50f221d0f47a --- /dev/null +++ b/tasks/hadolint__hadolint-867/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(DL3029): allow BUILDPLATFORM and TARGETPLATFORM variables + +## Description + +### What I did + +Allowed `BUILDPLATFORM` and `TARGETPLATFORM` in `FROM --plaform=` + +### How I did it + +Updated the existing rule to check if the value contains one of the variables. This is the lazy way without getting into complex regex. + +### How to verify it + +I added new tests, but I have not been able to run anything. I tried to use `nix-shell` to get a development environment, but the compilation is never ending. This is also my first time touching Haskell code, so I barely understand a quarter of the changes I made :sweat_smile: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9b380653b78f`. 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/hadolint__hadolint-867/tests/oracle.patch b/tasks/hadolint__hadolint-867/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..bc4de8c7195733c24d057538041aadd9c6fa3f4e --- /dev/null +++ b/tasks/hadolint__hadolint-867/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/src/Hadolint/Rule/DL3029.hs b/src/Hadolint/Rule/DL3029.hs +index 1dea33d..dca0cb7 100644 +--- a/src/Hadolint/Rule/DL3029.hs ++++ b/src/Hadolint/Rule/DL3029.hs +@@ -1,5 +1,6 @@ + module Hadolint.Rule.DL3029 (rule) where + ++import qualified Data.Text as Text + import Hadolint.Rule + import Language.Docker.Syntax + +@@ -10,6 +11,6 @@ rule = simpleRule code severity message check + severity = DLWarningC + message = "Do not use --platform flag with FROM" + +- check (From BaseImage {platform = Just p}) = p == "$BUILDPLATFORM" ++ check (From BaseImage {platform = Just p}) = "BUILDPLATFORM" `Text.isInfixOf` p || "TARGETPLATFORM" `Text.isInfixOf` p + check _ = True + {-# INLINEABLE rule #-} +diff --git a/test/Hadolint/Rule/DL3029Spec.hs b/test/Hadolint/Rule/DL3029Spec.hs +index 6589859..efa6bb2 100644 +--- a/test/Hadolint/Rule/DL3029Spec.hs ++++ b/test/Hadolint/Rule/DL3029Spec.hs +@@ -12,4 +12,9 @@ spec = do + describe "DL3029 - Do not use --platform flag with FROM." $ do + it "explicit platform flag" $ ruleCatches "DL3029" "FROM --platform=linux debian:jessie" + it "no platform flag" $ ruleCatchesNot "DL3029" "FROM debian:jessie" +- it "allow platform $BUILDPLATFORM flag" $ ruleCatchesNot "DL3029" "FROM --platform=$BUILDPLATFORM debian:jessie" ++ it "allows platform $BUILDPLATFORM flag" $ ruleCatchesNot "DL3029" "FROM --platform=$BUILDPLATFORM debian:jessie" ++ it "allows platform \"$BUILDPLATFORM\" flag" $ ruleCatchesNot "DL3029" "FROM --platform=\"$BUILDPLATFORM\" debian:jessie" ++ it "allows platform ${BUILDPLATFORM} flag" $ ruleCatchesNot "DL3029" "FROM --platform=${BUILDPLATFORM} debian:jessie" ++ it "allows platform ${BUILDPLATFORM:-} flag" $ ruleCatchesNot "DL3029" "FROM --platform=${BUILDPLATFORM:-} debian:jessie" ++ it "allows platform \"${BUILDPLATFORM:-}\" flag" $ ruleCatchesNot "DL3029" "FROM --platform=\"${BUILDPLATFORM:-}\" debian:jessie" ++ it "allows platform $TARGETPLATFORM flag" $ ruleCatchesNot "DL3029" "FROM --platform=$TARGETPLATFORM debian:jessie" diff --git a/tasks/hadolint__hadolint-867/tests/test.sh b/tasks/hadolint__hadolint-867/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..98e08007d80a388117a197adaaf28bcaa44dec7d --- /dev/null +++ b/tasks/hadolint__hadolint-867/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 9b380653b78fbea928af9210cb3823a3e0dfe130 > "$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/hadolint__hadolint-867/tests/verifier.py b/tasks/hadolint__hadolint-867/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-867/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/hadolint__hadolint-869/environment/Dockerfile b/tasks/hadolint__hadolint-869/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..95cd6092444c6cd3d0a9d75321fa9c9d3452d8ba --- /dev/null +++ b/tasks/hadolint__hadolint-869/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9b380653b78fbea928af9210cb3823a3e0dfe130 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9b380653b78fbea928af9210cb3823a3e0dfe130 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9b380653b78fbea928af9210cb3823a3e0dfe130 \ + && 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/hadolint__hadolint-869/instruction.md b/tasks/hadolint__hadolint-869/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..82512562df354f53345b02c2167e0fc0d673d833 --- /dev/null +++ b/tasks/hadolint__hadolint-869/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** release: create checksums for release artifacts + +## Description + +Create and release sha256 checksums for binary releases. + +fixes: #856 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9b380653b78f`. 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/hadolint__hadolint-869/solution/patch.diff b/tasks/hadolint__hadolint-869/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..95768cd066e3027a461e18f84b74baa5e2479a31 --- /dev/null +++ b/tasks/hadolint__hadolint-869/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index 9a6c1a3..fdc469d 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -312,14 +312,18 @@ jobs: + name: hadolint-Windows-x86_64.exe + path: artifacts/hadolint-Windows-x86_64.exe + +- - name: Rename ++ - name: Rename and Checksum + run: | + mv artifacts/hadolint-Linux-x86_64/hadolint hadolint-Linux-x86_64 + mv artifacts/hadolint-Linux-arm64/hadolint hadolint-Linux-arm64 +- + mv artifacts/hadolint-Darwin-x86_64/hadolint hadolint-Darwin-x86_64 + mv artifacts/hadolint-Windows-x86_64.exe/hadolint.exe hadolint-Windows-x86_64.exe + ++ sha256sum -b hadolint-Linux-x86_64 > hadolint-Linux-x86_64.sha256 ++ sha256sum -b hadolint-Linux-arm64 > hadolint-Linux-arm64.sha256 ++ sha256sum -b hadolint-Darwin-x86_64 > hadolint-Darwin-x86_64.sha256 ++ sha256sum -b hadolint-Windows-x86_64.exe > hadolint-Windows-x86_64.exe.sha256 ++ + - name: Release + uses: softprops/action-gh-release@v1 + if: startsWith(github.ref, 'refs/tags/') +@@ -328,6 +332,10 @@ jobs: + fail_on_unmatched_files: true + files: | + hadolint-Linux-x86_64 ++ hadolint-Linux-x86_64.sha256 + hadolint-Linux-arm64 ++ hadolint-Linux-arm64.sha256 + hadolint-Darwin-x86_64 ++ hadolint-Darwin-x86_64.sha256 + hadolint-Windows-x86_64.exe ++ hadolint-Windows-x86_64.exe.sha256 diff --git a/tasks/hadolint__hadolint-869/solution/solve.sh b/tasks/hadolint__hadolint-869/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-869/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/hadolint__hadolint-869/task.toml b/tasks/hadolint__hadolint-869/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09a1a0293b039979ec3ca73c6a7affd3d4a39a8f --- /dev/null +++ b/tasks/hadolint__hadolint-869/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-869" +description = "release: create checksums for release artifacts" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "9b380653b78fbea928af9210cb3823a3e0dfe130" +reference = "https://github.com/hadolint/hadolint/pull/869" +source_access = "auto" +built_at = "2026-11-16T16:09:53.732455+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ef424f7626a054a714fd24be10cee7b27ee341f3c394a231b36b07957e409835" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-09-07T07:08:53Z" +diff_format = "unified" +context_files = [ + ".github/workflows/release.yml", +] +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:00.801316+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:805c3691c4b81c4a537371f786137ebd77e68b7524be144fedada9a1fd67f332" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-869/tests/capture.py b/tasks/hadolint__hadolint-869/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-869/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/hadolint__hadolint-869/tests/instruction.md b/tasks/hadolint__hadolint-869/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..82512562df354f53345b02c2167e0fc0d673d833 --- /dev/null +++ b/tasks/hadolint__hadolint-869/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** release: create checksums for release artifacts + +## Description + +Create and release sha256 checksums for binary releases. + +fixes: #856 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9b380653b78f`. 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/hadolint__hadolint-869/tests/oracle.patch b/tasks/hadolint__hadolint-869/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..95768cd066e3027a461e18f84b74baa5e2479a31 --- /dev/null +++ b/tasks/hadolint__hadolint-869/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index 9a6c1a3..fdc469d 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -312,14 +312,18 @@ jobs: + name: hadolint-Windows-x86_64.exe + path: artifacts/hadolint-Windows-x86_64.exe + +- - name: Rename ++ - name: Rename and Checksum + run: | + mv artifacts/hadolint-Linux-x86_64/hadolint hadolint-Linux-x86_64 + mv artifacts/hadolint-Linux-arm64/hadolint hadolint-Linux-arm64 +- + mv artifacts/hadolint-Darwin-x86_64/hadolint hadolint-Darwin-x86_64 + mv artifacts/hadolint-Windows-x86_64.exe/hadolint.exe hadolint-Windows-x86_64.exe + ++ sha256sum -b hadolint-Linux-x86_64 > hadolint-Linux-x86_64.sha256 ++ sha256sum -b hadolint-Linux-arm64 > hadolint-Linux-arm64.sha256 ++ sha256sum -b hadolint-Darwin-x86_64 > hadolint-Darwin-x86_64.sha256 ++ sha256sum -b hadolint-Windows-x86_64.exe > hadolint-Windows-x86_64.exe.sha256 ++ + - name: Release + uses: softprops/action-gh-release@v1 + if: startsWith(github.ref, 'refs/tags/') +@@ -328,6 +332,10 @@ jobs: + fail_on_unmatched_files: true + files: | + hadolint-Linux-x86_64 ++ hadolint-Linux-x86_64.sha256 + hadolint-Linux-arm64 ++ hadolint-Linux-arm64.sha256 + hadolint-Darwin-x86_64 ++ hadolint-Darwin-x86_64.sha256 + hadolint-Windows-x86_64.exe ++ hadolint-Windows-x86_64.exe.sha256 diff --git a/tasks/hadolint__hadolint-869/tests/test.sh b/tasks/hadolint__hadolint-869/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..98e08007d80a388117a197adaaf28bcaa44dec7d --- /dev/null +++ b/tasks/hadolint__hadolint-869/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 9b380653b78fbea928af9210cb3823a3e0dfe130 > "$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/hadolint__hadolint-869/tests/verifier.py b/tasks/hadolint__hadolint-869/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-869/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/hadolint__hadolint-871/environment/Dockerfile b/tasks/hadolint__hadolint-871/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..95cd6092444c6cd3d0a9d75321fa9c9d3452d8ba --- /dev/null +++ b/tasks/hadolint__hadolint-871/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9b380653b78fbea928af9210cb3823a3e0dfe130 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9b380653b78fbea928af9210cb3823a3e0dfe130 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9b380653b78fbea928af9210cb3823a3e0dfe130 \ + && 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/hadolint__hadolint-871/instruction.md b/tasks/hadolint__hadolint-871/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..99e8420a4c5d5b38bf046b0ec8b271e39a4ec538 --- /dev/null +++ b/tasks/hadolint__hadolint-871/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** feature: global ignore pragma + +## Description + +Add global variant of the ignore pragma. This allows users to disable rules for the whole dockerfile by using a pragma like: + +```dockerfile +# hadolint global ignore=DL3003,SC2035 +``` + +### What I did +- add file-global variant of the ignore pragma +- clean up the pragma parsing code + +### How I did it +The file global ignore pragma works almost like the inline ignore pragma. The difference is that it parses into just a set of rules to ignore instead of a map from line-numbers to sets of rules to ignore. Consequently there is no check for line numbers when deciding if a check-failure should be ignored or propagated, all that matters is if that failures code is in that global set of rule codes to ignore. + +### How to verify it +The following Dockerfile should not trigger any of the globally ignored rules, but will still trigger all other rules just normal: + +```Dockerfile +# hadolint global ignore=DL3002 +FROM alpine +USER root +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9b380653b78f`. 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/hadolint__hadolint-871/solution/patch.diff b/tasks/hadolint__hadolint-871/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9cddafdcd53dc24baa3ab23deb413e98b29ec2e2 --- /dev/null +++ b/tasks/hadolint__hadolint-871/solution/patch.diff @@ -0,0 +1,213 @@ +diff --git a/README.md b/README.md +index 047695a..48e5a3f 100644 +--- a/README.md ++++ b/README.md +@@ -333,6 +333,19 @@ RUN cd /tmp && echo "hello!" + + The comment "inline ignores" applies only to the statement following it. + ++## Global ignores ++ ++Rules can also be ignored on a per-file basis using the global ignore pragma. ++It works just like inline ignores, excep that it applies to the whole file ++instead of just the next line. ++ ++```dockerfile ++# hadolint global ignore=DL3003,DL3006,SC1035 ++FROM ubuntu ++ ++RUN cd /tmp && echo "foo" ++``` ++ + ## Linting Labels + + Hadolint is able to check if specific labels are present and conform +diff --git a/src/Hadolint/Pragma.hs b/src/Hadolint/Pragma.hs +index f50fde2..8baa5be 100644 +--- a/src/Hadolint/Pragma.hs ++++ b/src/Hadolint/Pragma.hs +@@ -1,5 +1,6 @@ + module Hadolint.Pragma + ( ignored, ++ globalIgnored, + parseIgnorePragma, + parseShell + ) +@@ -26,19 +27,32 @@ ignored = Foldl.Fold parse mempty id + _ -> acc + parse acc _ = acc + ++globalIgnored :: Foldl.Fold (InstructionPos Text) (Set.Set RuleCode) ++globalIgnored = Foldl.Fold parse mempty id ++ where ++ parse acc InstructionPos { instruction = Comment comment } = ++ case parseGlobalIgnorePragma comment of ++ Just ignores@(_ : _) -> Set.union ( Set.fromList . fmap RuleCode $ ignores ) acc ++ _ -> acc ++ parse acc _ = acc ++ + parseIgnorePragma :: Text -> Maybe [Text] +-parseIgnorePragma = +- Megaparsec.parseMaybe commentParser +- +-commentParser :: Megaparsec.Parsec Void Text [Text] +-commentParser = +- do +- spaces +- >> string "hadolint" +- >> spaces1 +- >> string "ignore=" +- >> spaces +- >> Megaparsec.sepBy1 ruleName (spaces >> string "," >> spaces) ++parseIgnorePragma = Megaparsec.parseMaybe ignoreParser ++ ++parseGlobalIgnorePragma :: Text -> Maybe [Text] ++parseGlobalIgnorePragma = Megaparsec.parseMaybe globalIgnoreParser ++ ++ignoreParser :: Megaparsec.Parsec Void Text [Text] ++ignoreParser = hadolintPragma >> ignore ++ ++globalIgnoreParser :: Megaparsec.Parsec Void Text [Text] ++globalIgnoreParser = hadolintPragma >> string "global" >> spaces1 >> ignore ++ ++ignore :: Megaparsec.Parsec Void Text [Text] ++ignore = string "ignore" >> spaces >> string "=" >> spaces >> ruleList ++ ++ruleList :: Megaparsec.Parsec Void Text [Text] ++ruleList = Megaparsec.sepBy1 ruleName ( spaces >> string "," >> spaces ) + + ruleName :: Megaparsec.ParsecT Void Text Identity (Megaparsec.Tokens Text) + ruleName = Megaparsec.takeWhile1P Nothing (\c -> c `elem` Set.fromList "DLSC0123456789") +@@ -48,21 +62,16 @@ parseShell :: Text -> Maybe Text + parseShell = Megaparsec.parseMaybe shellParser + + shellParser :: Megaparsec.Parsec Void Text Text +-shellParser = +- do +- spaces +- >> string "hadolint" +- >> spaces1 +- >> string "shell" +- >> spaces +- >> string "=" +- >> spaces +- >> shellName ++shellParser = hadolintPragma >> string "shell" >> spaces >> string "=" >> spaces >> shellName + + shellName :: Megaparsec.ParsecT Void Text Identity (Megaparsec.Tokens Text) + shellName = Megaparsec.takeWhile1P Nothing (/= '\n') + + ++hadolintPragma :: Megaparsec.Parsec Void Text Text ++hadolintPragma = spaces >> string "hadolint" >> spaces1 ++ ++ + string :: Megaparsec.Tokens Text + -> Megaparsec.ParsecT Void Text Identity (Megaparsec.Tokens Text) + string = Megaparsec.string +diff --git a/src/Hadolint/Process.hs b/src/Hadolint/Process.hs +index ec6fb4b..3d3c682 100644 +--- a/src/Hadolint/Process.hs ++++ b/src/Hadolint/Process.hs +@@ -82,6 +82,8 @@ import qualified Hadolint.Shell as Shell + data AnalisisResult = AnalisisResult + { -- | The set of ignored rules per line + ignored :: SMap.IntMap (Set.Set RuleCode), ++ -- | The set of globally ignored rules ++ globalIgnored :: Set.Set RuleCode, + -- | A set of failures collected for reach rule + failed :: Failures + } +@@ -93,6 +95,7 @@ run config dockerfile = Seq.filter shouldKeep failed + + shouldKeep CheckFailure {line, code} + | disableIgnorePragma config = True ++ | code `Set.member` globalIgnored = False + | otherwise = Just True /= do + ignoreList <- SMap.lookup line ignored + return $ code `Set.member` ignoreList +@@ -103,6 +106,7 @@ analyze :: + analyze config = + AnalisisResult + <$> Hadolint.Pragma.ignored ++ <*> Hadolint.Pragma.globalIgnored + <*> Foldl.premap parseShell (failures config) + + parseShell :: InstructionPos Text.Text -> InstructionPos Shell.ParsedShell +diff --git a/test/Hadolint/PragmaSpec.hs b/test/Hadolint/PragmaSpec.hs +index a3e4485..e9325f7 100644 +--- a/test/Hadolint/PragmaSpec.hs ++++ b/test/Hadolint/PragmaSpec.hs +@@ -11,6 +11,7 @@ spec = do + let ?config = def + + describe "Rules can be ignored with inline comments" $ do ++ + it "ignores single rule" $ + let dockerFile = + [ "FROM ubuntu", +@@ -18,6 +19,7 @@ spec = do + "USER root" + ] + in ruleCatchesNot "DL3002" $ Text.unlines dockerFile ++ + it "ignores only the given rule" $ + let dockerFile = + [ "FROM scratch", +@@ -25,6 +27,7 @@ spec = do + "USER root" + ] + in ruleCatches "DL3002" $ Text.unlines dockerFile ++ + it "ignores only the given rule, when multiple passed" $ + let dockerFile = + [ "FROM scratch", +@@ -32,6 +35,7 @@ spec = do + "USER root" + ] + in ruleCatchesNot "DL3002" $ Text.unlines dockerFile ++ + it "ignores the rule only if directly above the instruction" $ + let dockerFile = + [ "# hadolint ignore=DL3001,DL3002", +@@ -39,6 +43,7 @@ spec = do + "USER root" + ] + in ruleCatches "DL3002" $ Text.unlines dockerFile ++ + it "won't ignore the rule if passed invalid rule names" $ + let dockerFile = + [ "FROM scratch", +@@ -46,6 +51,7 @@ spec = do + "USER root" + ] + in ruleCatches "DL3002" $ Text.unlines dockerFile ++ + it "ignores multiple rules correctly, even with some extra whitespace" $ + let dockerFile = + [ "FROM node as foo", +@@ -55,3 +61,24 @@ spec = do + in do + ruleCatchesNot "DL3023" $ Text.unlines dockerFile + ruleCatchesNot "DL3021" $ Text.unlines dockerFile ++ ++ ++ describe "Rules can be ignored globally with global ignore pragma" $ do ++ ++ it "ignores single rule" $ ++ let dockerFile = ++ [ "# hadolint global ignore=DL3002", ++ "FROM ubuntu", ++ "USER root" ++ ] ++ in ruleCatchesNot "DL3002" $ Text.unlines dockerFile ++ ++ it "ignores multiple rules correctly, even with some extra whitespace" $ ++ let dockerFile = ++ [ "# hadolint global ignore = DL3023 , DL3021", ++ "FROM node as foo", ++ "COPY --from=foo bar baz ." ++ ] ++ in do ++ ruleCatchesNot "DL3023" $ Text.unlines dockerFile ++ ruleCatchesNot "DL3021" $ Text.unlines dockerFile diff --git a/tasks/hadolint__hadolint-871/solution/solve.sh b/tasks/hadolint__hadolint-871/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-871/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/hadolint__hadolint-871/task.toml b/tasks/hadolint__hadolint-871/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6f2e3541fde7aa33caf8f3d9b9754a2e26c10b66 --- /dev/null +++ b/tasks/hadolint__hadolint-871/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-871" +description = "feature: global ignore pragma" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "9b380653b78fbea928af9210cb3823a3e0dfe130" +reference = "https://github.com/hadolint/hadolint/pull/871" +source_access = "auto" +built_at = "2026-11-16T16:09:53.729219+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3e048995b145ccf061d89ca428324e1c83c9f496270599f1c9eb58931e3d368c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-11-07T09:41:09Z" +diff_format = "unified" +context_files = [ + "README.md", + "src/Hadolint/Pragma.hs", + "src/Hadolint/Process.hs", + "test/Hadolint/PragmaSpec.hs", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 97 +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:00.801778+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:805c3691c4b81c4a537371f786137ebd77e68b7524be144fedada9a1fd67f332" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-871/tests/capture.py b/tasks/hadolint__hadolint-871/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-871/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/hadolint__hadolint-871/tests/instruction.md b/tasks/hadolint__hadolint-871/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..99e8420a4c5d5b38bf046b0ec8b271e39a4ec538 --- /dev/null +++ b/tasks/hadolint__hadolint-871/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** feature: global ignore pragma + +## Description + +Add global variant of the ignore pragma. This allows users to disable rules for the whole dockerfile by using a pragma like: + +```dockerfile +# hadolint global ignore=DL3003,SC2035 +``` + +### What I did +- add file-global variant of the ignore pragma +- clean up the pragma parsing code + +### How I did it +The file global ignore pragma works almost like the inline ignore pragma. The difference is that it parses into just a set of rules to ignore instead of a map from line-numbers to sets of rules to ignore. Consequently there is no check for line numbers when deciding if a check-failure should be ignored or propagated, all that matters is if that failures code is in that global set of rule codes to ignore. + +### How to verify it +The following Dockerfile should not trigger any of the globally ignored rules, but will still trigger all other rules just normal: + +```Dockerfile +# hadolint global ignore=DL3002 +FROM alpine +USER root +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9b380653b78f`. 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/hadolint__hadolint-871/tests/oracle.patch b/tasks/hadolint__hadolint-871/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9cddafdcd53dc24baa3ab23deb413e98b29ec2e2 --- /dev/null +++ b/tasks/hadolint__hadolint-871/tests/oracle.patch @@ -0,0 +1,213 @@ +diff --git a/README.md b/README.md +index 047695a..48e5a3f 100644 +--- a/README.md ++++ b/README.md +@@ -333,6 +333,19 @@ RUN cd /tmp && echo "hello!" + + The comment "inline ignores" applies only to the statement following it. + ++## Global ignores ++ ++Rules can also be ignored on a per-file basis using the global ignore pragma. ++It works just like inline ignores, excep that it applies to the whole file ++instead of just the next line. ++ ++```dockerfile ++# hadolint global ignore=DL3003,DL3006,SC1035 ++FROM ubuntu ++ ++RUN cd /tmp && echo "foo" ++``` ++ + ## Linting Labels + + Hadolint is able to check if specific labels are present and conform +diff --git a/src/Hadolint/Pragma.hs b/src/Hadolint/Pragma.hs +index f50fde2..8baa5be 100644 +--- a/src/Hadolint/Pragma.hs ++++ b/src/Hadolint/Pragma.hs +@@ -1,5 +1,6 @@ + module Hadolint.Pragma + ( ignored, ++ globalIgnored, + parseIgnorePragma, + parseShell + ) +@@ -26,19 +27,32 @@ ignored = Foldl.Fold parse mempty id + _ -> acc + parse acc _ = acc + ++globalIgnored :: Foldl.Fold (InstructionPos Text) (Set.Set RuleCode) ++globalIgnored = Foldl.Fold parse mempty id ++ where ++ parse acc InstructionPos { instruction = Comment comment } = ++ case parseGlobalIgnorePragma comment of ++ Just ignores@(_ : _) -> Set.union ( Set.fromList . fmap RuleCode $ ignores ) acc ++ _ -> acc ++ parse acc _ = acc ++ + parseIgnorePragma :: Text -> Maybe [Text] +-parseIgnorePragma = +- Megaparsec.parseMaybe commentParser +- +-commentParser :: Megaparsec.Parsec Void Text [Text] +-commentParser = +- do +- spaces +- >> string "hadolint" +- >> spaces1 +- >> string "ignore=" +- >> spaces +- >> Megaparsec.sepBy1 ruleName (spaces >> string "," >> spaces) ++parseIgnorePragma = Megaparsec.parseMaybe ignoreParser ++ ++parseGlobalIgnorePragma :: Text -> Maybe [Text] ++parseGlobalIgnorePragma = Megaparsec.parseMaybe globalIgnoreParser ++ ++ignoreParser :: Megaparsec.Parsec Void Text [Text] ++ignoreParser = hadolintPragma >> ignore ++ ++globalIgnoreParser :: Megaparsec.Parsec Void Text [Text] ++globalIgnoreParser = hadolintPragma >> string "global" >> spaces1 >> ignore ++ ++ignore :: Megaparsec.Parsec Void Text [Text] ++ignore = string "ignore" >> spaces >> string "=" >> spaces >> ruleList ++ ++ruleList :: Megaparsec.Parsec Void Text [Text] ++ruleList = Megaparsec.sepBy1 ruleName ( spaces >> string "," >> spaces ) + + ruleName :: Megaparsec.ParsecT Void Text Identity (Megaparsec.Tokens Text) + ruleName = Megaparsec.takeWhile1P Nothing (\c -> c `elem` Set.fromList "DLSC0123456789") +@@ -48,21 +62,16 @@ parseShell :: Text -> Maybe Text + parseShell = Megaparsec.parseMaybe shellParser + + shellParser :: Megaparsec.Parsec Void Text Text +-shellParser = +- do +- spaces +- >> string "hadolint" +- >> spaces1 +- >> string "shell" +- >> spaces +- >> string "=" +- >> spaces +- >> shellName ++shellParser = hadolintPragma >> string "shell" >> spaces >> string "=" >> spaces >> shellName + + shellName :: Megaparsec.ParsecT Void Text Identity (Megaparsec.Tokens Text) + shellName = Megaparsec.takeWhile1P Nothing (/= '\n') + + ++hadolintPragma :: Megaparsec.Parsec Void Text Text ++hadolintPragma = spaces >> string "hadolint" >> spaces1 ++ ++ + string :: Megaparsec.Tokens Text + -> Megaparsec.ParsecT Void Text Identity (Megaparsec.Tokens Text) + string = Megaparsec.string +diff --git a/src/Hadolint/Process.hs b/src/Hadolint/Process.hs +index ec6fb4b..3d3c682 100644 +--- a/src/Hadolint/Process.hs ++++ b/src/Hadolint/Process.hs +@@ -82,6 +82,8 @@ import qualified Hadolint.Shell as Shell + data AnalisisResult = AnalisisResult + { -- | The set of ignored rules per line + ignored :: SMap.IntMap (Set.Set RuleCode), ++ -- | The set of globally ignored rules ++ globalIgnored :: Set.Set RuleCode, + -- | A set of failures collected for reach rule + failed :: Failures + } +@@ -93,6 +95,7 @@ run config dockerfile = Seq.filter shouldKeep failed + + shouldKeep CheckFailure {line, code} + | disableIgnorePragma config = True ++ | code `Set.member` globalIgnored = False + | otherwise = Just True /= do + ignoreList <- SMap.lookup line ignored + return $ code `Set.member` ignoreList +@@ -103,6 +106,7 @@ analyze :: + analyze config = + AnalisisResult + <$> Hadolint.Pragma.ignored ++ <*> Hadolint.Pragma.globalIgnored + <*> Foldl.premap parseShell (failures config) + + parseShell :: InstructionPos Text.Text -> InstructionPos Shell.ParsedShell +diff --git a/test/Hadolint/PragmaSpec.hs b/test/Hadolint/PragmaSpec.hs +index a3e4485..e9325f7 100644 +--- a/test/Hadolint/PragmaSpec.hs ++++ b/test/Hadolint/PragmaSpec.hs +@@ -11,6 +11,7 @@ spec = do + let ?config = def + + describe "Rules can be ignored with inline comments" $ do ++ + it "ignores single rule" $ + let dockerFile = + [ "FROM ubuntu", +@@ -18,6 +19,7 @@ spec = do + "USER root" + ] + in ruleCatchesNot "DL3002" $ Text.unlines dockerFile ++ + it "ignores only the given rule" $ + let dockerFile = + [ "FROM scratch", +@@ -25,6 +27,7 @@ spec = do + "USER root" + ] + in ruleCatches "DL3002" $ Text.unlines dockerFile ++ + it "ignores only the given rule, when multiple passed" $ + let dockerFile = + [ "FROM scratch", +@@ -32,6 +35,7 @@ spec = do + "USER root" + ] + in ruleCatchesNot "DL3002" $ Text.unlines dockerFile ++ + it "ignores the rule only if directly above the instruction" $ + let dockerFile = + [ "# hadolint ignore=DL3001,DL3002", +@@ -39,6 +43,7 @@ spec = do + "USER root" + ] + in ruleCatches "DL3002" $ Text.unlines dockerFile ++ + it "won't ignore the rule if passed invalid rule names" $ + let dockerFile = + [ "FROM scratch", +@@ -46,6 +51,7 @@ spec = do + "USER root" + ] + in ruleCatches "DL3002" $ Text.unlines dockerFile ++ + it "ignores multiple rules correctly, even with some extra whitespace" $ + let dockerFile = + [ "FROM node as foo", +@@ -55,3 +61,24 @@ spec = do + in do + ruleCatchesNot "DL3023" $ Text.unlines dockerFile + ruleCatchesNot "DL3021" $ Text.unlines dockerFile ++ ++ ++ describe "Rules can be ignored globally with global ignore pragma" $ do ++ ++ it "ignores single rule" $ ++ let dockerFile = ++ [ "# hadolint global ignore=DL3002", ++ "FROM ubuntu", ++ "USER root" ++ ] ++ in ruleCatchesNot "DL3002" $ Text.unlines dockerFile ++ ++ it "ignores multiple rules correctly, even with some extra whitespace" $ ++ let dockerFile = ++ [ "# hadolint global ignore = DL3023 , DL3021", ++ "FROM node as foo", ++ "COPY --from=foo bar baz ." ++ ] ++ in do ++ ruleCatchesNot "DL3023" $ Text.unlines dockerFile ++ ruleCatchesNot "DL3021" $ Text.unlines dockerFile diff --git a/tasks/hadolint__hadolint-871/tests/test.sh b/tasks/hadolint__hadolint-871/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..98e08007d80a388117a197adaaf28bcaa44dec7d --- /dev/null +++ b/tasks/hadolint__hadolint-871/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 9b380653b78fbea928af9210cb3823a3e0dfe130 > "$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/hadolint__hadolint-871/tests/verifier.py b/tasks/hadolint__hadolint-871/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-871/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/hadolint__hadolint-880/environment/Dockerfile b/tasks/hadolint__hadolint-880/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..16df26a0a810470ade0001a6246072f25e197750 --- /dev/null +++ b/tasks/hadolint__hadolint-880/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d4cccd0c08f2e1d5f89337648eb2900776fd1c8b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d4cccd0c08f2e1d5f89337648eb2900776fd1c8b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d4cccd0c08f2e1d5f89337648eb2900776fd1c8b \ + && 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/hadolint__hadolint-880/instruction.md b/tasks/hadolint__hadolint-880/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..59129bc4b3bb776440dcf10163605d9ea490d1da --- /dev/null +++ b/tasks/hadolint__hadolint-880/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Allow rm yum cache clean up + +## Description + +Update DL3032 and DL3040 to allow explicit yum cache clean up after install. + + + + + +### What I did + +Update DL3032 and DL3040 to allow explicit yum cache clean up after install using `rm -rf /var/cache/yum/*` + +### How I did it + +Added `||` condition to clean up rules. + +### How to verify it + +Unit tests have been added for both rules. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d4cccd0c08f2`. 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/hadolint__hadolint-880/solution/patch.diff b/tasks/hadolint__hadolint-880/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8b9cb9771174e970bb88086c6790179244c81949 --- /dev/null +++ b/tasks/hadolint__hadolint-880/solution/patch.diff @@ -0,0 +1,49 @@ +diff --git a/src/Hadolint/Rule/DL3032.hs b/src/Hadolint/Rule/DL3032.hs +index b6fcdfb..c895677 100644 +--- a/src/Hadolint/Rule/DL3032.hs ++++ b/src/Hadolint/Rule/DL3032.hs +@@ -24,5 +24,6 @@ dl3032 = simpleRule code severity message check + check _ = True + + yumInstall = Shell.cmdHasArgs "yum" ["install"] +- yumClean = Shell.cmdHasArgs "yum" ["clean", "all"] ++ yumClean args = Shell.cmdHasArgs "yum" ["clean", "all"] args ++ || Shell.cmdHasArgs "rm" ["-rf", "/var/cache/yum/*"] args + {-# INLINEABLE dl3032 #-} +diff --git a/src/Hadolint/Rule/DL3040.hs b/src/Hadolint/Rule/DL3040.hs +index b65ca36..2be6a81 100644 +--- a/src/Hadolint/Rule/DL3040.hs ++++ b/src/Hadolint/Rule/DL3040.hs +@@ -26,6 +26,7 @@ dl3040 = simpleRule code severity message check + ) + + dnfInstall cmdName = Shell.cmdHasArgs cmdName ["install"] +- dnfClean cmdName = Shell.cmdHasArgs cmdName ["clean", "all"] ++ dnfClean cmdName args = Shell.cmdHasArgs cmdName ["clean", "all"] args ++ || Shell.cmdHasArgs "rm" ["-rf", "/var/cache/yum/*"] args + dnfCmds = ["dnf", "microdnf"] + {-# INLINEABLE dl3040 #-} +diff --git a/test/Hadolint/Rule/DL3032Spec.hs b/test/Hadolint/Rule/DL3032Spec.hs +index 506d779..d682d87 100644 +--- a/test/Hadolint/Rule/DL3032Spec.hs ++++ b/test/Hadolint/Rule/DL3032Spec.hs +@@ -18,3 +18,6 @@ spec = do + ruleCatchesNot "DL3032" "RUN bash -c `# not even a yum command`" + onBuildRuleCatchesNot "DL3032" "RUN yum install -y mariadb-10.4 && yum clean all" + onBuildRuleCatchesNot "DL3032" "RUN bash -c `# not even a yum command`" ++ it "ok with rm -rf /var/cache/yum/*" $ do ++ ruleCatchesNot "DL3032" "RUN yum install -y mariadb-10.4 && rm -rf /var/cache/yum/*" ++ onBuildRuleCatchesNot "DL3032" "RUN yum install -y mariadb-10.4 && rm -rf /var/cache/yum/*" +diff --git a/test/Hadolint/Rule/DL3040Spec.hs b/test/Hadolint/Rule/DL3040Spec.hs +index 699df61..da9af53 100644 +--- a/test/Hadolint/Rule/DL3040Spec.hs ++++ b/test/Hadolint/Rule/DL3040Spec.hs +@@ -23,3 +23,8 @@ spec = do + onBuildRuleCatchesNot "DL3040" "RUN dnf install -y mariadb-10.4 && dnf clean all" + onBuildRuleCatchesNot "DL3040" "RUN microdnf install -y mariadb-10.4 && microdnf clean all" + onBuildRuleCatchesNot "DL3040" "RUN notdnf install mariadb" ++ it "ok with rm /var/cache/yum" $ do ++ ruleCatchesNot "DL3040" "RUN dnf install -y mariadb-10.4 && rm -rf /var/cache/yum/*" ++ ruleCatchesNot "DL3040" "RUN microdnf install -y mariadb-10.4 && rm -rf /var/cache/yum/*" ++ onBuildRuleCatchesNot "DL3040" "RUN dnf install -y mariadb-10.4 && rm -rf /var/cache/yum/*" ++ onBuildRuleCatchesNot "DL3040" "RUN microdnf install -y mariadb-10.4 && rm -rf /var/cache/yum/*" diff --git a/tasks/hadolint__hadolint-880/solution/solve.sh b/tasks/hadolint__hadolint-880/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-880/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/hadolint__hadolint-880/task.toml b/tasks/hadolint__hadolint-880/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d856117f96fc93dbde1a8c19104bed42f8befaf9 --- /dev/null +++ b/tasks/hadolint__hadolint-880/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-880" +description = "Allow rm yum cache clean up" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "d4cccd0c08f2e1d5f89337648eb2900776fd1c8b" +reference = "https://github.com/hadolint/hadolint/pull/880" +source_access = "auto" +built_at = "2026-11-16T16:09:53.730908+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:42f807d464b06c071f790c6bcfe281756312dca8c1183789b67c9ec9bd6cc9d8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-11-07T09:40:45Z" +diff_format = "unified" +context_files = [ + "src/Hadolint/Rule/DL3032.hs", + "src/Hadolint/Rule/DL3040.hs", + "test/Hadolint/Rule/DL3032Spec.hs", + "test/Hadolint/Rule/DL3040Spec.hs", +] +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:00.802254+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c67dc226ee99866fc7948051674b032e86fb1d6fa1d4ca2184f720cfd78413a8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-880/tests/capture.py b/tasks/hadolint__hadolint-880/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-880/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/hadolint__hadolint-880/tests/instruction.md b/tasks/hadolint__hadolint-880/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..59129bc4b3bb776440dcf10163605d9ea490d1da --- /dev/null +++ b/tasks/hadolint__hadolint-880/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** Allow rm yum cache clean up + +## Description + +Update DL3032 and DL3040 to allow explicit yum cache clean up after install. + + + + + +### What I did + +Update DL3032 and DL3040 to allow explicit yum cache clean up after install using `rm -rf /var/cache/yum/*` + +### How I did it + +Added `||` condition to clean up rules. + +### How to verify it + +Unit tests have been added for both rules. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d4cccd0c08f2`. 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/hadolint__hadolint-880/tests/oracle.patch b/tasks/hadolint__hadolint-880/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8b9cb9771174e970bb88086c6790179244c81949 --- /dev/null +++ b/tasks/hadolint__hadolint-880/tests/oracle.patch @@ -0,0 +1,49 @@ +diff --git a/src/Hadolint/Rule/DL3032.hs b/src/Hadolint/Rule/DL3032.hs +index b6fcdfb..c895677 100644 +--- a/src/Hadolint/Rule/DL3032.hs ++++ b/src/Hadolint/Rule/DL3032.hs +@@ -24,5 +24,6 @@ dl3032 = simpleRule code severity message check + check _ = True + + yumInstall = Shell.cmdHasArgs "yum" ["install"] +- yumClean = Shell.cmdHasArgs "yum" ["clean", "all"] ++ yumClean args = Shell.cmdHasArgs "yum" ["clean", "all"] args ++ || Shell.cmdHasArgs "rm" ["-rf", "/var/cache/yum/*"] args + {-# INLINEABLE dl3032 #-} +diff --git a/src/Hadolint/Rule/DL3040.hs b/src/Hadolint/Rule/DL3040.hs +index b65ca36..2be6a81 100644 +--- a/src/Hadolint/Rule/DL3040.hs ++++ b/src/Hadolint/Rule/DL3040.hs +@@ -26,6 +26,7 @@ dl3040 = simpleRule code severity message check + ) + + dnfInstall cmdName = Shell.cmdHasArgs cmdName ["install"] +- dnfClean cmdName = Shell.cmdHasArgs cmdName ["clean", "all"] ++ dnfClean cmdName args = Shell.cmdHasArgs cmdName ["clean", "all"] args ++ || Shell.cmdHasArgs "rm" ["-rf", "/var/cache/yum/*"] args + dnfCmds = ["dnf", "microdnf"] + {-# INLINEABLE dl3040 #-} +diff --git a/test/Hadolint/Rule/DL3032Spec.hs b/test/Hadolint/Rule/DL3032Spec.hs +index 506d779..d682d87 100644 +--- a/test/Hadolint/Rule/DL3032Spec.hs ++++ b/test/Hadolint/Rule/DL3032Spec.hs +@@ -18,3 +18,6 @@ spec = do + ruleCatchesNot "DL3032" "RUN bash -c `# not even a yum command`" + onBuildRuleCatchesNot "DL3032" "RUN yum install -y mariadb-10.4 && yum clean all" + onBuildRuleCatchesNot "DL3032" "RUN bash -c `# not even a yum command`" ++ it "ok with rm -rf /var/cache/yum/*" $ do ++ ruleCatchesNot "DL3032" "RUN yum install -y mariadb-10.4 && rm -rf /var/cache/yum/*" ++ onBuildRuleCatchesNot "DL3032" "RUN yum install -y mariadb-10.4 && rm -rf /var/cache/yum/*" +diff --git a/test/Hadolint/Rule/DL3040Spec.hs b/test/Hadolint/Rule/DL3040Spec.hs +index 699df61..da9af53 100644 +--- a/test/Hadolint/Rule/DL3040Spec.hs ++++ b/test/Hadolint/Rule/DL3040Spec.hs +@@ -23,3 +23,8 @@ spec = do + onBuildRuleCatchesNot "DL3040" "RUN dnf install -y mariadb-10.4 && dnf clean all" + onBuildRuleCatchesNot "DL3040" "RUN microdnf install -y mariadb-10.4 && microdnf clean all" + onBuildRuleCatchesNot "DL3040" "RUN notdnf install mariadb" ++ it "ok with rm /var/cache/yum" $ do ++ ruleCatchesNot "DL3040" "RUN dnf install -y mariadb-10.4 && rm -rf /var/cache/yum/*" ++ ruleCatchesNot "DL3040" "RUN microdnf install -y mariadb-10.4 && rm -rf /var/cache/yum/*" ++ onBuildRuleCatchesNot "DL3040" "RUN dnf install -y mariadb-10.4 && rm -rf /var/cache/yum/*" ++ onBuildRuleCatchesNot "DL3040" "RUN microdnf install -y mariadb-10.4 && rm -rf /var/cache/yum/*" diff --git a/tasks/hadolint__hadolint-880/tests/test.sh b/tasks/hadolint__hadolint-880/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..90ef10442630bb60ebd88a3944fe6dc4751b11d5 --- /dev/null +++ b/tasks/hadolint__hadolint-880/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 d4cccd0c08f2e1d5f89337648eb2900776fd1c8b > "$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/hadolint__hadolint-880/tests/verifier.py b/tasks/hadolint__hadolint-880/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-880/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/hadolint__hadolint-888/environment/Dockerfile b/tasks/hadolint__hadolint-888/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..16df26a0a810470ade0001a6246072f25e197750 --- /dev/null +++ b/tasks/hadolint__hadolint-888/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d4cccd0c08f2e1d5f89337648eb2900776fd1c8b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d4cccd0c08f2e1d5f89337648eb2900776fd1c8b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d4cccd0c08f2e1d5f89337648eb2900776fd1c8b \ + && 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/hadolint__hadolint-888/instruction.md b/tasks/hadolint__hadolint-888/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa6abdd143248bc8ca650b20e0241ef5c994c9c9 --- /dev/null +++ b/tasks/hadolint__hadolint-888/instruction.md @@ -0,0 +1,151 @@ +# Issue + +**Title:** build(deps): bump actions/cache from 3.0.4 to 3.0.11 + +## Description + +Bumps [actions/cache](https://github.com/actions/cache) from 3.0.4 to 3.0.11. +
+Release notes +

Sourced from actions/cache's releases.

+
+

v3.0.11

+

What's Changed

+ +

New Contributors

+ +

Full Changelog: https://github.com/actions/cache/compare/v3...v3.0.11

+

v3.0.10

+
    +
  • Fix a bug with sorting inputs.
  • +
  • Update definition for restore-keys in README.md
  • +
+

v3.0.9

+
    +
  • Enhanced the warning message for cache unavailability in case of GHES.
  • +
+

v3.0.8

+

What's Changed

+
    +
  • Fix zstd not working for windows on gnu tar in issues.
  • +
  • Allow users to provide a custom timeout as input for aborting cache segment download using the environment variable SEGMENT_DOWNLOAD_TIMEOUT_MIN. Default is 60 minutes.
  • +
+

v3.0.7

+

What's Changed

+
    +
  • Fix for the download stuck problem has been added in actions/cache for users who were intermittently facing the issue. As part of this fix, new timeout has been introduced in the download step to stop the download if it doesn't complete within an hour and run the rest of the workflow without erroring out.
  • +
+

v3.0.6

+

What's Changed

+
    +
  • Add example for clojure lein project dependencies by @​shivamarora1 in PR actions/cache#835
  • +
  • Update toolkit's cache npm module to latest. Bump cache version to v3.0.6 by @​pdotl in PR actions/cache#887
  • +
  • Fix issue #809 where cache save/restore was failing for Amazon Linux 2 runners due to older tar version
  • +
  • Fix issue #833 where cache save was not working for caching github workspace directory
  • +
+

New Contributors

+ +

Full Changelog: https://github.com/actions/cache/compare/v3...v3.0.6

+

v3.0.5

+

Removed error handling by consuming actions/cache 3.0 toolkit, Now cache server error handling will be done by toolkit.

+
+
+
+Changelog +

Sourced from actions/cache's changelog.

+
+

3.0.4

+
    +
  • Fixed tar creation error while trying to create tar with path as ~/ home folder on ubuntu-latest. (issue)
  • +
+

3.0.5

+
    +
  • Removed error handling by consuming actions/cache 3.0 toolkit, Now cache server error handling will be done by toolkit. (PR)
  • +
+

3.0.6

+
    +
  • Fixed #809 - zstd -d: no such file or directory error
  • +
  • Fixed #833 - cache doesn't work with github workspace directory
  • +
+

3.0.7

+
    +
  • Fixed #810 - download stuck issue. A new timeout is introduced in the download process to abort the download if it gets stuck and doesn't finish within an hour.
  • +
+

3.0.8

+
    +
  • Fix zstd not working for windows on gnu tar in issues #888 and #891.
  • +
  • Allowing users to provide a custom timeout as input for aborting download of a cache segment using an environment variable SEGMENT_DOWNLOAD_TIMEOUT_MIN. Default is 60 minutes.
  • +
+

3.0.9

+
    +
  • Enhanced the warning message for cache unavailablity in case of GHES.
  • +
+

3.0.10

+
    +
  • Fix a bug with sorting inputs.
  • +
  • Update definition for restore-keys in README.md
  • +
+

3.0.11

+
    +
  • Update toolkit version to 3.0.5 to include @actions/core@^1.10.0
  • +
  • Update @actions/cache to use updated saveState and setOutput functions from @actions/core@^1.10.0
  • +
+
+
+
+Commits +
    +
  • 9b0c1fc Merge pull request #956 from actions/pdotl-version-bump
  • +
  • 18103f6 Fix licensed status error
  • +
  • 3e383cd Update RELEASES
  • +
  • 43428ea toolkit versioon update and version bump for cache
  • +
  • 1c73980 3.0.11
  • +
  • a3f5edc Merge pull request #950 from rentziass/rentziass/update-actions-core
  • +
  • 831ee69 Update licenses
  • +
  • b9c8bfe Update @​actions/core to 1.10.0
  • +
  • 0f20846 Merge pull request #946 from actions/Phantsure-patch-2
  • +
  • 862fc14 Update README.md
  • +
  • Additional commits viewable in compare view
  • +
+
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/cache&package-manager=github_actions&previous-version=3.0.4&new-version=3.0.11)](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) + +--- + +
+Dependabot commands and options +
+ +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 merge` will merge this PR after your CI passes on it +- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it +- `@dependabot cancel merge` will cancel a previously requested merge and block automerging +- `@dependabot reopen` will reopen this PR if it is closed +- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually +- `@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) + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d4cccd0c08f2`. 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/hadolint__hadolint-888/solution/patch.diff b/tasks/hadolint__hadolint-888/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8178381211476e720d5f6564281fcdcd568aeee5 --- /dev/null +++ b/tasks/hadolint__hadolint-888/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml +index 213ef41..3a7454b 100644 +--- a/.github/workflows/haskell.yml ++++ b/.github/workflows/haskell.yml +@@ -53,7 +53,7 @@ jobs: + # cache + + - name: Cache store +- uses: actions/cache@v3.0.4 ++ uses: actions/cache@v3.0.11 + with: + path: ${{ steps.setup-haskell-cabal.outputs.cabal-store }} + key: ${{ runner.os }}-${{ hashFiles('cabal.project.freeze') }} +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index fdc469d..0c47955 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -235,7 +235,7 @@ jobs: + run: cabal freeze + + - name: Cache store +- uses: actions/cache@v3.0.4 ++ uses: actions/cache@v3.0.11 + with: + path: ${{ steps.setup-haskell-cabal.outputs.cabal-store }} + key: ${{ runner.os }}-${{ hashFiles('cabal.project.freeze') }} diff --git a/tasks/hadolint__hadolint-888/solution/solve.sh b/tasks/hadolint__hadolint-888/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-888/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/hadolint__hadolint-888/task.toml b/tasks/hadolint__hadolint-888/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d9d37d08b35215532d632fc4b7ce7b3f5cf2e5a4 --- /dev/null +++ b/tasks/hadolint__hadolint-888/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-888" +description = "build(deps): bump actions/cache from 3.0.4 to 3.0.11" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "d4cccd0c08f2e1d5f89337648eb2900776fd1c8b" +reference = "https://github.com/hadolint/hadolint/pull/888" +source_access = "auto" +built_at = "2026-11-16T16:09:53.725139+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:fde4a1c694e8bbb1dc29c6f6677f1c2985e6bb8eccd0260c1c78e5a28cc0c04f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-11-10T08:52:35Z" +diff_format = "unified" +context_files = [ + ".github/workflows/haskell.yml", + ".github/workflows/release.yml", +] +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:00.802727+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c67dc226ee99866fc7948051674b032e86fb1d6fa1d4ca2184f720cfd78413a8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-888/tests/capture.py b/tasks/hadolint__hadolint-888/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-888/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/hadolint__hadolint-888/tests/instruction.md b/tasks/hadolint__hadolint-888/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa6abdd143248bc8ca650b20e0241ef5c994c9c9 --- /dev/null +++ b/tasks/hadolint__hadolint-888/tests/instruction.md @@ -0,0 +1,151 @@ +# Issue + +**Title:** build(deps): bump actions/cache from 3.0.4 to 3.0.11 + +## Description + +Bumps [actions/cache](https://github.com/actions/cache) from 3.0.4 to 3.0.11. +
+Release notes +

Sourced from actions/cache's releases.

+
+

v3.0.11

+

What's Changed

+ +

New Contributors

+ +

Full Changelog: https://github.com/actions/cache/compare/v3...v3.0.11

+

v3.0.10

+
    +
  • Fix a bug with sorting inputs.
  • +
  • Update definition for restore-keys in README.md
  • +
+

v3.0.9

+
    +
  • Enhanced the warning message for cache unavailability in case of GHES.
  • +
+

v3.0.8

+

What's Changed

+
    +
  • Fix zstd not working for windows on gnu tar in issues.
  • +
  • Allow users to provide a custom timeout as input for aborting cache segment download using the environment variable SEGMENT_DOWNLOAD_TIMEOUT_MIN. Default is 60 minutes.
  • +
+

v3.0.7

+

What's Changed

+
    +
  • Fix for the download stuck problem has been added in actions/cache for users who were intermittently facing the issue. As part of this fix, new timeout has been introduced in the download step to stop the download if it doesn't complete within an hour and run the rest of the workflow without erroring out.
  • +
+

v3.0.6

+

What's Changed

+
    +
  • Add example for clojure lein project dependencies by @​shivamarora1 in PR actions/cache#835
  • +
  • Update toolkit's cache npm module to latest. Bump cache version to v3.0.6 by @​pdotl in PR actions/cache#887
  • +
  • Fix issue #809 where cache save/restore was failing for Amazon Linux 2 runners due to older tar version
  • +
  • Fix issue #833 where cache save was not working for caching github workspace directory
  • +
+

New Contributors

+ +

Full Changelog: https://github.com/actions/cache/compare/v3...v3.0.6

+

v3.0.5

+

Removed error handling by consuming actions/cache 3.0 toolkit, Now cache server error handling will be done by toolkit.

+
+
+
+Changelog +

Sourced from actions/cache's changelog.

+
+

3.0.4

+
    +
  • Fixed tar creation error while trying to create tar with path as ~/ home folder on ubuntu-latest. (issue)
  • +
+

3.0.5

+
    +
  • Removed error handling by consuming actions/cache 3.0 toolkit, Now cache server error handling will be done by toolkit. (PR)
  • +
+

3.0.6

+
    +
  • Fixed #809 - zstd -d: no such file or directory error
  • +
  • Fixed #833 - cache doesn't work with github workspace directory
  • +
+

3.0.7

+
    +
  • Fixed #810 - download stuck issue. A new timeout is introduced in the download process to abort the download if it gets stuck and doesn't finish within an hour.
  • +
+

3.0.8

+
    +
  • Fix zstd not working for windows on gnu tar in issues #888 and #891.
  • +
  • Allowing users to provide a custom timeout as input for aborting download of a cache segment using an environment variable SEGMENT_DOWNLOAD_TIMEOUT_MIN. Default is 60 minutes.
  • +
+

3.0.9

+
    +
  • Enhanced the warning message for cache unavailablity in case of GHES.
  • +
+

3.0.10

+
    +
  • Fix a bug with sorting inputs.
  • +
  • Update definition for restore-keys in README.md
  • +
+

3.0.11

+
    +
  • Update toolkit version to 3.0.5 to include @actions/core@^1.10.0
  • +
  • Update @actions/cache to use updated saveState and setOutput functions from @actions/core@^1.10.0
  • +
+
+
+
+Commits +
    +
  • 9b0c1fc Merge pull request #956 from actions/pdotl-version-bump
  • +
  • 18103f6 Fix licensed status error
  • +
  • 3e383cd Update RELEASES
  • +
  • 43428ea toolkit versioon update and version bump for cache
  • +
  • 1c73980 3.0.11
  • +
  • a3f5edc Merge pull request #950 from rentziass/rentziass/update-actions-core
  • +
  • 831ee69 Update licenses
  • +
  • b9c8bfe Update @​actions/core to 1.10.0
  • +
  • 0f20846 Merge pull request #946 from actions/Phantsure-patch-2
  • +
  • 862fc14 Update README.md
  • +
  • Additional commits viewable in compare view
  • +
+
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/cache&package-manager=github_actions&previous-version=3.0.4&new-version=3.0.11)](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) + +--- + +
+Dependabot commands and options +
+ +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 merge` will merge this PR after your CI passes on it +- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it +- `@dependabot cancel merge` will cancel a previously requested merge and block automerging +- `@dependabot reopen` will reopen this PR if it is closed +- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually +- `@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) + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d4cccd0c08f2`. 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/hadolint__hadolint-888/tests/oracle.patch b/tasks/hadolint__hadolint-888/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8178381211476e720d5f6564281fcdcd568aeee5 --- /dev/null +++ b/tasks/hadolint__hadolint-888/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml +index 213ef41..3a7454b 100644 +--- a/.github/workflows/haskell.yml ++++ b/.github/workflows/haskell.yml +@@ -53,7 +53,7 @@ jobs: + # cache + + - name: Cache store +- uses: actions/cache@v3.0.4 ++ uses: actions/cache@v3.0.11 + with: + path: ${{ steps.setup-haskell-cabal.outputs.cabal-store }} + key: ${{ runner.os }}-${{ hashFiles('cabal.project.freeze') }} +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index fdc469d..0c47955 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -235,7 +235,7 @@ jobs: + run: cabal freeze + + - name: Cache store +- uses: actions/cache@v3.0.4 ++ uses: actions/cache@v3.0.11 + with: + path: ${{ steps.setup-haskell-cabal.outputs.cabal-store }} + key: ${{ runner.os }}-${{ hashFiles('cabal.project.freeze') }} diff --git a/tasks/hadolint__hadolint-888/tests/test.sh b/tasks/hadolint__hadolint-888/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..90ef10442630bb60ebd88a3944fe6dc4751b11d5 --- /dev/null +++ b/tasks/hadolint__hadolint-888/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 d4cccd0c08f2e1d5f89337648eb2900776fd1c8b > "$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/hadolint__hadolint-888/tests/verifier.py b/tasks/hadolint__hadolint-888/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-888/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/hadolint__hadolint-900/environment/Dockerfile b/tasks/hadolint__hadolint-900/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a80df227ec55e43faf0d051c296bacddc98219df --- /dev/null +++ b/tasks/hadolint__hadolint-900/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 41a0f7ab4d79cd3202328797498f5a0fbcd3a4e4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 41a0f7ab4d79cd3202328797498f5a0fbcd3a4e4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 41a0f7ab4d79cd3202328797498f5a0fbcd3a4e4 \ + && 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/hadolint__hadolint-900/instruction.md b/tasks/hadolint__hadolint-900/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..33907fe6cd2edc9d600d74555301984a5f275964 --- /dev/null +++ b/tasks/hadolint__hadolint-900/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix: false positive in `DL3022` + +## Description + +### What I did + +Simple patch to fix bug with hadolint raising false positives if the stages are mentioned by index rather than names. +Such as, +```dockerfile +FROM X as stage1 +RUN # do some work, likely, build something to copy + +FROM Y as stage2 +COPY --from=0 bar . +``` + +### How I did it + +I use decimal conversion over string to get the index and compare it to the count of the stages in source, not sure if there was a better way to write the code I just wrote it because I needed it to be fixed. + +### How to verify it + +Added a couple tests to `DL3022Spec.hs` + + +#### Note: Let me know if there are any mistakes I will fix em. Though as it's a weekend I might not always be available. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `41a0f7ab4d79`. 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/hadolint__hadolint-900/solution/patch.diff b/tasks/hadolint__hadolint-900/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1f97deb38587c6587e8ccc670084f8a59b823b30 --- /dev/null +++ b/tasks/hadolint__hadolint-900/solution/patch.diff @@ -0,0 +1,80 @@ +diff --git a/src/Hadolint/Rule/DL3022.hs b/src/Hadolint/Rule/DL3022.hs +index eb60ffe..bf6b098 100644 +--- a/src/Hadolint/Rule/DL3022.hs ++++ b/src/Hadolint/Rule/DL3022.hs +@@ -2,20 +2,45 @@ module Hadolint.Rule.DL3022 (rule) where + + import qualified Data.Set as Set + import qualified Data.Text as Text ++import qualified Data.Text.Read as Read + import Hadolint.Rule + import Language.Docker.Syntax + ++data Acc ++ = Acc { count :: Int, names :: Set.Set Text.Text } ++ | Empty ++ deriving (Eq) ++ + rule :: Rule args +-rule = customRule check (emptyState Set.empty) ++rule = customRule check (emptyState Empty) + where + code = "DL3022" + severity = DLWarningC + message = "`COPY --from` should reference a previously defined `FROM` alias" + +- check _ st (From BaseImage {alias = Just (ImageAlias als)}) = st |> modify (Set.insert als) ++ check _ st (From BaseImage {alias = Just (ImageAlias als)}) = st |> modify (incAndAddName als) ++ check _ st (From BaseImage {}) = st |> modify incCount + check line st (Copy (CopyArgs _ _) (CopyFlags _ _ _ (CopySource s))) + | ":" `Text.isInfixOf` dropQuotes s = st +- | Set.member s (state st) = st +- | otherwise = st |> addFail CheckFailure {..} ++ | isMember s (state st) = st ++ | otherwise = case Read.decimal s of ++ Right (v, _) | v < nameCount (state st) -> st ++ _ -> st |> addFail CheckFailure {..} + check _ st _ = st + {-# INLINEABLE rule #-} ++ ++incAndAddName :: Text.Text -> Acc -> Acc ++incAndAddName s Empty = Acc { count = 1, names = Set.singleton s } ++incAndAddName s Acc { count, names } = Acc { count = count + 1, names = Set.insert s names } ++ ++incCount :: Acc -> Acc ++incCount Empty = Acc { count = 1, names = Set.empty } ++incCount Acc { count, names } = Acc { count = count + 1, names = names } ++ ++isMember :: Text.Text -> Acc -> Bool ++isMember _ Empty = False ++isMember s Acc { names } = Set.member s names ++ ++nameCount :: Acc -> Int ++nameCount Empty = 0 ++nameCount Acc { count } = count +diff --git a/test/Hadolint/Rule/DL3022Spec.hs b/test/Hadolint/Rule/DL3022Spec.hs +index 249bd51..10bd14a 100644 +--- a/test/Hadolint/Rule/DL3022Spec.hs ++++ b/test/Hadolint/Rule/DL3022Spec.hs +@@ -30,3 +30,20 @@ spec = do + ] + in ruleCatchesNot "DL3022" $ Text.unlines dockerFile + it "don't warn on external images" $ ruleCatchesNot "DL3022" "COPY --from=haskell:latest bar ." ++ it "warn on invalid stage count as --from=" $ ruleCatches "DL3022" "COPY --from=0 bar ." ++ it "don't warn on valid stage count as --from=" $ ++ let dockerFile = ++ [ "FROM scratch as build", ++ "RUN foo", ++ "FROM node", ++ "COPY --from=0 foo ." ++ ] ++ in ruleCatchesNot "DL3022" $ Text.unlines dockerFile ++ it "don't warn on valid stage count as --from=" $ ++ let dockerFile = ++ [ "FROM scratch", ++ "RUN foo", ++ "FROM node", ++ "COPY --from=0 foo ." ++ ] ++ in ruleCatchesNot "DL3022" $ Text.unlines dockerFile +\ No newline at end of file diff --git a/tasks/hadolint__hadolint-900/solution/solve.sh b/tasks/hadolint__hadolint-900/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-900/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/hadolint__hadolint-900/task.toml b/tasks/hadolint__hadolint-900/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..84952fce6a55af5fb8947fa8b6b553b3ba8a4408 --- /dev/null +++ b/tasks/hadolint__hadolint-900/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-900" +description = "fix: false positive in `DL3022`" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "41a0f7ab4d79cd3202328797498f5a0fbcd3a4e4" +reference = "https://github.com/hadolint/hadolint/pull/900" +source_access = "auto" +built_at = "2026-11-16T16:09:53.721283+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9c274958cb7e99421e29b18419bf0c92c31f3fded5de7b0f393c32161a65d9c8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-11-16T15:41:55Z" +diff_format = "unified" +context_files = [ + "src/Hadolint/Rule/DL3022.hs", + "test/Hadolint/Rule/DL3022Spec.hs", +] +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:00.803181+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8289f3f84a60aaa489b048d2e79f4cb595051dd26c250ddda803dfcdd184f706" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-900/tests/capture.py b/tasks/hadolint__hadolint-900/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-900/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/hadolint__hadolint-900/tests/instruction.md b/tasks/hadolint__hadolint-900/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..33907fe6cd2edc9d600d74555301984a5f275964 --- /dev/null +++ b/tasks/hadolint__hadolint-900/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix: false positive in `DL3022` + +## Description + +### What I did + +Simple patch to fix bug with hadolint raising false positives if the stages are mentioned by index rather than names. +Such as, +```dockerfile +FROM X as stage1 +RUN # do some work, likely, build something to copy + +FROM Y as stage2 +COPY --from=0 bar . +``` + +### How I did it + +I use decimal conversion over string to get the index and compare it to the count of the stages in source, not sure if there was a better way to write the code I just wrote it because I needed it to be fixed. + +### How to verify it + +Added a couple tests to `DL3022Spec.hs` + + +#### Note: Let me know if there are any mistakes I will fix em. Though as it's a weekend I might not always be available. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `41a0f7ab4d79`. 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/hadolint__hadolint-900/tests/oracle.patch b/tasks/hadolint__hadolint-900/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1f97deb38587c6587e8ccc670084f8a59b823b30 --- /dev/null +++ b/tasks/hadolint__hadolint-900/tests/oracle.patch @@ -0,0 +1,80 @@ +diff --git a/src/Hadolint/Rule/DL3022.hs b/src/Hadolint/Rule/DL3022.hs +index eb60ffe..bf6b098 100644 +--- a/src/Hadolint/Rule/DL3022.hs ++++ b/src/Hadolint/Rule/DL3022.hs +@@ -2,20 +2,45 @@ module Hadolint.Rule.DL3022 (rule) where + + import qualified Data.Set as Set + import qualified Data.Text as Text ++import qualified Data.Text.Read as Read + import Hadolint.Rule + import Language.Docker.Syntax + ++data Acc ++ = Acc { count :: Int, names :: Set.Set Text.Text } ++ | Empty ++ deriving (Eq) ++ + rule :: Rule args +-rule = customRule check (emptyState Set.empty) ++rule = customRule check (emptyState Empty) + where + code = "DL3022" + severity = DLWarningC + message = "`COPY --from` should reference a previously defined `FROM` alias" + +- check _ st (From BaseImage {alias = Just (ImageAlias als)}) = st |> modify (Set.insert als) ++ check _ st (From BaseImage {alias = Just (ImageAlias als)}) = st |> modify (incAndAddName als) ++ check _ st (From BaseImage {}) = st |> modify incCount + check line st (Copy (CopyArgs _ _) (CopyFlags _ _ _ (CopySource s))) + | ":" `Text.isInfixOf` dropQuotes s = st +- | Set.member s (state st) = st +- | otherwise = st |> addFail CheckFailure {..} ++ | isMember s (state st) = st ++ | otherwise = case Read.decimal s of ++ Right (v, _) | v < nameCount (state st) -> st ++ _ -> st |> addFail CheckFailure {..} + check _ st _ = st + {-# INLINEABLE rule #-} ++ ++incAndAddName :: Text.Text -> Acc -> Acc ++incAndAddName s Empty = Acc { count = 1, names = Set.singleton s } ++incAndAddName s Acc { count, names } = Acc { count = count + 1, names = Set.insert s names } ++ ++incCount :: Acc -> Acc ++incCount Empty = Acc { count = 1, names = Set.empty } ++incCount Acc { count, names } = Acc { count = count + 1, names = names } ++ ++isMember :: Text.Text -> Acc -> Bool ++isMember _ Empty = False ++isMember s Acc { names } = Set.member s names ++ ++nameCount :: Acc -> Int ++nameCount Empty = 0 ++nameCount Acc { count } = count +diff --git a/test/Hadolint/Rule/DL3022Spec.hs b/test/Hadolint/Rule/DL3022Spec.hs +index 249bd51..10bd14a 100644 +--- a/test/Hadolint/Rule/DL3022Spec.hs ++++ b/test/Hadolint/Rule/DL3022Spec.hs +@@ -30,3 +30,20 @@ spec = do + ] + in ruleCatchesNot "DL3022" $ Text.unlines dockerFile + it "don't warn on external images" $ ruleCatchesNot "DL3022" "COPY --from=haskell:latest bar ." ++ it "warn on invalid stage count as --from=" $ ruleCatches "DL3022" "COPY --from=0 bar ." ++ it "don't warn on valid stage count as --from=" $ ++ let dockerFile = ++ [ "FROM scratch as build", ++ "RUN foo", ++ "FROM node", ++ "COPY --from=0 foo ." ++ ] ++ in ruleCatchesNot "DL3022" $ Text.unlines dockerFile ++ it "don't warn on valid stage count as --from=" $ ++ let dockerFile = ++ [ "FROM scratch", ++ "RUN foo", ++ "FROM node", ++ "COPY --from=0 foo ." ++ ] ++ in ruleCatchesNot "DL3022" $ Text.unlines dockerFile +\ No newline at end of file diff --git a/tasks/hadolint__hadolint-900/tests/test.sh b/tasks/hadolint__hadolint-900/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3bd56a70436d32f3d123552189b5ef75bf797d95 --- /dev/null +++ b/tasks/hadolint__hadolint-900/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 41a0f7ab4d79cd3202328797498f5a0fbcd3a4e4 > "$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/hadolint__hadolint-900/tests/verifier.py b/tasks/hadolint__hadolint-900/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-900/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/hadolint__hadolint-902/environment/Dockerfile b/tasks/hadolint__hadolint-902/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..83b587a0f8323d7db5c76d0ca833f28509132694 --- /dev/null +++ b/tasks/hadolint__hadolint-902/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fcbd01791c9251d83f2486e61ecaf41ee700a766 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fcbd01791c9251d83f2486e61ecaf41ee700a766 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fcbd01791c9251d83f2486e61ecaf41ee700a766 \ + && 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/hadolint__hadolint-902/instruction.md b/tasks/hadolint__hadolint-902/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b87edac96a81102fc7f6f8d018517bfd09359312 --- /dev/null +++ b/tasks/hadolint__hadolint-902/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** DL3011: fixup changes in AST + +## Description + +Fix up usage of the AST in DL3011 corresponding to the changes to the AST with respect to port ranges in `EXPOSE` instructions. + +requires: +fixes: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fcbd01791c92`. 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/hadolint__hadolint-902/solution/patch.diff b/tasks/hadolint__hadolint-902/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..20333c86d9de5ec9ba23a1824d3956069650f846 --- /dev/null +++ b/tasks/hadolint__hadolint-902/solution/patch.diff @@ -0,0 +1,89 @@ +diff --git a/.gitignore b/.gitignore +index f353de8..40ef52e 100644 +--- a/.gitignore ++++ b/.gitignore +@@ -11,3 +11,5 @@ dist-newstyle + + # travis wait is generating log in PWD + travis_wait_*.log ++ ++cabal.project.local* +diff --git a/hadolint.cabal b/hadolint.cabal +index 3e11344..1a55eac 100644 +--- a/hadolint.cabal ++++ b/hadolint.cabal +@@ -155,7 +155,7 @@ library + , foldl + , gitrev >=1.3.1 + , ilist +- , language-docker >=11.0.0 && <12 ++ , language-docker >=12.0.0 && <13 + , megaparsec >=9.0.0 + , mtl + , network-uri +@@ -197,7 +197,7 @@ executable hadolint + , containers + , data-default + , hadolint +- , language-docker >=11.0.0 && <12 ++ , language-docker >=12.0.0 && <13 + , megaparsec >=9.0.0 + , optparse-applicative >=0.14.0 + , prettyprinter >=1.7.0 +@@ -323,7 +323,7 @@ test-suite hadolint-unit-tests + , foldl + , hadolint + , hspec >=2.8.3 +- , language-docker >=11.0.0 && <12 ++ , language-docker >=12.0.0 && <13 + , megaparsec >=9.0.0 + , optparse-applicative >=0.14.0 + , silently +diff --git a/package.yaml b/package.yaml +index 8763d47..61123c8 100644 +--- a/package.yaml ++++ b/package.yaml +@@ -28,7 +28,7 @@ dependencies: + - base >=4.8 && <5 + - containers + - data-default +- - language-docker >=11.0.0 && <12 ++ - language-docker >=12.0.0 && <13 + - megaparsec >= 9.0.0 + - optparse-applicative >= 0.14.0 + - text +diff --git a/src/Hadolint/Rule/DL3011.hs b/src/Hadolint/Rule/DL3011.hs +index 2a8b8cc..57a97ed 100644 +--- a/src/Hadolint/Rule/DL3011.hs ++++ b/src/Hadolint/Rule/DL3011.hs +@@ -10,7 +10,7 @@ rule = simpleRule code severity message check + severity = DLErrorC + message = "Valid UNIX ports range from 0 to 65535" + check (Expose (Ports ports)) = +- and [p <= 65535 | Port p _ <- ports] +- && and [l <= 65535 && m <= 65535 | PortRange l m _ <- ports] ++ and [p <= 65535 | PortSpec (Port p _) <- ports] ++ && and [l <= 65535 && m <= 65535 | PortRangeSpec (PortRange (Port l _) (Port m _)) <- ports] + check _ = True + {-# INLINEABLE rule #-} +diff --git a/test/Hadolint/Rule/DL3011Spec.hs b/test/Hadolint/Rule/DL3011Spec.hs +index 6e71294..820f922 100644 +--- a/test/Hadolint/Rule/DL3011Spec.hs ++++ b/test/Hadolint/Rule/DL3011Spec.hs +@@ -9,6 +9,13 @@ spec :: SpecWith () + spec = do + let ?config = def + +- describe "EXPOSE rules" $ do +- it "invalid port" $ ruleCatches "DL3011" "EXPOSE 80000" +- it "valid port" $ ruleCatchesNot "DL3011" "EXPOSE 60000" ++ describe "DL3011 - Valid UNIX ports range from 0 to 65535" $ do ++ describe "DL3011 - single port" $ do ++ it "invalid port" $ ruleCatches "DL3011" "EXPOSE 80000" ++ it "valid port" $ ruleCatchesNot "DL3011" "EXPOSE 60000" ++ it "valid port vairable" $ ruleCatchesNot "DL3011" "EXPOSE ${FOOBAR}" ++ ++ describe "DL3011 - port range" $ do ++ it "invalid port in range" $ ruleCatches "DL3011" "EXPOSE 40000-80000/tcp" ++ it "valid port range" $ ruleCatchesNot "DL3011" "EXPOSE 40000-60000/tcp" ++ it "valid port range variable" $ ruleCatchesNot "DL3011" "EXPOSE 40000-${FOOBAR}" diff --git a/tasks/hadolint__hadolint-902/solution/solve.sh b/tasks/hadolint__hadolint-902/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-902/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/hadolint__hadolint-902/task.toml b/tasks/hadolint__hadolint-902/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0cca205d6f1b61df36999f7338e53c6f1814062d --- /dev/null +++ b/tasks/hadolint__hadolint-902/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-902" +description = "DL3011: fixup changes in AST" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "fcbd01791c9251d83f2486e61ecaf41ee700a766" +reference = "https://github.com/hadolint/hadolint/pull/902" +source_access = "auto" +built_at = "2026-11-16T16:09:53.722655+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0d38a1d341aa410b367d75f032852177ffc8db50daf76aabed827e46b6fad383" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-11-16T15:40:51Z" +diff_format = "unified" +context_files = [ + ".gitignore", + "hadolint.cabal", + "package.yaml", + "src/Hadolint/Rule/DL3011.hs", + "test/Hadolint/Rule/DL3011Spec.hs", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 27 +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:00.803682+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:03b8c2f3c78d00782d14ffda3ba696b598194c41c724bb34ee64acece92eab20" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-902/tests/capture.py b/tasks/hadolint__hadolint-902/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-902/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/hadolint__hadolint-902/tests/instruction.md b/tasks/hadolint__hadolint-902/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b87edac96a81102fc7f6f8d018517bfd09359312 --- /dev/null +++ b/tasks/hadolint__hadolint-902/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** DL3011: fixup changes in AST + +## Description + +Fix up usage of the AST in DL3011 corresponding to the changes to the AST with respect to port ranges in `EXPOSE` instructions. + +requires: +fixes: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fcbd01791c92`. 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/hadolint__hadolint-902/tests/oracle.patch b/tasks/hadolint__hadolint-902/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..20333c86d9de5ec9ba23a1824d3956069650f846 --- /dev/null +++ b/tasks/hadolint__hadolint-902/tests/oracle.patch @@ -0,0 +1,89 @@ +diff --git a/.gitignore b/.gitignore +index f353de8..40ef52e 100644 +--- a/.gitignore ++++ b/.gitignore +@@ -11,3 +11,5 @@ dist-newstyle + + # travis wait is generating log in PWD + travis_wait_*.log ++ ++cabal.project.local* +diff --git a/hadolint.cabal b/hadolint.cabal +index 3e11344..1a55eac 100644 +--- a/hadolint.cabal ++++ b/hadolint.cabal +@@ -155,7 +155,7 @@ library + , foldl + , gitrev >=1.3.1 + , ilist +- , language-docker >=11.0.0 && <12 ++ , language-docker >=12.0.0 && <13 + , megaparsec >=9.0.0 + , mtl + , network-uri +@@ -197,7 +197,7 @@ executable hadolint + , containers + , data-default + , hadolint +- , language-docker >=11.0.0 && <12 ++ , language-docker >=12.0.0 && <13 + , megaparsec >=9.0.0 + , optparse-applicative >=0.14.0 + , prettyprinter >=1.7.0 +@@ -323,7 +323,7 @@ test-suite hadolint-unit-tests + , foldl + , hadolint + , hspec >=2.8.3 +- , language-docker >=11.0.0 && <12 ++ , language-docker >=12.0.0 && <13 + , megaparsec >=9.0.0 + , optparse-applicative >=0.14.0 + , silently +diff --git a/package.yaml b/package.yaml +index 8763d47..61123c8 100644 +--- a/package.yaml ++++ b/package.yaml +@@ -28,7 +28,7 @@ dependencies: + - base >=4.8 && <5 + - containers + - data-default +- - language-docker >=11.0.0 && <12 ++ - language-docker >=12.0.0 && <13 + - megaparsec >= 9.0.0 + - optparse-applicative >= 0.14.0 + - text +diff --git a/src/Hadolint/Rule/DL3011.hs b/src/Hadolint/Rule/DL3011.hs +index 2a8b8cc..57a97ed 100644 +--- a/src/Hadolint/Rule/DL3011.hs ++++ b/src/Hadolint/Rule/DL3011.hs +@@ -10,7 +10,7 @@ rule = simpleRule code severity message check + severity = DLErrorC + message = "Valid UNIX ports range from 0 to 65535" + check (Expose (Ports ports)) = +- and [p <= 65535 | Port p _ <- ports] +- && and [l <= 65535 && m <= 65535 | PortRange l m _ <- ports] ++ and [p <= 65535 | PortSpec (Port p _) <- ports] ++ && and [l <= 65535 && m <= 65535 | PortRangeSpec (PortRange (Port l _) (Port m _)) <- ports] + check _ = True + {-# INLINEABLE rule #-} +diff --git a/test/Hadolint/Rule/DL3011Spec.hs b/test/Hadolint/Rule/DL3011Spec.hs +index 6e71294..820f922 100644 +--- a/test/Hadolint/Rule/DL3011Spec.hs ++++ b/test/Hadolint/Rule/DL3011Spec.hs +@@ -9,6 +9,13 @@ spec :: SpecWith () + spec = do + let ?config = def + +- describe "EXPOSE rules" $ do +- it "invalid port" $ ruleCatches "DL3011" "EXPOSE 80000" +- it "valid port" $ ruleCatchesNot "DL3011" "EXPOSE 60000" ++ describe "DL3011 - Valid UNIX ports range from 0 to 65535" $ do ++ describe "DL3011 - single port" $ do ++ it "invalid port" $ ruleCatches "DL3011" "EXPOSE 80000" ++ it "valid port" $ ruleCatchesNot "DL3011" "EXPOSE 60000" ++ it "valid port vairable" $ ruleCatchesNot "DL3011" "EXPOSE ${FOOBAR}" ++ ++ describe "DL3011 - port range" $ do ++ it "invalid port in range" $ ruleCatches "DL3011" "EXPOSE 40000-80000/tcp" ++ it "valid port range" $ ruleCatchesNot "DL3011" "EXPOSE 40000-60000/tcp" ++ it "valid port range variable" $ ruleCatchesNot "DL3011" "EXPOSE 40000-${FOOBAR}" diff --git a/tasks/hadolint__hadolint-902/tests/test.sh b/tasks/hadolint__hadolint-902/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..367ed582d15f774dca80af3e6031e8a92873e406 --- /dev/null +++ b/tasks/hadolint__hadolint-902/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 fcbd01791c9251d83f2486e61ecaf41ee700a766 > "$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/hadolint__hadolint-902/tests/verifier.py b/tasks/hadolint__hadolint-902/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-902/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/hadolint__hadolint-910/environment/Dockerfile b/tasks/hadolint__hadolint-910/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7a5147c062a08c0f8b7ddfaabe463af99be17130 --- /dev/null +++ b/tasks/hadolint__hadolint-910/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e12f4fae04d08fa57d8f9dd4597b8f509ea83aa2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e12f4fae04d08fa57d8f9dd4597b8f509ea83aa2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e12f4fae04d08fa57d8f9dd4597b8f509ea83aa2 \ + && 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/hadolint__hadolint-910/instruction.md b/tasks/hadolint__hadolint-910/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c5cf02581095bd18ff93a779ff6006ac793a871 --- /dev/null +++ b/tasks/hadolint__hadolint-910/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** update hadolint's config json schema to support latest properties + +## Description + +### What I did + +I updated the json schema for the hadolint.yaml file + +### How I did it + +I was creating a hadolint yaml in vscode when I saw it highlighted some keys as non supported. So I added them to the hadolint.json file. + +### How to verify it + +using a jsonschema validator, such as https://check-jsonschema.readthedocs.io/en/latest/install.html + +``` +pip install check-jsonschema + +yq /path/to/.hadolint.yaml -o json > .hadolint.json + +check-jsonschema --schemafile contrib/hadolint.json .hadolint.json +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e12f4fae04d0`. 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/hadolint__hadolint-910/solution/patch.diff b/tasks/hadolint__hadolint-910/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ee3087125320cb70293e1ec20001deb74cf640fc --- /dev/null +++ b/tasks/hadolint__hadolint-910/solution/patch.diff @@ -0,0 +1,42 @@ +diff --git a/contrib/hadolint.json b/contrib/hadolint.json +index 4021330..65e4d78 100644 +--- a/contrib/hadolint.json ++++ b/contrib/hadolint.json +@@ -5,6 +5,10 @@ + "type": "object", + "additionalProperties": false, + "properties": { ++ "disable-ignore-pragma": { ++ "type": "boolean", ++ "description": "Disable inline ignore pragmas `# hadolint ignore=DLxxxx`" ++ }, + "failure-threshold": { + "type": "string", + "description": "A threshold controlling how severe a rule violation must be before the return code indicates failure.", +@@ -35,6 +39,11 @@ + } + ] + }, ++ "format": { ++ "type": "string", ++ "enum": ["tty", "json", "checkstyle", "codeclimate", "gitlab_codeclimate", "gnu", "codacy"], ++ "description": "Output format" ++ }, + "strict-labels": { + "type": "boolean", + "description": "Strictly adhere to label-schem, don't allow additional labels." +@@ -44,6 +53,14 @@ + "description": "A label-schema. See https://github.com/hadolint/hadolint#linting-labels for reference.", + "additionalProperties": true + }, ++ "no-color": { ++ "type": "boolean", ++ "description": "Don't colorize output." ++ }, ++ "no-fail": { ++ "type": "boolean", ++ "description": "Don't exit with a failure status code when any rule is violated." ++ }, + "override": { + "type": "object", + "additionalProperties": false, diff --git a/tasks/hadolint__hadolint-910/solution/solve.sh b/tasks/hadolint__hadolint-910/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-910/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/hadolint__hadolint-910/task.toml b/tasks/hadolint__hadolint-910/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6ce9d2a4d90c4864f2e86cf8abc4391ea6713c24 --- /dev/null +++ b/tasks/hadolint__hadolint-910/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-910" +description = "update hadolint's config json schema to support latest properties" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "e12f4fae04d08fa57d8f9dd4597b8f509ea83aa2" +reference = "https://github.com/hadolint/hadolint/pull/910" +source_access = "auto" +built_at = "2026-11-16T16:09:53.719933+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f76bdece3dbd4bb50cb5ac4e8f3adf0ff9dc786879fc6a8e7c351e279b0a783c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2022-12-01T10:41:45Z" +diff_format = "unified" +context_files = [ + "contrib/hadolint.json", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 17 +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:00.804173+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b737e6e9db1406f3ca33dfece72c97bdefdf21d82fbabd86d5a8759cfd04f1e3" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-910/tests/capture.py b/tasks/hadolint__hadolint-910/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-910/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/hadolint__hadolint-910/tests/instruction.md b/tasks/hadolint__hadolint-910/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c5cf02581095bd18ff93a779ff6006ac793a871 --- /dev/null +++ b/tasks/hadolint__hadolint-910/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** update hadolint's config json schema to support latest properties + +## Description + +### What I did + +I updated the json schema for the hadolint.yaml file + +### How I did it + +I was creating a hadolint yaml in vscode when I saw it highlighted some keys as non supported. So I added them to the hadolint.json file. + +### How to verify it + +using a jsonschema validator, such as https://check-jsonschema.readthedocs.io/en/latest/install.html + +``` +pip install check-jsonschema + +yq /path/to/.hadolint.yaml -o json > .hadolint.json + +check-jsonschema --schemafile contrib/hadolint.json .hadolint.json +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e12f4fae04d0`. 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/hadolint__hadolint-910/tests/oracle.patch b/tasks/hadolint__hadolint-910/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ee3087125320cb70293e1ec20001deb74cf640fc --- /dev/null +++ b/tasks/hadolint__hadolint-910/tests/oracle.patch @@ -0,0 +1,42 @@ +diff --git a/contrib/hadolint.json b/contrib/hadolint.json +index 4021330..65e4d78 100644 +--- a/contrib/hadolint.json ++++ b/contrib/hadolint.json +@@ -5,6 +5,10 @@ + "type": "object", + "additionalProperties": false, + "properties": { ++ "disable-ignore-pragma": { ++ "type": "boolean", ++ "description": "Disable inline ignore pragmas `# hadolint ignore=DLxxxx`" ++ }, + "failure-threshold": { + "type": "string", + "description": "A threshold controlling how severe a rule violation must be before the return code indicates failure.", +@@ -35,6 +39,11 @@ + } + ] + }, ++ "format": { ++ "type": "string", ++ "enum": ["tty", "json", "checkstyle", "codeclimate", "gitlab_codeclimate", "gnu", "codacy"], ++ "description": "Output format" ++ }, + "strict-labels": { + "type": "boolean", + "description": "Strictly adhere to label-schem, don't allow additional labels." +@@ -44,6 +53,14 @@ + "description": "A label-schema. See https://github.com/hadolint/hadolint#linting-labels for reference.", + "additionalProperties": true + }, ++ "no-color": { ++ "type": "boolean", ++ "description": "Don't colorize output." ++ }, ++ "no-fail": { ++ "type": "boolean", ++ "description": "Don't exit with a failure status code when any rule is violated." ++ }, + "override": { + "type": "object", + "additionalProperties": false, diff --git a/tasks/hadolint__hadolint-910/tests/test.sh b/tasks/hadolint__hadolint-910/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c5f729f63a283a950d36685756251d065cf5ad86 --- /dev/null +++ b/tasks/hadolint__hadolint-910/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 e12f4fae04d08fa57d8f9dd4597b8f509ea83aa2 > "$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/hadolint__hadolint-910/tests/verifier.py b/tasks/hadolint__hadolint-910/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-910/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/hadolint__hadolint-913/environment/Dockerfile b/tasks/hadolint__hadolint-913/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..54f4bb1c5ba27b1622bb3a9b5e8372df044a4ebb --- /dev/null +++ b/tasks/hadolint__hadolint-913/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7c54238e20ab404201b8968a6d439be3f3e5c681 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7c54238e20ab404201b8968a6d439be3f3e5c681 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7c54238e20ab404201b8968a6d439be3f3e5c681 \ + && 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/hadolint__hadolint-913/instruction.md b/tasks/hadolint__hadolint-913/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af5fd392616c6ccd08f54ccdaf522bf88f4c291d --- /dev/null +++ b/tasks/hadolint__hadolint-913/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** DL3014: Fix false positive on double quiet + +## Description + +`apt-get` can take the `--quiet` or `-q` argument to increase its quietness level. At the maximum of 2, this will also imply `assume-yes` i.e. the `-y` flag. Therefore if the necessary quietness level has been configured by command line parameters, DL3014 should not alert the user to the missing `-y` flag. + +fixes: #911 + + + +### How to verify it +Unittests are included. In any case, the following Dockerfile should no longer produce warning DL3014: + +```Dockerfile +FROM debian:stable-slim +RUN apt-get update && apt-get install --quiet --quiet sl +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7c54238e20ab`. 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/hadolint__hadolint-913/solution/patch.diff b/tasks/hadolint__hadolint-913/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..68afe270de73b1d3fc91982128401618765e8c1f --- /dev/null +++ b/tasks/hadolint__hadolint-913/solution/patch.diff @@ -0,0 +1,86 @@ +diff --git a/src/Hadolint/Rule/DL3014.hs b/src/Hadolint/Rule/DL3014.hs +index 11daa2e..278ccbf 100644 +--- a/src/Hadolint/Rule/DL3014.hs ++++ b/src/Hadolint/Rule/DL3014.hs +@@ -22,5 +22,9 @@ dl3014 = simpleRule code severity message check + + forgotAptYesOption cmd = isAptGetInstall cmd && not (hasYesOption cmd) + isAptGetInstall = Shell.cmdHasArgs "apt-get" ["install"] +- hasYesOption = Shell.hasAnyFlag ["y", "yes", "q", "assume-yes"] ++ hasYesOption cmd = ++ Shell.hasAnyFlag ["y", "yes", "qq", "assume-yes"] cmd ++ || ( Shell.countFlag "q" cmd == 2 ) ++ || ( Shell.countFlag "quiet" cmd == 2 ) ++ || "-q=2" `elem` Shell.getArgs cmd + {-# INLINEABLE dl3014 #-} +diff --git a/src/Hadolint/Shell.hs b/src/Hadolint/Shell.hs +index bae3a48..6b21e67 100644 +--- a/src/Hadolint/Shell.hs ++++ b/src/Hadolint/Shell.hs +@@ -205,6 +205,9 @@ getArgsNoFlags args = map arg $ filter (notAFlagId . partId) (arguments args) + hasFlag :: Text.Text -> Command -> Bool + hasFlag flag Command {flags} = not $ null [f | CmdPart f _ <- flags, f == flag] + ++countFlag :: Text.Text -> Command -> Int ++countFlag flag Command {flags} = length [ f | CmdPart f _ <- flags, f == flag ] ++ + hasAnyFlag :: [Text.Text] -> Command -> Bool + hasAnyFlag fs Command {flags} = not $ null [f | CmdPart f _ <- flags, f `elem` fs] + +@@ -217,9 +220,9 @@ dropFlagArg flagsToDrop Command {name, arguments, flags} = Command name filterdA + idsToDrop = Set.fromList [getValueId fId arguments | CmdPart f fId <- flags, f `elem` flagsToDrop] + filterdArgs = [arg | arg@(CmdPart _ aId) <- arguments, not (aId `Set.member` idsToDrop)] + +--- | given a flag and a command, return list of arguments for that particulat ++-- | given a flag and a command, return list of arguments for that particular + -- flag. E.g., if the command is `useradd -u 12345 luser` and this function is +--- called for the command `u`, it returns ["12345"]. ++-- called for the flag `u`, it returns ["12345"]. + getFlagArg :: Text.Text -> Command -> [Text.Text] + getFlagArg flag Command {arguments, flags} = extractArgs + where +diff --git a/test/Hadolint/Rule/DL3014Spec.hs b/test/Hadolint/Rule/DL3014Spec.hs +index dcb3d58..303325e 100644 +--- a/test/Hadolint/Rule/DL3014Spec.hs ++++ b/test/Hadolint/Rule/DL3014Spec.hs +@@ -13,12 +13,18 @@ spec = do + it "apt-get auto yes" $ do + ruleCatches "DL3014" "RUN apt-get install python" + onBuildRuleCatches "DL3014" "RUN apt-get install python" ++ ++ describe "Insufficient Quiet Levels" $ do ++ it "apt-get -q" $ do ++ ruleCatches "DL3014" "RUN apt-get install -q python" ++ onBuildRuleCatches "DL3014" "RUN apt-get install -q python" ++ it "apt-get --quiet" $ do ++ ruleCatches "DL3014" "RUN apt-get install --quiet python" ++ onBuildRuleCatches "DL3014" "RUN apt-get install -q python" ++ + it "apt-get yes shortflag" $ do + ruleCatchesNot "DL3014" "RUN apt-get install -yq python" + onBuildRuleCatchesNot "DL3014" "RUN apt-get install -yq python" +- it "apt-get yes quiet level 2 implies -y" $ do +- ruleCatchesNot "DL3014" "RUN apt-get install -qq python" +- onBuildRuleCatchesNot "DL3014" "RUN apt-get install -qq python" + it "apt-get yes different pos" $ do + ruleCatchesNot "DL3014" "RUN apt-get install -y python" + onBuildRuleCatchesNot "DL3014" "RUN apt-get install -y python" +@@ -31,3 +37,18 @@ spec = do + it "apt-get with assume-yes" $ do + ruleCatchesNot "DL3014" "RUN apt-get --assume-yes install python" + onBuildRuleCatchesNot "DL3014" "RUN apt-get --assume-yes install python" ++ ++ describe "Quiet level 2 implies assume-yes" $ do ++ it "apt-get -qq" $ do ++ ruleCatchesNot "DL3014" "RUN apt-get install -qq python" ++ onBuildRuleCatchesNot "DL3014" "RUN apt-get install -qq python" ++ it "apt-get -q -q" $ do ++ ruleCatchesNot "DL3014" "RUN apt-get install -q -q python" ++ onBuildRuleCatchesNot "DL3014" "RUN apt-get install -q -q python" ++ it "apt-get -q=2" $ do ++ ruleCatchesNot "DL3014" "RUN apt-get install -q=2 python" ++ onBuildRuleCatchesNot "DL3014" "RUN apt-get install -q=2 python" ++ it "apt-get --quiet --quiet" $ do ++ ruleCatchesNot "DL3014" "RUN apt-get install --quiet --quiet python" ++ onBuildRuleCatchesNot "DL3014" ++ "RUN apt-get install --quiet --quiet python" diff --git a/tasks/hadolint__hadolint-913/solution/solve.sh b/tasks/hadolint__hadolint-913/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-913/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/hadolint__hadolint-913/task.toml b/tasks/hadolint__hadolint-913/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..98357bb84c4ba9b24f0090df66d9c8651c04ab78 --- /dev/null +++ b/tasks/hadolint__hadolint-913/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-913" +description = "DL3014: Fix false positive on double quiet" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "7c54238e20ab404201b8968a6d439be3f3e5c681" +reference = "https://github.com/hadolint/hadolint/pull/913" +source_access = "auto" +built_at = "2026-11-16T16:09:53.718624+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d68ae325e62a13f84333b11219fd649f7dbfee005699035372f02334b2e8bf0d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-01-30T08:50:43Z" +diff_format = "unified" +context_files = [ + "src/Hadolint/Rule/DL3014.hs", + "src/Hadolint/Shell.hs", + "test/Hadolint/Rule/DL3014Spec.hs", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 38 +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:00.804631+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:42f240578bd9c2832958caa98b353a79d24b8e56cbeb22bd2a2a9a9687a2c9cc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-913/tests/capture.py b/tasks/hadolint__hadolint-913/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-913/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/hadolint__hadolint-913/tests/instruction.md b/tasks/hadolint__hadolint-913/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af5fd392616c6ccd08f54ccdaf522bf88f4c291d --- /dev/null +++ b/tasks/hadolint__hadolint-913/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** DL3014: Fix false positive on double quiet + +## Description + +`apt-get` can take the `--quiet` or `-q` argument to increase its quietness level. At the maximum of 2, this will also imply `assume-yes` i.e. the `-y` flag. Therefore if the necessary quietness level has been configured by command line parameters, DL3014 should not alert the user to the missing `-y` flag. + +fixes: #911 + + + +### How to verify it +Unittests are included. In any case, the following Dockerfile should no longer produce warning DL3014: + +```Dockerfile +FROM debian:stable-slim +RUN apt-get update && apt-get install --quiet --quiet sl +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7c54238e20ab`. 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/hadolint__hadolint-913/tests/oracle.patch b/tasks/hadolint__hadolint-913/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..68afe270de73b1d3fc91982128401618765e8c1f --- /dev/null +++ b/tasks/hadolint__hadolint-913/tests/oracle.patch @@ -0,0 +1,86 @@ +diff --git a/src/Hadolint/Rule/DL3014.hs b/src/Hadolint/Rule/DL3014.hs +index 11daa2e..278ccbf 100644 +--- a/src/Hadolint/Rule/DL3014.hs ++++ b/src/Hadolint/Rule/DL3014.hs +@@ -22,5 +22,9 @@ dl3014 = simpleRule code severity message check + + forgotAptYesOption cmd = isAptGetInstall cmd && not (hasYesOption cmd) + isAptGetInstall = Shell.cmdHasArgs "apt-get" ["install"] +- hasYesOption = Shell.hasAnyFlag ["y", "yes", "q", "assume-yes"] ++ hasYesOption cmd = ++ Shell.hasAnyFlag ["y", "yes", "qq", "assume-yes"] cmd ++ || ( Shell.countFlag "q" cmd == 2 ) ++ || ( Shell.countFlag "quiet" cmd == 2 ) ++ || "-q=2" `elem` Shell.getArgs cmd + {-# INLINEABLE dl3014 #-} +diff --git a/src/Hadolint/Shell.hs b/src/Hadolint/Shell.hs +index bae3a48..6b21e67 100644 +--- a/src/Hadolint/Shell.hs ++++ b/src/Hadolint/Shell.hs +@@ -205,6 +205,9 @@ getArgsNoFlags args = map arg $ filter (notAFlagId . partId) (arguments args) + hasFlag :: Text.Text -> Command -> Bool + hasFlag flag Command {flags} = not $ null [f | CmdPart f _ <- flags, f == flag] + ++countFlag :: Text.Text -> Command -> Int ++countFlag flag Command {flags} = length [ f | CmdPart f _ <- flags, f == flag ] ++ + hasAnyFlag :: [Text.Text] -> Command -> Bool + hasAnyFlag fs Command {flags} = not $ null [f | CmdPart f _ <- flags, f `elem` fs] + +@@ -217,9 +220,9 @@ dropFlagArg flagsToDrop Command {name, arguments, flags} = Command name filterdA + idsToDrop = Set.fromList [getValueId fId arguments | CmdPart f fId <- flags, f `elem` flagsToDrop] + filterdArgs = [arg | arg@(CmdPart _ aId) <- arguments, not (aId `Set.member` idsToDrop)] + +--- | given a flag and a command, return list of arguments for that particulat ++-- | given a flag and a command, return list of arguments for that particular + -- flag. E.g., if the command is `useradd -u 12345 luser` and this function is +--- called for the command `u`, it returns ["12345"]. ++-- called for the flag `u`, it returns ["12345"]. + getFlagArg :: Text.Text -> Command -> [Text.Text] + getFlagArg flag Command {arguments, flags} = extractArgs + where +diff --git a/test/Hadolint/Rule/DL3014Spec.hs b/test/Hadolint/Rule/DL3014Spec.hs +index dcb3d58..303325e 100644 +--- a/test/Hadolint/Rule/DL3014Spec.hs ++++ b/test/Hadolint/Rule/DL3014Spec.hs +@@ -13,12 +13,18 @@ spec = do + it "apt-get auto yes" $ do + ruleCatches "DL3014" "RUN apt-get install python" + onBuildRuleCatches "DL3014" "RUN apt-get install python" ++ ++ describe "Insufficient Quiet Levels" $ do ++ it "apt-get -q" $ do ++ ruleCatches "DL3014" "RUN apt-get install -q python" ++ onBuildRuleCatches "DL3014" "RUN apt-get install -q python" ++ it "apt-get --quiet" $ do ++ ruleCatches "DL3014" "RUN apt-get install --quiet python" ++ onBuildRuleCatches "DL3014" "RUN apt-get install -q python" ++ + it "apt-get yes shortflag" $ do + ruleCatchesNot "DL3014" "RUN apt-get install -yq python" + onBuildRuleCatchesNot "DL3014" "RUN apt-get install -yq python" +- it "apt-get yes quiet level 2 implies -y" $ do +- ruleCatchesNot "DL3014" "RUN apt-get install -qq python" +- onBuildRuleCatchesNot "DL3014" "RUN apt-get install -qq python" + it "apt-get yes different pos" $ do + ruleCatchesNot "DL3014" "RUN apt-get install -y python" + onBuildRuleCatchesNot "DL3014" "RUN apt-get install -y python" +@@ -31,3 +37,18 @@ spec = do + it "apt-get with assume-yes" $ do + ruleCatchesNot "DL3014" "RUN apt-get --assume-yes install python" + onBuildRuleCatchesNot "DL3014" "RUN apt-get --assume-yes install python" ++ ++ describe "Quiet level 2 implies assume-yes" $ do ++ it "apt-get -qq" $ do ++ ruleCatchesNot "DL3014" "RUN apt-get install -qq python" ++ onBuildRuleCatchesNot "DL3014" "RUN apt-get install -qq python" ++ it "apt-get -q -q" $ do ++ ruleCatchesNot "DL3014" "RUN apt-get install -q -q python" ++ onBuildRuleCatchesNot "DL3014" "RUN apt-get install -q -q python" ++ it "apt-get -q=2" $ do ++ ruleCatchesNot "DL3014" "RUN apt-get install -q=2 python" ++ onBuildRuleCatchesNot "DL3014" "RUN apt-get install -q=2 python" ++ it "apt-get --quiet --quiet" $ do ++ ruleCatchesNot "DL3014" "RUN apt-get install --quiet --quiet python" ++ onBuildRuleCatchesNot "DL3014" ++ "RUN apt-get install --quiet --quiet python" diff --git a/tasks/hadolint__hadolint-913/tests/test.sh b/tasks/hadolint__hadolint-913/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2e0d9462d4f027aaf005300526a64eabc63b4ca6 --- /dev/null +++ b/tasks/hadolint__hadolint-913/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 7c54238e20ab404201b8968a6d439be3f3e5c681 > "$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/hadolint__hadolint-913/tests/verifier.py b/tasks/hadolint__hadolint-913/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-913/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/hadolint__hadolint-927/environment/Dockerfile b/tasks/hadolint__hadolint-927/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..54f4bb1c5ba27b1622bb3a9b5e8372df044a4ebb --- /dev/null +++ b/tasks/hadolint__hadolint-927/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7c54238e20ab404201b8968a6d439be3f3e5c681 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7c54238e20ab404201b8968a6d439be3f3e5c681 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7c54238e20ab404201b8968a6d439be3f3e5c681 \ + && 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/hadolint__hadolint-927/instruction.md b/tasks/hadolint__hadolint-927/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d82025b218fe0d134eb93ceef1e46ec401940002 --- /dev/null +++ b/tasks/hadolint__hadolint-927/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Add LABEL org.opencontainers.image.source="https://github.com/hadolin… + +## Description + +…t/hadolint" to dockerfile + + + +### What I did + +Added LABEL org.opencontainers.image.source="https://github.com/hadolint/hadolint" + +### How I did it + +### How to verify it + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7c54238e20ab`. 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/hadolint__hadolint-927/solution/patch.diff b/tasks/hadolint__hadolint-927/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..266bdcc3492ac469076a789479a2ed8d432a017d --- /dev/null +++ b/tasks/hadolint__hadolint-927/solution/patch.diff @@ -0,0 +1,21 @@ +diff --git a/docker/Dockerfile b/docker/Dockerfile +index adf0be2..c8ce720 100644 +--- a/docker/Dockerfile ++++ b/docker/Dockerfile +@@ -1,11 +1,14 @@ + FROM scratch as base + COPY --chmod=777 hadolint /bin/hadolint ++LABEL org.opencontainers.image.source="https://github.com/hadolint/hadolint" + CMD ["/bin/hadolint", "-"] + + FROM debian:bullseye-slim as debian + COPY --chmod=777 hadolint /bin/hadolint ++LABEL org.opencontainers.image.source="https://github.com/hadolint/hadolint" + CMD ["/bin/hadolint", "-"] + + FROM alpine:3.15 as alpine + COPY --chmod=777 hadolint /bin/hadolint +-CMD ["/bin/hadolint", "-"] +\ No newline at end of file ++LABEL org.opencontainers.image.source="https://github.com/hadolint/hadolint" ++CMD ["/bin/hadolint", "-"] diff --git a/tasks/hadolint__hadolint-927/solution/solve.sh b/tasks/hadolint__hadolint-927/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-927/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/hadolint__hadolint-927/task.toml b/tasks/hadolint__hadolint-927/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4210f64c612731701f205efc6e4d87f3daf416f9 --- /dev/null +++ b/tasks/hadolint__hadolint-927/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-927" +description = "Add LABEL org.opencontainers.image.source=\"https://github.com/hadolin…" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "7c54238e20ab404201b8968a6d439be3f3e5c681" +reference = "https://github.com/hadolint/hadolint/pull/927" +source_access = "auto" +built_at = "2026-11-16T16:09:53.717364+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:74cd2fb9da5a7d26668f0001638d4d2d88c074f773f07cdeb01c36224972bd1d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-01-30T08:49:56Z" +diff_format = "unified" +context_files = [ + "docker/Dockerfile", +] +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:00.805105+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:42f240578bd9c2832958caa98b353a79d24b8e56cbeb22bd2a2a9a9687a2c9cc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-927/tests/capture.py b/tasks/hadolint__hadolint-927/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-927/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/hadolint__hadolint-927/tests/instruction.md b/tasks/hadolint__hadolint-927/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d82025b218fe0d134eb93ceef1e46ec401940002 --- /dev/null +++ b/tasks/hadolint__hadolint-927/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** Add LABEL org.opencontainers.image.source="https://github.com/hadolin… + +## Description + +…t/hadolint" to dockerfile + + + +### What I did + +Added LABEL org.opencontainers.image.source="https://github.com/hadolint/hadolint" + +### How I did it + +### How to verify it + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7c54238e20ab`. 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/hadolint__hadolint-927/tests/oracle.patch b/tasks/hadolint__hadolint-927/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..266bdcc3492ac469076a789479a2ed8d432a017d --- /dev/null +++ b/tasks/hadolint__hadolint-927/tests/oracle.patch @@ -0,0 +1,21 @@ +diff --git a/docker/Dockerfile b/docker/Dockerfile +index adf0be2..c8ce720 100644 +--- a/docker/Dockerfile ++++ b/docker/Dockerfile +@@ -1,11 +1,14 @@ + FROM scratch as base + COPY --chmod=777 hadolint /bin/hadolint ++LABEL org.opencontainers.image.source="https://github.com/hadolint/hadolint" + CMD ["/bin/hadolint", "-"] + + FROM debian:bullseye-slim as debian + COPY --chmod=777 hadolint /bin/hadolint ++LABEL org.opencontainers.image.source="https://github.com/hadolint/hadolint" + CMD ["/bin/hadolint", "-"] + + FROM alpine:3.15 as alpine + COPY --chmod=777 hadolint /bin/hadolint +-CMD ["/bin/hadolint", "-"] +\ No newline at end of file ++LABEL org.opencontainers.image.source="https://github.com/hadolint/hadolint" ++CMD ["/bin/hadolint", "-"] diff --git a/tasks/hadolint__hadolint-927/tests/test.sh b/tasks/hadolint__hadolint-927/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2e0d9462d4f027aaf005300526a64eabc63b4ca6 --- /dev/null +++ b/tasks/hadolint__hadolint-927/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 7c54238e20ab404201b8968a6d439be3f3e5c681 > "$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/hadolint__hadolint-927/tests/verifier.py b/tasks/hadolint__hadolint-927/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-927/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/hadolint__hadolint-931/environment/Dockerfile b/tasks/hadolint__hadolint-931/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cfad13f055e05075d5720ed97d606d8c7f35442a --- /dev/null +++ b/tasks/hadolint__hadolint-931/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 91976038644d470092d3906ce6cf7240fa0e821a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 91976038644d470092d3906ce6cf7240fa0e821a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 91976038644d470092d3906ce6cf7240fa0e821a \ + && 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/hadolint__hadolint-931/instruction.md b/tasks/hadolint__hadolint-931/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..67397d3f6687e9b48f9a9ba7aad18151e980e675 --- /dev/null +++ b/tasks/hadolint__hadolint-931/instruction.md @@ -0,0 +1,105 @@ +# Issue + +**Title:** build(deps): bump docker/build-push-action from 3 to 4 + +## Description + +Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 3 to 4. +
+Release notes +

Sourced from docker/build-push-action's releases.

+
+

v4.0.0

+
+

Note

+

Buildx v0.10 enables support for a minimal SLSA Provenance attestation, which requires support for OCI-compliant multi-platform images. This may introduce issues with registry and runtime support (e.g. Google Cloud Run and AWS Lambda). You can optionally disable the default provenance attestation functionality using provenance: false.

+
+ +

Full Changelog: https://github.com/docker/build-push-action/compare/v3.3.1...v4.0.0

+

v3.3.1

+ +

Full Changelog: https://github.com/docker/build-push-action/compare/v3.3.0...v3.3.1

+

v3.3.0

+
+

Note

+

Buildx v0.10 enables support for a minimal SLSA Provenance attestation, which requires support for OCI-compliant multi-platform images. This may introduce issues with registry and runtime support (e.g. Google Cloud Run and AWS Lambda). You can optionally disable the default provenance attestation functionality using provenance: false.

+
+ +

Full Changelog: https://github.com/docker/build-push-action/compare/v3.2.0...v3.3.0

+

v3.2.0

+ +

Full Changelog: https://github.com/docker/build-push-action/compare/v3.1.1...v3.2.0

+

v3.1.1

+ +

Full Changelog: https://github.com/docker/build-push-action/compare/v3.1.0...v3.1.1

+

v3.1.0

+
    +
  • no-cache-filters input by @​crazy-max (#653)
  • +
  • Bump @​actions/github from 5.0.1 to 5.0.3 (#619)
  • +
  • Bump @​actions/core from 1.6.0 to 1.9.0 (#620 #637)
  • +
  • Bump csv-parse from 5.0.4 to 5.3.0 (#623 #650)
  • +
+

Full Changelog: https://github.com/docker/build-push-action/compare/v3.0.0...v3.1.0

+
+
+
+Commits +
    +
  • 3b5e802 Merge pull request #784 from crazy-max/enable-provenance
  • +
  • 02d3266 update generated content
  • +
  • f403daf revert disable provenance by default if not set
  • +
  • See full diff in compare view
  • +
+
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=docker/build-push-action&package-manager=github_actions&previous-version=3&new-version=4)](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) + +--- + +
+Dependabot commands and options +
+ +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 merge` will merge this PR after your CI passes on it +- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it +- `@dependabot cancel merge` will cancel a previously requested merge and block automerging +- `@dependabot reopen` will reopen this PR if it is closed +- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually +- `@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) + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `91976038644d`. 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/hadolint__hadolint-931/solution/patch.diff b/tasks/hadolint__hadolint-931/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1d77fe356a7e227c11935aecf6efdad04a18522b --- /dev/null +++ b/tasks/hadolint__hadolint-931/solution/patch.diff @@ -0,0 +1,31 @@ +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index 97ec280..56449d2 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -91,7 +91,7 @@ jobs: + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Push Docker Image Scratch +- uses: docker/build-push-action@v3 ++ uses: docker/build-push-action@v4 + with: + context: ${{matrix.target}} + file: docker/Dockerfile +@@ -103,7 +103,7 @@ jobs: + hadolint/hadolint:${{github.sha}}-${{matrix.target}} + + - name: Push Docker Image Debian +- uses: docker/build-push-action@v3 ++ uses: docker/build-push-action@v4 + with: + context: ${{matrix.target}} + file: docker/Dockerfile +@@ -115,7 +115,7 @@ jobs: + hadolint/hadolint:${{github.sha}}-debian-${{matrix.target}} + + - name: Push Docker Image Alpine +- uses: docker/build-push-action@v3 ++ uses: docker/build-push-action@v4 + with: + context: ${{matrix.target}} + file: docker/Dockerfile diff --git a/tasks/hadolint__hadolint-931/solution/solve.sh b/tasks/hadolint__hadolint-931/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-931/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/hadolint__hadolint-931/task.toml b/tasks/hadolint__hadolint-931/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8104c32e38b1e9a525cefd90024fc43214a8b8ff --- /dev/null +++ b/tasks/hadolint__hadolint-931/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-931" +description = "build(deps): bump docker/build-push-action from 3 to 4" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "91976038644d470092d3906ce6cf7240fa0e821a" +reference = "https://github.com/hadolint/hadolint/pull/931" +source_access = "auto" +built_at = "2026-11-16T16:09:53.710039+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d0b1e0b32efc722ae3542eb678a7a5d47b89177d24662f189e9d6278071f2bcd" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-04-05T08:15:16Z" +diff_format = "unified" +context_files = [ + ".github/workflows/release.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:00.805571+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f001a0eebe77009917ccfbbec362d23020555094646df417e1ec56ceac398ea3" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-931/tests/capture.py b/tasks/hadolint__hadolint-931/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-931/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/hadolint__hadolint-931/tests/instruction.md b/tasks/hadolint__hadolint-931/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..67397d3f6687e9b48f9a9ba7aad18151e980e675 --- /dev/null +++ b/tasks/hadolint__hadolint-931/tests/instruction.md @@ -0,0 +1,105 @@ +# Issue + +**Title:** build(deps): bump docker/build-push-action from 3 to 4 + +## Description + +Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 3 to 4. +
+Release notes +

Sourced from docker/build-push-action's releases.

+
+

v4.0.0

+
+

Note

+

Buildx v0.10 enables support for a minimal SLSA Provenance attestation, which requires support for OCI-compliant multi-platform images. This may introduce issues with registry and runtime support (e.g. Google Cloud Run and AWS Lambda). You can optionally disable the default provenance attestation functionality using provenance: false.

+
+ +

Full Changelog: https://github.com/docker/build-push-action/compare/v3.3.1...v4.0.0

+

v3.3.1

+ +

Full Changelog: https://github.com/docker/build-push-action/compare/v3.3.0...v3.3.1

+

v3.3.0

+
+

Note

+

Buildx v0.10 enables support for a minimal SLSA Provenance attestation, which requires support for OCI-compliant multi-platform images. This may introduce issues with registry and runtime support (e.g. Google Cloud Run and AWS Lambda). You can optionally disable the default provenance attestation functionality using provenance: false.

+
+ +

Full Changelog: https://github.com/docker/build-push-action/compare/v3.2.0...v3.3.0

+

v3.2.0

+ +

Full Changelog: https://github.com/docker/build-push-action/compare/v3.1.1...v3.2.0

+

v3.1.1

+ +

Full Changelog: https://github.com/docker/build-push-action/compare/v3.1.0...v3.1.1

+

v3.1.0

+
    +
  • no-cache-filters input by @​crazy-max (#653)
  • +
  • Bump @​actions/github from 5.0.1 to 5.0.3 (#619)
  • +
  • Bump @​actions/core from 1.6.0 to 1.9.0 (#620 #637)
  • +
  • Bump csv-parse from 5.0.4 to 5.3.0 (#623 #650)
  • +
+

Full Changelog: https://github.com/docker/build-push-action/compare/v3.0.0...v3.1.0

+
+
+
+Commits +
    +
  • 3b5e802 Merge pull request #784 from crazy-max/enable-provenance
  • +
  • 02d3266 update generated content
  • +
  • f403daf revert disable provenance by default if not set
  • +
  • See full diff in compare view
  • +
+
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=docker/build-push-action&package-manager=github_actions&previous-version=3&new-version=4)](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) + +--- + +
+Dependabot commands and options +
+ +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 merge` will merge this PR after your CI passes on it +- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it +- `@dependabot cancel merge` will cancel a previously requested merge and block automerging +- `@dependabot reopen` will reopen this PR if it is closed +- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually +- `@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) + +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `91976038644d`. 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/hadolint__hadolint-931/tests/oracle.patch b/tasks/hadolint__hadolint-931/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1d77fe356a7e227c11935aecf6efdad04a18522b --- /dev/null +++ b/tasks/hadolint__hadolint-931/tests/oracle.patch @@ -0,0 +1,31 @@ +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index 97ec280..56449d2 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -91,7 +91,7 @@ jobs: + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Push Docker Image Scratch +- uses: docker/build-push-action@v3 ++ uses: docker/build-push-action@v4 + with: + context: ${{matrix.target}} + file: docker/Dockerfile +@@ -103,7 +103,7 @@ jobs: + hadolint/hadolint:${{github.sha}}-${{matrix.target}} + + - name: Push Docker Image Debian +- uses: docker/build-push-action@v3 ++ uses: docker/build-push-action@v4 + with: + context: ${{matrix.target}} + file: docker/Dockerfile +@@ -115,7 +115,7 @@ jobs: + hadolint/hadolint:${{github.sha}}-debian-${{matrix.target}} + + - name: Push Docker Image Alpine +- uses: docker/build-push-action@v3 ++ uses: docker/build-push-action@v4 + with: + context: ${{matrix.target}} + file: docker/Dockerfile diff --git a/tasks/hadolint__hadolint-931/tests/test.sh b/tasks/hadolint__hadolint-931/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1d0c222d02055427ccf5d7f5d293c247d2f39655 --- /dev/null +++ b/tasks/hadolint__hadolint-931/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 91976038644d470092d3906ce6cf7240fa0e821a > "$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/hadolint__hadolint-931/tests/verifier.py b/tasks/hadolint__hadolint-931/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-931/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/hadolint__hadolint-940/environment/Dockerfile b/tasks/hadolint__hadolint-940/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b78e17d44233f22fd159fe61a2e9de7a84576688 --- /dev/null +++ b/tasks/hadolint__hadolint-940/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin dc66e0996474b324f10649618f424fc76ca60e28 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard dc66e0996474b324f10649618f424fc76ca60e28 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base dc66e0996474b324f10649618f424fc76ca60e28 \ + && 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/hadolint__hadolint-940/instruction.md b/tasks/hadolint__hadolint-940/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9fcf22a7a658242816f13439b400ae83d371aa6f --- /dev/null +++ b/tasks/hadolint__hadolint-940/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** fix: misidentification of pipenv + +## Description + +### What I did + +Check that when we detect `pip` it's not actually `pipenv`. This . + +### How I did it + +Add an extra `&& not (…)` check. + +### How to verify it + +Run Hadolint on this Dockerfile: + +``` +FROM python:3.10 +RUN pip install --no-cache-dir pipenv==2023.2.18 \ + && python3 -m venv /venv +RUN pipenv install --python 3.10 --keep-outdated --ignore-pipfile \ + && rm -rf /root/.cache/pipenv +``` + +It raises DL3013 on the current version of Hadolint and nothing on my fork. + +(Caveat: I had to compile with a newer `base` package, but the change should be simple enough that it makes no difference.) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `dc66e0996474`. 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/hadolint__hadolint-940/solution/patch.diff b/tasks/hadolint__hadolint-940/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..008e06714eed2f5abd3456b15478bfc248e99ef1 --- /dev/null +++ b/tasks/hadolint__hadolint-940/solution/patch.diff @@ -0,0 +1,23 @@ +diff --git a/src/Hadolint/Shell.hs b/src/Hadolint/Shell.hs +index d67ff13..7ab6a09 100644 +--- a/src/Hadolint/Shell.hs ++++ b/src/Hadolint/Shell.hs +@@ -241,6 +241,7 @@ isPipInstall cmd@(Command name _ _) = isStdPipInstall || isPythonPipInstall + where + isStdPipInstall = + "pip" `Text.isPrefixOf` name ++ && not ("pipenv" `Text.isPrefixOf` name) + && ["install"] `isInfixOf` getArgs cmd + isPythonPipInstall = + "python" `Text.isPrefixOf` name +diff --git a/test/Hadolint/Rule/DL3013Spec.hs b/test/Hadolint/Rule/DL3013Spec.hs +index a9315f3..2a94ac6 100644 +--- a/test/Hadolint/Rule/DL3013Spec.hs ++++ b/test/Hadolint/Rule/DL3013Spec.hs +@@ -165,3 +165,6 @@ spec = do + onBuildRuleCatchesNot + "DL3013" + "RUN pip install --index-url https://user:pass@eg.com/foo --extra-index-url https://user:pass@ex-eg.io/foo foobar==1.0.0" ++ it "pipenv is not pip" $ do ++ ruleCatchesNot "DL3013" "RUN pipenv install black" ++ onBuildRuleCatchesNot "DL3013" "RUN pipenv install black" diff --git a/tasks/hadolint__hadolint-940/solution/solve.sh b/tasks/hadolint__hadolint-940/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-940/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/hadolint__hadolint-940/task.toml b/tasks/hadolint__hadolint-940/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9d43cbea47fe1019aee3a2a23daf53ce879f34ff --- /dev/null +++ b/tasks/hadolint__hadolint-940/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-940" +description = "fix: misidentification of pipenv (#366)" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "dc66e0996474b324f10649618f424fc76ca60e28" +reference = "https://github.com/hadolint/hadolint/pull/940" +source_access = "auto" +built_at = "2026-11-16T16:09:53.716065+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3e36929e057cbe8058469054ddce54f116a4002a795c8bbeb770fb15a9b04f50" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-02-28T08:01:51Z" +diff_format = "unified" +context_files = [ + "src/Hadolint/Shell.hs", + "test/Hadolint/Rule/DL3013Spec.hs", +] +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:00.806071+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f1f9c2978b764172895c8d50d99485ea2505bd33a65edbdb1eb91f436a4f7ede" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-940/tests/capture.py b/tasks/hadolint__hadolint-940/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-940/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/hadolint__hadolint-940/tests/instruction.md b/tasks/hadolint__hadolint-940/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9fcf22a7a658242816f13439b400ae83d371aa6f --- /dev/null +++ b/tasks/hadolint__hadolint-940/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** fix: misidentification of pipenv + +## Description + +### What I did + +Check that when we detect `pip` it's not actually `pipenv`. This . + +### How I did it + +Add an extra `&& not (…)` check. + +### How to verify it + +Run Hadolint on this Dockerfile: + +``` +FROM python:3.10 +RUN pip install --no-cache-dir pipenv==2023.2.18 \ + && python3 -m venv /venv +RUN pipenv install --python 3.10 --keep-outdated --ignore-pipfile \ + && rm -rf /root/.cache/pipenv +``` + +It raises DL3013 on the current version of Hadolint and nothing on my fork. + +(Caveat: I had to compile with a newer `base` package, but the change should be simple enough that it makes no difference.) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `dc66e0996474`. 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/hadolint__hadolint-940/tests/oracle.patch b/tasks/hadolint__hadolint-940/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..008e06714eed2f5abd3456b15478bfc248e99ef1 --- /dev/null +++ b/tasks/hadolint__hadolint-940/tests/oracle.patch @@ -0,0 +1,23 @@ +diff --git a/src/Hadolint/Shell.hs b/src/Hadolint/Shell.hs +index d67ff13..7ab6a09 100644 +--- a/src/Hadolint/Shell.hs ++++ b/src/Hadolint/Shell.hs +@@ -241,6 +241,7 @@ isPipInstall cmd@(Command name _ _) = isStdPipInstall || isPythonPipInstall + where + isStdPipInstall = + "pip" `Text.isPrefixOf` name ++ && not ("pipenv" `Text.isPrefixOf` name) + && ["install"] `isInfixOf` getArgs cmd + isPythonPipInstall = + "python" `Text.isPrefixOf` name +diff --git a/test/Hadolint/Rule/DL3013Spec.hs b/test/Hadolint/Rule/DL3013Spec.hs +index a9315f3..2a94ac6 100644 +--- a/test/Hadolint/Rule/DL3013Spec.hs ++++ b/test/Hadolint/Rule/DL3013Spec.hs +@@ -165,3 +165,6 @@ spec = do + onBuildRuleCatchesNot + "DL3013" + "RUN pip install --index-url https://user:pass@eg.com/foo --extra-index-url https://user:pass@ex-eg.io/foo foobar==1.0.0" ++ it "pipenv is not pip" $ do ++ ruleCatchesNot "DL3013" "RUN pipenv install black" ++ onBuildRuleCatchesNot "DL3013" "RUN pipenv install black" diff --git a/tasks/hadolint__hadolint-940/tests/test.sh b/tasks/hadolint__hadolint-940/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4c7faa99889230c694cfca69eefb9f19d3f51ada --- /dev/null +++ b/tasks/hadolint__hadolint-940/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 dc66e0996474b324f10649618f424fc76ca60e28 > "$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/hadolint__hadolint-940/tests/verifier.py b/tasks/hadolint__hadolint-940/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-940/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/hadolint__hadolint-942/environment/Dockerfile b/tasks/hadolint__hadolint-942/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d260227ab5fc326087316a834a82eb673173c8c4 --- /dev/null +++ b/tasks/hadolint__hadolint-942/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6cab02ad0143cf334fe276cb7240f0263674be2d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6cab02ad0143cf334fe276cb7240f0263674be2d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6cab02ad0143cf334fe276cb7240f0263674be2d \ + && 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/hadolint__hadolint-942/instruction.md b/tasks/hadolint__hadolint-942/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..997d8f8b04afab2c44621d5df244357e048f4fa4 --- /dev/null +++ b/tasks/hadolint__hadolint-942/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** fix: fp in `DL3006` + +## Description + + + +### What I did + +ensure we don't raise if image name is an arg + +### How I did it + +names can't start with `$` + +### How to verify it + +added a test, which fails if changes not present + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6cab02ad0143`. 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/hadolint__hadolint-942/solution/patch.diff b/tasks/hadolint__hadolint-942/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..68b08d4723f99fc7e4899a90d8fd4fe7c1a79e87 --- /dev/null +++ b/tasks/hadolint__hadolint-942/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/src/Hadolint/Rule/DL3006.hs b/src/Hadolint/Rule/DL3006.hs +index d54c503..edfdc1c 100644 +--- a/src/Hadolint/Rule/DL3006.hs ++++ b/src/Hadolint/Rule/DL3006.hs +@@ -1,6 +1,7 @@ + module Hadolint.Rule.DL3006 (rule) where + + import qualified Data.Set as Set ++import qualified Data.Text as Text + import Data.Text (Text) + import Hadolint.Rule + import Language.Docker.Syntax +@@ -21,7 +22,7 @@ rule = customRule check (emptyState Set.empty) + -- When the image being used is a previously defined FROM alias, + -- then we can safely ignore that the image is not tagged. Otherwise + -- we marked it as a failure +- if Set.member i (state st) ++ if Text.isPrefixOf "$" i || Set.member i (state st) + then newState + else newState |> addFail (CheckFailure {..}) + _ -> newState +diff --git a/test/Hadolint/Rule/DL3006Spec.hs b/test/Hadolint/Rule/DL3006Spec.hs +index 876bd11..6ede7e2 100644 +--- a/test/Hadolint/Rule/DL3006Spec.hs ++++ b/test/Hadolint/Rule/DL3006Spec.hs +@@ -17,6 +17,8 @@ spec = do + ruleCatchesNot "DL3006" "FROM ruby@sha256:f1dbca0f5dbc9" + it "untagged digest is not an error" $ + ruleCatchesNot "DL3006" "FROM ruby:2" ++ it "using args is not an error" $ ++ ruleCatchesNot "DL3006" "FROM ${VALUE}" + it "local aliases are OK to be untagged" $ + let dockerFile = + [ "FROM golang:1.9.3-alpine3.7 AS build", diff --git a/tasks/hadolint__hadolint-942/solution/solve.sh b/tasks/hadolint__hadolint-942/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-942/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/hadolint__hadolint-942/task.toml b/tasks/hadolint__hadolint-942/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2c677323c6ee6bd66907372d01b2514a8de5f30f --- /dev/null +++ b/tasks/hadolint__hadolint-942/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-942" +description = "fix: fp in `DL3006`" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "6cab02ad0143cf334fe276cb7240f0263674be2d" +reference = "https://github.com/hadolint/hadolint/pull/942" +source_access = "auto" +built_at = "2026-11-16T16:09:53.705159+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:911c38f8b4573d6cae19c2ca31028949645747f01a085e07ce36db20aeecb29d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-04-24T19:42:15Z" +diff_format = "unified" +context_files = [ + "src/Hadolint/Rule/DL3006.hs", + "test/Hadolint/Rule/DL3006Spec.hs", +] +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:00.806554+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:35e85350384bcf8526210d3c0e3ea521bda15b41f9e90913ca635e770afd8173" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-942/tests/capture.py b/tasks/hadolint__hadolint-942/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-942/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/hadolint__hadolint-942/tests/instruction.md b/tasks/hadolint__hadolint-942/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..997d8f8b04afab2c44621d5df244357e048f4fa4 --- /dev/null +++ b/tasks/hadolint__hadolint-942/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** fix: fp in `DL3006` + +## Description + + + +### What I did + +ensure we don't raise if image name is an arg + +### How I did it + +names can't start with `$` + +### How to verify it + +added a test, which fails if changes not present + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6cab02ad0143`. 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/hadolint__hadolint-942/tests/oracle.patch b/tasks/hadolint__hadolint-942/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..68b08d4723f99fc7e4899a90d8fd4fe7c1a79e87 --- /dev/null +++ b/tasks/hadolint__hadolint-942/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/src/Hadolint/Rule/DL3006.hs b/src/Hadolint/Rule/DL3006.hs +index d54c503..edfdc1c 100644 +--- a/src/Hadolint/Rule/DL3006.hs ++++ b/src/Hadolint/Rule/DL3006.hs +@@ -1,6 +1,7 @@ + module Hadolint.Rule.DL3006 (rule) where + + import qualified Data.Set as Set ++import qualified Data.Text as Text + import Data.Text (Text) + import Hadolint.Rule + import Language.Docker.Syntax +@@ -21,7 +22,7 @@ rule = customRule check (emptyState Set.empty) + -- When the image being used is a previously defined FROM alias, + -- then we can safely ignore that the image is not tagged. Otherwise + -- we marked it as a failure +- if Set.member i (state st) ++ if Text.isPrefixOf "$" i || Set.member i (state st) + then newState + else newState |> addFail (CheckFailure {..}) + _ -> newState +diff --git a/test/Hadolint/Rule/DL3006Spec.hs b/test/Hadolint/Rule/DL3006Spec.hs +index 876bd11..6ede7e2 100644 +--- a/test/Hadolint/Rule/DL3006Spec.hs ++++ b/test/Hadolint/Rule/DL3006Spec.hs +@@ -17,6 +17,8 @@ spec = do + ruleCatchesNot "DL3006" "FROM ruby@sha256:f1dbca0f5dbc9" + it "untagged digest is not an error" $ + ruleCatchesNot "DL3006" "FROM ruby:2" ++ it "using args is not an error" $ ++ ruleCatchesNot "DL3006" "FROM ${VALUE}" + it "local aliases are OK to be untagged" $ + let dockerFile = + [ "FROM golang:1.9.3-alpine3.7 AS build", diff --git a/tasks/hadolint__hadolint-942/tests/test.sh b/tasks/hadolint__hadolint-942/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e8608c5f7806885d408284b8d515dfb2bd0afc8a --- /dev/null +++ b/tasks/hadolint__hadolint-942/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 6cab02ad0143cf334fe276cb7240f0263674be2d > "$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/hadolint__hadolint-942/tests/verifier.py b/tasks/hadolint__hadolint-942/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-942/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/hadolint__hadolint-946/environment/Dockerfile b/tasks/hadolint__hadolint-946/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d260227ab5fc326087316a834a82eb673173c8c4 --- /dev/null +++ b/tasks/hadolint__hadolint-946/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6cab02ad0143cf334fe276cb7240f0263674be2d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6cab02ad0143cf334fe276cb7240f0263674be2d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6cab02ad0143cf334fe276cb7240f0263674be2d \ + && 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/hadolint__hadolint-946/instruction.md b/tasks/hadolint__hadolint-946/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..34675a9f709b6c0cfa8bcce96293ad3aab3364d2 --- /dev/null +++ b/tasks/hadolint__hadolint-946/instruction.md @@ -0,0 +1,168 @@ +# Issue + +**Title:** build(deps): bump actions/cache from 3.0.11 to 3.3.1 + +## Description + +Bumps [actions/cache](https://github.com/actions/cache) from 3.0.11 to 3.3.1. +
+Release notes +

Sourced from actions/cache's releases.

+
+

v3.3.1

+

What's Changed

+ +

Full Changelog: https://github.com/actions/cache/compare/v3...v3.3.1

+

v3.3.0

+

What's Changed

+ +

New Contributors

+ +

Full Changelog: https://github.com/actions/cache/compare/v3...v3.3.0

+

v3.2.6

+

What's Changed

+ +

Full Changelog: https://github.com/actions/cache/compare/v3...v3.2.6

+

v3.2.5

+

What's Changed

+ +

New Contributors

+ +

Full Changelog: https://github.com/actions/cache/compare/v3...v3.2.5

+

v3.2.4

+

What's Changed

+ + +
+

... (truncated)

+
+
+Changelog +

Sourced from actions/cache's changelog.

+
+

3.0.11

+
    +
  • Update toolkit version to 3.0.5 to include @actions/core@^1.10.0
  • +
  • Update @actions/cache to use updated saveState and setOutput functions from @actions/core@^1.10.0
  • +
+

3.1.0-beta.1

+
    +
  • Update @actions/cache on windows to use gnu tar and zstd by default and fallback to bsdtar and zstd if gnu tar is not available. (issue)
  • +
+

3.1.0-beta.2

+
    +
  • Added support for fallback to gzip to restore old caches on windows.
  • +
+

3.1.0-beta.3

+
    +
  • Bug fixes for bsdtar fallback if gnutar not available and gzip fallback if cache saved using old cache action on windows.
  • +
+

3.2.0-beta.1

+
    +
  • Added two new actions - restore and save for granular control on cache.
  • +
+

3.2.0

+
    +
  • Released the two new actions - restore and save for granular control on cache
  • +
+

3.2.1

+
    +
  • Update @actions/cache on windows to use gnu tar and zstd by default and fallback to bsdtar and zstd if gnu tar is not available. (issue)
  • +
  • Added support for fallback to gzip to restore old caches on windows.
  • +
  • Added logs for cache version in case of a cache miss.
  • +
+

3.2.2

+
    +
  • Reverted the changes made in 3.2.1 to use gnu tar and zstd by default on windows.
  • +
+

3.2.3

+
    +
  • Support cross os caching on Windows as an opt-in feature.
  • +
  • Fix issue with symlink restoration on Windows for cross-os caches.
  • +
+

3.2.4

+
    +
  • Added option to fail job on cache miss.
  • +
+

3.2.5

+
    +
  • Added fix to prevent from setting MYSYS environment variable globally.
  • +
+

3.2.6

+ +
+

... (truncated)

+
+
+Commits + +
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/cache&package-manager=github_actions&previous-version=3.0.11&new-version=3.3.1)](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) + +--- + +
+Dependabot commands and options +
+ +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 merge` will merge this PR after your CI passes on it +- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it +- `@dependabot cancel merge` will cancel a previously requested merge and block automerging +- `@dependabot reopen` will reopen this PR if it is closed +- `@depen + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6cab02ad0143`. 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/hadolint__hadolint-946/solution/patch.diff b/tasks/hadolint__hadolint-946/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7a44bcb654fbc939e5864548dc2d77846be65cc2 --- /dev/null +++ b/tasks/hadolint__hadolint-946/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml +index 7aa1f56..399a5a8 100644 +--- a/.github/workflows/haskell.yml ++++ b/.github/workflows/haskell.yml +@@ -63,7 +63,7 @@ jobs: + # cache + + - name: Cache store +- uses: actions/cache@v3.0.11 ++ uses: actions/cache@v3.3.1 + with: + path: ${{ steps.setup-haskell-cabal.outputs.cabal-store }} + key: ${{ runner.os }}-${{ hashFiles('cabal.project.freeze') }} +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index cb621be..4589dd9 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -246,7 +246,7 @@ jobs: + run: cabal freeze + + - name: Cache store +- uses: actions/cache@v3.0.11 ++ uses: actions/cache@v3.3.1 + with: + path: ${{ steps.setup-haskell-cabal.outputs.cabal-store }} + key: ${{ runner.os }}-${{ hashFiles('cabal.project.freeze') }} diff --git a/tasks/hadolint__hadolint-946/solution/solve.sh b/tasks/hadolint__hadolint-946/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-946/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/hadolint__hadolint-946/task.toml b/tasks/hadolint__hadolint-946/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e367c0387e33f77915dd823d435d37ebeb392d08 --- /dev/null +++ b/tasks/hadolint__hadolint-946/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-946" +description = "build(deps): bump actions/cache from 3.0.11 to 3.3.1" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "6cab02ad0143cf334fe276cb7240f0263674be2d" +reference = "https://github.com/hadolint/hadolint/pull/946" +source_access = "auto" +built_at = "2026-11-16T16:09:53.713561+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0ef667e78d3146439e532715c7e653f83c5e066530ddcda3a4d6e6de7191d265" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2023-04-05T08:14:37Z" +diff_format = "unified" +context_files = [ + ".github/workflows/haskell.yml", + ".github/workflows/release.yml", +] +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:00.807033+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:35e85350384bcf8526210d3c0e3ea521bda15b41f9e90913ca635e770afd8173" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-946/tests/capture.py b/tasks/hadolint__hadolint-946/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-946/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/hadolint__hadolint-946/tests/instruction.md b/tasks/hadolint__hadolint-946/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..34675a9f709b6c0cfa8bcce96293ad3aab3364d2 --- /dev/null +++ b/tasks/hadolint__hadolint-946/tests/instruction.md @@ -0,0 +1,168 @@ +# Issue + +**Title:** build(deps): bump actions/cache from 3.0.11 to 3.3.1 + +## Description + +Bumps [actions/cache](https://github.com/actions/cache) from 3.0.11 to 3.3.1. +
+Release notes +

Sourced from actions/cache's releases.

+
+

v3.3.1

+

What's Changed

+ +

Full Changelog: https://github.com/actions/cache/compare/v3...v3.3.1

+

v3.3.0

+

What's Changed

+ +

New Contributors

+ +

Full Changelog: https://github.com/actions/cache/compare/v3...v3.3.0

+

v3.2.6

+

What's Changed

+ +

Full Changelog: https://github.com/actions/cache/compare/v3...v3.2.6

+

v3.2.5

+

What's Changed

+ +

New Contributors

+ +

Full Changelog: https://github.com/actions/cache/compare/v3...v3.2.5

+

v3.2.4

+

What's Changed

+ + +
+

... (truncated)

+
+
+Changelog +

Sourced from actions/cache's changelog.

+
+

3.0.11

+
    +
  • Update toolkit version to 3.0.5 to include @actions/core@^1.10.0
  • +
  • Update @actions/cache to use updated saveState and setOutput functions from @actions/core@^1.10.0
  • +
+

3.1.0-beta.1

+
    +
  • Update @actions/cache on windows to use gnu tar and zstd by default and fallback to bsdtar and zstd if gnu tar is not available. (issue)
  • +
+

3.1.0-beta.2

+
    +
  • Added support for fallback to gzip to restore old caches on windows.
  • +
+

3.1.0-beta.3

+
    +
  • Bug fixes for bsdtar fallback if gnutar not available and gzip fallback if cache saved using old cache action on windows.
  • +
+

3.2.0-beta.1

+
    +
  • Added two new actions - restore and save for granular control on cache.
  • +
+

3.2.0

+
    +
  • Released the two new actions - restore and save for granular control on cache
  • +
+

3.2.1

+
    +
  • Update @actions/cache on windows to use gnu tar and zstd by default and fallback to bsdtar and zstd if gnu tar is not available. (issue)
  • +
  • Added support for fallback to gzip to restore old caches on windows.
  • +
  • Added logs for cache version in case of a cache miss.
  • +
+

3.2.2

+
    +
  • Reverted the changes made in 3.2.1 to use gnu tar and zstd by default on windows.
  • +
+

3.2.3

+
    +
  • Support cross os caching on Windows as an opt-in feature.
  • +
  • Fix issue with symlink restoration on Windows for cross-os caches.
  • +
+

3.2.4

+
    +
  • Added option to fail job on cache miss.
  • +
+

3.2.5

+
    +
  • Added fix to prevent from setting MYSYS environment variable globally.
  • +
+

3.2.6

+ +
+

... (truncated)

+
+
+Commits + +
+
+ +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=actions/cache&package-manager=github_actions&previous-version=3.0.11&new-version=3.3.1)](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) + +--- + +
+Dependabot commands and options +
+ +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 merge` will merge this PR after your CI passes on it +- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it +- `@dependabot cancel merge` will cancel a previously requested merge and block automerging +- `@dependabot reopen` will reopen this PR if it is closed +- `@depen + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6cab02ad0143`. 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/hadolint__hadolint-946/tests/oracle.patch b/tasks/hadolint__hadolint-946/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7a44bcb654fbc939e5864548dc2d77846be65cc2 --- /dev/null +++ b/tasks/hadolint__hadolint-946/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml +index 7aa1f56..399a5a8 100644 +--- a/.github/workflows/haskell.yml ++++ b/.github/workflows/haskell.yml +@@ -63,7 +63,7 @@ jobs: + # cache + + - name: Cache store +- uses: actions/cache@v3.0.11 ++ uses: actions/cache@v3.3.1 + with: + path: ${{ steps.setup-haskell-cabal.outputs.cabal-store }} + key: ${{ runner.os }}-${{ hashFiles('cabal.project.freeze') }} +diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml +index cb621be..4589dd9 100644 +--- a/.github/workflows/release.yml ++++ b/.github/workflows/release.yml +@@ -246,7 +246,7 @@ jobs: + run: cabal freeze + + - name: Cache store +- uses: actions/cache@v3.0.11 ++ uses: actions/cache@v3.3.1 + with: + path: ${{ steps.setup-haskell-cabal.outputs.cabal-store }} + key: ${{ runner.os }}-${{ hashFiles('cabal.project.freeze') }} diff --git a/tasks/hadolint__hadolint-946/tests/test.sh b/tasks/hadolint__hadolint-946/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e8608c5f7806885d408284b8d515dfb2bd0afc8a --- /dev/null +++ b/tasks/hadolint__hadolint-946/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 6cab02ad0143cf334fe276cb7240f0263674be2d > "$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/hadolint__hadolint-946/tests/verifier.py b/tasks/hadolint__hadolint-946/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-946/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/hadolint__hadolint-954/environment/Dockerfile b/tasks/hadolint__hadolint-954/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..614300c84b168e9cc661c3c99eadb96d7d303091 --- /dev/null +++ b/tasks/hadolint__hadolint-954/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/hadolint/hadolint.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/hadolint/hadolint.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/hadolint/hadolint.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 024fd640378acd5d8218f77ec2c744826cdda5ce 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 024fd640378acd5d8218f77ec2c744826cdda5ce \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 024fd640378acd5d8218f77ec2c744826cdda5ce \ + && 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/hadolint__hadolint-954/instruction.md b/tasks/hadolint__hadolint-954/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09e82a48d46781551db49cc41dbfc88407db320e --- /dev/null +++ b/tasks/hadolint__hadolint-954/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** Improve parsing of gem install flag patterns to reduce false positives + +## Description + + + +### What I did +In Hadolint, there are several gem install flag patterns that result in false positives. + +Warnings should not be displayed for the following patterns: + +```dockerfile +RUN gem install bundler:2.0.1 -- --use-system-libraries true +RUN gem install bundler:2.0.1 --use-system-libraries true +RUN gem install bundler:2.0.1 --use-system-libraries=true +``` + +In this PR, I have made adjustments so that these patterns can also be parsed correctly. + +### How I did it +I modified the processing to remove options and their subsequent arguments from the list of arguments. + +### How to verify it +I have added tests related to the additional patterns. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `024fd640378a`. 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/hadolint__hadolint-954/solution/patch.diff b/tasks/hadolint__hadolint-954/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..dcdd48e6e1fcb360dbfe6ab87ee72585b6ce85a7 --- /dev/null +++ b/tasks/hadolint__hadolint-954/solution/patch.diff @@ -0,0 +1,44 @@ +diff --git a/src/Hadolint/Rule/DL3028.hs b/src/Hadolint/Rule/DL3028.hs +index 2710b8b..5d9a52b 100644 +--- a/src/Hadolint/Rule/DL3028.hs ++++ b/src/Hadolint/Rule/DL3028.hs +@@ -34,8 +34,15 @@ gems shell = + not (Shell.cmdHasArgs "gem" ["-v"] cmd), + not (Shell.cmdHasArgs "gem" ["--version"] cmd), + not (Shell.cmdHasPrefixArg "gem" "--version=" cmd), +- arg <- Shell.getArgsNoFlags cmd, ++ let args = Shell.getArgs cmd, ++ let argsUntilDoubleDash = takeWhile (/= "--") args, ++ arg <- removeOptions argsUntilDoubleDash, + arg /= "install", +- arg /= "i", +- arg /= "--" ++ arg /= "i" + ] ++ where ++ removeOptions [] = [] ++ removeOptions (x : xs) ++ | x == "--" = removeOptions xs ++ | "-" `Text.isPrefixOf` x = removeOptions (drop 1 xs) ++ | otherwise = x : removeOptions xs +diff --git a/test/Hadolint/Rule/DL3028Spec.hs b/test/Hadolint/Rule/DL3028Spec.hs +index e662caf..ad85eff 100644 +--- a/test/Hadolint/Rule/DL3028Spec.hs ++++ b/test/Hadolint/Rule/DL3028Spec.hs +@@ -39,6 +39,15 @@ spec = do + it "does not warn on --version with =" $ do + ruleCatchesNot "DL3028" "RUN gem install bundler --version='2.0.1'" + onBuildRuleCatchesNot "DL3028" "RUN gem install bundler --version='2.0.1'" +- it "does not warn on extra flags" $ do ++ it "does not warn when using extra flags with equal sign and double dashes" $ do + ruleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 -- --use-system-libraries=true" + onBuildRuleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 -- --use-system-libraries=true" ++ it "does not warn when using extra flags with double dashes" $ do ++ ruleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 -- --use-system-libraries true" ++ onBuildRuleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 -- --use-system-libraries true" ++ it "does not warn when using extra flags" $ do ++ ruleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 --use-system-libraries true" ++ onBuildRuleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 --use-system-libraries true" ++ it "does not warn when using extra flags with equal sign" $ do ++ ruleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 --use-system-libraries=true" ++ onBuildRuleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 --use-system-libraries=true" diff --git a/tasks/hadolint__hadolint-954/solution/solve.sh b/tasks/hadolint__hadolint-954/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/hadolint__hadolint-954/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/hadolint__hadolint-954/task.toml b/tasks/hadolint__hadolint-954/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d58772152e8425ceb1db163f915ccf2d221a17e9 --- /dev/null +++ b/tasks/hadolint__hadolint-954/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/hadolint__hadolint-954" +description = "Improve parsing of gem install flag patterns to reduce false positives" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "hadolint", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "hadolint/hadolint" +ref = "024fd640378acd5d8218f77ec2c744826cdda5ce" +reference = "https://github.com/hadolint/hadolint/pull/954" +source_access = "auto" +built_at = "2026-11-16T16:09:53.703869+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:836b96fadd3d8404c6ca6b0530d027545263913a36d4b032ec25ed252bed03e4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2024-04-24T19:41:20Z" +diff_format = "unified" +context_files = [ + "src/Hadolint/Rule/DL3028.hs", + "test/Hadolint/Rule/DL3028Spec.hs", +] +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:00.807504+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4871abaadaf66576d4cee15f47de75d1dd0bc9374e27f158169d8333c8790eb7" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/hadolint__hadolint-954/tests/capture.py b/tasks/hadolint__hadolint-954/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/hadolint__hadolint-954/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/hadolint__hadolint-954/tests/instruction.md b/tasks/hadolint__hadolint-954/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09e82a48d46781551db49cc41dbfc88407db320e --- /dev/null +++ b/tasks/hadolint__hadolint-954/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** Improve parsing of gem install flag patterns to reduce false positives + +## Description + + + +### What I did +In Hadolint, there are several gem install flag patterns that result in false positives. + +Warnings should not be displayed for the following patterns: + +```dockerfile +RUN gem install bundler:2.0.1 -- --use-system-libraries true +RUN gem install bundler:2.0.1 --use-system-libraries true +RUN gem install bundler:2.0.1 --use-system-libraries=true +``` + +In this PR, I have made adjustments so that these patterns can also be parsed correctly. + +### How I did it +I modified the processing to remove options and their subsequent arguments from the list of arguments. + +### How to verify it +I have added tests related to the additional patterns. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `024fd640378a`. 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/hadolint__hadolint-954/tests/oracle.patch b/tasks/hadolint__hadolint-954/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..dcdd48e6e1fcb360dbfe6ab87ee72585b6ce85a7 --- /dev/null +++ b/tasks/hadolint__hadolint-954/tests/oracle.patch @@ -0,0 +1,44 @@ +diff --git a/src/Hadolint/Rule/DL3028.hs b/src/Hadolint/Rule/DL3028.hs +index 2710b8b..5d9a52b 100644 +--- a/src/Hadolint/Rule/DL3028.hs ++++ b/src/Hadolint/Rule/DL3028.hs +@@ -34,8 +34,15 @@ gems shell = + not (Shell.cmdHasArgs "gem" ["-v"] cmd), + not (Shell.cmdHasArgs "gem" ["--version"] cmd), + not (Shell.cmdHasPrefixArg "gem" "--version=" cmd), +- arg <- Shell.getArgsNoFlags cmd, ++ let args = Shell.getArgs cmd, ++ let argsUntilDoubleDash = takeWhile (/= "--") args, ++ arg <- removeOptions argsUntilDoubleDash, + arg /= "install", +- arg /= "i", +- arg /= "--" ++ arg /= "i" + ] ++ where ++ removeOptions [] = [] ++ removeOptions (x : xs) ++ | x == "--" = removeOptions xs ++ | "-" `Text.isPrefixOf` x = removeOptions (drop 1 xs) ++ | otherwise = x : removeOptions xs +diff --git a/test/Hadolint/Rule/DL3028Spec.hs b/test/Hadolint/Rule/DL3028Spec.hs +index e662caf..ad85eff 100644 +--- a/test/Hadolint/Rule/DL3028Spec.hs ++++ b/test/Hadolint/Rule/DL3028Spec.hs +@@ -39,6 +39,15 @@ spec = do + it "does not warn on --version with =" $ do + ruleCatchesNot "DL3028" "RUN gem install bundler --version='2.0.1'" + onBuildRuleCatchesNot "DL3028" "RUN gem install bundler --version='2.0.1'" +- it "does not warn on extra flags" $ do ++ it "does not warn when using extra flags with equal sign and double dashes" $ do + ruleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 -- --use-system-libraries=true" + onBuildRuleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 -- --use-system-libraries=true" ++ it "does not warn when using extra flags with double dashes" $ do ++ ruleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 -- --use-system-libraries true" ++ onBuildRuleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 -- --use-system-libraries true" ++ it "does not warn when using extra flags" $ do ++ ruleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 --use-system-libraries true" ++ onBuildRuleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 --use-system-libraries true" ++ it "does not warn when using extra flags with equal sign" $ do ++ ruleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 --use-system-libraries=true" ++ onBuildRuleCatchesNot "DL3028" "RUN gem install bundler:2.0.1 --use-system-libraries=true" diff --git a/tasks/hadolint__hadolint-954/tests/test.sh b/tasks/hadolint__hadolint-954/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c5dd8a960106bb4cab3bf0758c6f65d205cb54e0 --- /dev/null +++ b/tasks/hadolint__hadolint-954/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 024fd640378acd5d8218f77ec2c744826cdda5ce > "$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/hadolint__hadolint-954/tests/verifier.py b/tasks/hadolint__hadolint-954/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/hadolint__hadolint-954/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/henrygd__beszel-1917/environment/Dockerfile b/tasks/henrygd__beszel-1917/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..823fbf6147c94ede9f5ea2c195456af392653fa3 --- /dev/null +++ b/tasks/henrygd__beszel-1917/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6141b15f0359516101e4da0fc4350f4d04f165aa 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6141b15f0359516101e4da0fc4350f4d04f165aa \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6141b15f0359516101e4da0fc4350f4d04f165aa \ + && 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/henrygd__beszel-1917/instruction.md b/tasks/henrygd__beszel-1917/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..19b19585219d04ffcef7bc7bebb92738141869ae --- /dev/null +++ b/tasks/henrygd__beszel-1917/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** feat: sync display name with hostname + +## Description + +## 📃 Description + +Adds a hub env var to keep system display names in sync with the hostname reported by the agent. When `SYNC_SYSTEM_NAMES=true` is set, the hub updates the system's name whenever an agent connects and reports its details. + + + + +## 🪵 Changelog + +### ➕ Added + +- `SYNC_SYSTEM_NAMES` hub env var to sync system names with agent hostnames + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6141b15f0359`. 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/henrygd__beszel-1917/solution/patch.diff b/tasks/henrygd__beszel-1917/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..77793985c4a0d4c25ce13e9d428cdf44420be742 --- /dev/null +++ b/tasks/henrygd__beszel-1917/solution/patch.diff @@ -0,0 +1,55 @@ +diff --git a/internal/hub/systems/system.go b/internal/hub/systems/system.go +index a93d69e3..469c1e06 100644 +--- a/internal/hub/systems/system.go ++++ b/internal/hub/systems/system.go +@@ -279,6 +279,10 @@ func (sys *System) createRecords(data *system.CombinedData) (*core.Record, error + if err := createSystemDetailsRecord(txApp, data.Details, sys.Id); err != nil { + return err + } ++ // sync display name with hostname if enabled (details are fetched once per agent connection) ++ if syncNames, _ := utils.GetEnv("SYNC_SYSTEM_NAMES"); syncNames == "true" && data.Details.Hostname != "" { ++ systemRecord.Set("name", data.Details.Hostname) ++ } + } + + if data.Monitors != nil { +diff --git a/internal/hub/systems/system_sync_name_test.go b/internal/hub/systems/system_sync_name_test.go +new file mode 100644 +index 00000000..339b6566 +--- /dev/null ++++ b/internal/hub/systems/system_sync_name_test.go +@@ -0,0 +1,34 @@ ++//go:build testing ++ ++package systems ++ ++import ( ++ "testing" ++ ++ "github.com/henrygd/beszel/internal/entities/system" ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/require" ++) ++ ++func TestCreateRecordsSyncSystemNames(t *testing.T) { ++ for _, tc := range []struct { ++ name string ++ env string ++ hostname string ++ expected string ++ }{ ++ {"disabled", "", "new-host", "test-system"}, ++ {"enabled", "true", "new-host", "new-host"}, ++ {"enabled with empty hostname", "true", "", "test-system"}, ++ } { ++ t.Run(tc.name, func(t *testing.T) { ++ t.Setenv("SYNC_SYSTEM_NAMES", tc.env) ++ sys, app := newTestSystemWithHub(t) ++ _, err := sys.createRecords(&system.CombinedData{Details: &system.Details{Hostname: tc.hostname}}) ++ require.NoError(t, err) ++ record, err := app.FindRecordById("systems", sys.Id) ++ require.NoError(t, err) ++ assert.Equal(t, tc.expected, record.GetString("name")) ++ }) ++ } ++} diff --git a/tasks/henrygd__beszel-1917/solution/solve.sh b/tasks/henrygd__beszel-1917/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-1917/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/henrygd__beszel-1917/task.toml b/tasks/henrygd__beszel-1917/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..df465945540457b5e8e67db34a8e8affc03fd472 --- /dev/null +++ b/tasks/henrygd__beszel-1917/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-1917" +description = "feat: sync display name with hostname" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "6141b15f0359516101e4da0fc4350f4d04f165aa" +reference = "https://github.com/henrygd/beszel/pull/1917" +source_access = "auto" +built_at = "2026-11-16T16:09:53.483186+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:77b248dcf1c91281469c6438fc526ed762f68f2b1530d9db5d1db0f1732fb1d5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-24T21:46:00Z" +diff_format = "unified" +context_files = [ + "internal/hub/systems/system.go", + "internal/hub/systems/system_sync_name_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 38 +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:00.807973+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:eff3f6b412b728b2f9c5c6e114daa0627537ff9012295732032291eb672f632a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-1917/tests/capture.py b/tasks/henrygd__beszel-1917/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-1917/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/henrygd__beszel-1917/tests/instruction.md b/tasks/henrygd__beszel-1917/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..19b19585219d04ffcef7bc7bebb92738141869ae --- /dev/null +++ b/tasks/henrygd__beszel-1917/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** feat: sync display name with hostname + +## Description + +## 📃 Description + +Adds a hub env var to keep system display names in sync with the hostname reported by the agent. When `SYNC_SYSTEM_NAMES=true` is set, the hub updates the system's name whenever an agent connects and reports its details. + + + + +## 🪵 Changelog + +### ➕ Added + +- `SYNC_SYSTEM_NAMES` hub env var to sync system names with agent hostnames + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6141b15f0359`. 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/henrygd__beszel-1917/tests/oracle.patch b/tasks/henrygd__beszel-1917/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..77793985c4a0d4c25ce13e9d428cdf44420be742 --- /dev/null +++ b/tasks/henrygd__beszel-1917/tests/oracle.patch @@ -0,0 +1,55 @@ +diff --git a/internal/hub/systems/system.go b/internal/hub/systems/system.go +index a93d69e3..469c1e06 100644 +--- a/internal/hub/systems/system.go ++++ b/internal/hub/systems/system.go +@@ -279,6 +279,10 @@ func (sys *System) createRecords(data *system.CombinedData) (*core.Record, error + if err := createSystemDetailsRecord(txApp, data.Details, sys.Id); err != nil { + return err + } ++ // sync display name with hostname if enabled (details are fetched once per agent connection) ++ if syncNames, _ := utils.GetEnv("SYNC_SYSTEM_NAMES"); syncNames == "true" && data.Details.Hostname != "" { ++ systemRecord.Set("name", data.Details.Hostname) ++ } + } + + if data.Monitors != nil { +diff --git a/internal/hub/systems/system_sync_name_test.go b/internal/hub/systems/system_sync_name_test.go +new file mode 100644 +index 00000000..339b6566 +--- /dev/null ++++ b/internal/hub/systems/system_sync_name_test.go +@@ -0,0 +1,34 @@ ++//go:build testing ++ ++package systems ++ ++import ( ++ "testing" ++ ++ "github.com/henrygd/beszel/internal/entities/system" ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/require" ++) ++ ++func TestCreateRecordsSyncSystemNames(t *testing.T) { ++ for _, tc := range []struct { ++ name string ++ env string ++ hostname string ++ expected string ++ }{ ++ {"disabled", "", "new-host", "test-system"}, ++ {"enabled", "true", "new-host", "new-host"}, ++ {"enabled with empty hostname", "true", "", "test-system"}, ++ } { ++ t.Run(tc.name, func(t *testing.T) { ++ t.Setenv("SYNC_SYSTEM_NAMES", tc.env) ++ sys, app := newTestSystemWithHub(t) ++ _, err := sys.createRecords(&system.CombinedData{Details: &system.Details{Hostname: tc.hostname}}) ++ require.NoError(t, err) ++ record, err := app.FindRecordById("systems", sys.Id) ++ require.NoError(t, err) ++ assert.Equal(t, tc.expected, record.GetString("name")) ++ }) ++ } ++} diff --git a/tasks/henrygd__beszel-1917/tests/test.sh b/tasks/henrygd__beszel-1917/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..69cac24d52b3f4a0e38bd422d94dd32f5e585237 --- /dev/null +++ b/tasks/henrygd__beszel-1917/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 6141b15f0359516101e4da0fc4350f4d04f165aa > "$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/henrygd__beszel-1917/tests/verifier.py b/tasks/henrygd__beszel-1917/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-1917/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/henrygd__beszel-1972/environment/Dockerfile b/tasks/henrygd__beszel-1972/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..352389aa09c9e150e723e9aa7620b479654ddf41 --- /dev/null +++ b/tasks/henrygd__beszel-1972/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 \ + && 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/henrygd__beszel-1972/instruction.md b/tasks/henrygd__beszel-1972/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ab7c3cf7784fbd7637cf17a10c53f19d962218d --- /dev/null +++ b/tasks/henrygd__beszel-1972/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Fix: Enable immediate exit on errors in install-agent.sh + +## Description + +## 📃 Description + +Add error handling to ensure the script exits on errors. + +Refs + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c157c2026d03`. 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/henrygd__beszel-1972/solution/patch.diff b/tasks/henrygd__beszel-1972/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..31e2e1a0cc9de86d6be980184cd760277df40628 --- /dev/null +++ b/tasks/henrygd__beszel-1972/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/supplemental/scripts/install-agent.sh b/supplemental/scripts/install-agent.sh +index c181846c..e5b92177 100755 +--- a/supplemental/scripts/install-agent.sh ++++ b/supplemental/scripts/install-agent.sh +@@ -230,6 +230,9 @@ detect_mips_endianness() { + echo "mips" + } + ++# Ensure script exits immediately on errors ++set -eu ++ + # Default values + PORT=45876 + UNINSTALL=false diff --git a/tasks/henrygd__beszel-1972/solution/solve.sh b/tasks/henrygd__beszel-1972/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-1972/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/henrygd__beszel-1972/task.toml b/tasks/henrygd__beszel-1972/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fd5f5ee4ef3e8c8f2d81c73e9776a112adf38e17 --- /dev/null +++ b/tasks/henrygd__beszel-1972/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-1972" +description = "Fix: Enable immediate exit on errors in install-agent.sh" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "c157c2026d0348aabcfb37c3e9cfafba2b0f8b26" +reference = "https://github.com/henrygd/beszel/pull/1972" +source_access = "auto" +built_at = "2026-11-16T16:09:53.514047+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f8b572ab5d2efa6980d4899d21b0184e9a0884353984eca21aac232ffc0b74ae" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-05T16:05:45Z" +diff_format = "unified" +context_files = [ + "supplemental/scripts/install-agent.sh", +] +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:00.808672+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:aa05e20d6167ddfbf85263c52c72a43421968b8505219d601d1ac0de8c167851" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-1972/tests/capture.py b/tasks/henrygd__beszel-1972/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-1972/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/henrygd__beszel-1972/tests/instruction.md b/tasks/henrygd__beszel-1972/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ab7c3cf7784fbd7637cf17a10c53f19d962218d --- /dev/null +++ b/tasks/henrygd__beszel-1972/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Fix: Enable immediate exit on errors in install-agent.sh + +## Description + +## 📃 Description + +Add error handling to ensure the script exits on errors. + +Refs + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c157c2026d03`. 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/henrygd__beszel-1972/tests/oracle.patch b/tasks/henrygd__beszel-1972/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..31e2e1a0cc9de86d6be980184cd760277df40628 --- /dev/null +++ b/tasks/henrygd__beszel-1972/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/supplemental/scripts/install-agent.sh b/supplemental/scripts/install-agent.sh +index c181846c..e5b92177 100755 +--- a/supplemental/scripts/install-agent.sh ++++ b/supplemental/scripts/install-agent.sh +@@ -230,6 +230,9 @@ detect_mips_endianness() { + echo "mips" + } + ++# Ensure script exits immediately on errors ++set -eu ++ + # Default values + PORT=45876 + UNINSTALL=false diff --git a/tasks/henrygd__beszel-1972/tests/test.sh b/tasks/henrygd__beszel-1972/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d6be1a89c574b99fd94339c386a3cbfa4a0aae87 --- /dev/null +++ b/tasks/henrygd__beszel-1972/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 c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 > "$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/henrygd__beszel-1972/tests/verifier.py b/tasks/henrygd__beszel-1972/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-1972/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/henrygd__beszel-2275/environment/Dockerfile b/tasks/henrygd__beszel-2275/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c6a37a45cb866fd2251a05000aad5d67c53fe91c --- /dev/null +++ b/tasks/henrygd__beszel-2275/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 467f1767132b8b4e68ae6652b3763e3cbf609586 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 467f1767132b8b4e68ae6652b3763e3cbf609586 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 467f1767132b8b4e68ae6652b3763e3cbf609586 \ + && 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/henrygd__beszel-2275/instruction.md b/tasks/henrygd__beszel-2275/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43f261678b4568c95cf822e2a182a3033d8a41aa --- /dev/null +++ b/tasks/henrygd__beszel-2275/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** Warn when critical ATA SMART attributes are nonzero + +## Description + +## 📃 Description + +### Problem +ATA SMART health remained `PASSED` when smartctl's overall assessment passed, even if critical attributes 5 (reallocated sectors), 197 (pending sectors), or 198 (offline uncorrectable sectors) had a nonzero raw value. + +### Fix +Set the ATA drive health to `WARNING` after parsing one of those attributes with a nonzero raw value. Existing `FAILED` and `UNKNOWN` statuses remain unchanged. + +### User impact +Users receive a degraded SMART health state and its existing alert path for these early disk-failure indicators, without affecting NVMe, SCSI, eMMC, or mdraid devices. + +## 📖 Documentation + +N/A - no user-facing command or configuration changes. + +## 🪵 Changelog + +### 🔧 Fixed + +- Warn when critical ATA SMART attributes have nonzero raw values. + +## 📷 Screenshots + +N/A - no UI changes. + +## Verification + +- `go test -tags testing ./agent -run '^TestParseSmartForSata' -count=1` passed, including the new synthetic smartctl JSON cases for attributes 5, 197, and 198 and the `FAILED`/`UNKNOWN` preservation cases. +- `go test -tags testing ./agent -count=1` reached unrelated Windows-only failures: Unix error-text and path-separator assertions in `TestGetToken`, `TestAddExtraFilesystemFolders`, and `TestAddPartitionExtraFs`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `467f1767132b`. 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/henrygd__beszel-2275/solution/patch.diff b/tasks/henrygd__beszel-2275/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c1aafaf6b732f1056dc63bdf76a439a0d54c2be2 --- /dev/null +++ b/tasks/henrygd__beszel-2275/solution/patch.diff @@ -0,0 +1,82 @@ +diff --git a/agent/smart.go b/agent/smart.go +index 28a5ad81..bcbdd91a 100644 +--- a/agent/smart.go ++++ b/agent/smart.go +@@ -931,6 +931,9 @@ func (sm *SmartManager) parseSmartForSata(output []byte, deviceType string) (boo + if parsed, ok := smart.ParseSmartRawValueString(attr.Raw.String); ok { + rawValue = parsed + } ++ if smartData.SmartStatus == "PASSED" && rawValue > 0 && (attr.ID == 5 || attr.ID == 197 || attr.ID == 198) { ++ smartData.SmartStatus = "WARNING" ++ } + smartAttr := &smart.SmartAttribute{ + ID: attr.ID, + Name: attr.Name, +diff --git a/agent/smart_test.go b/agent/smart_test.go +index e2296db9..4850368e 100644 +--- a/agent/smart_test.go ++++ b/agent/smart_test.go +@@ -4,8 +4,10 @@ package agent + + import ( + "errors" ++ "fmt" + "os" + "path/filepath" ++ "strconv" + "testing" + + "github.com/henrygd/beszel/internal/entities/smart" +@@ -88,6 +90,52 @@ func TestParseSmartForSata(t *testing.T) { + } + } + ++func TestParseSmartForSataWarnsForCriticalAttributes(t *testing.T) { ++ for _, attrID := range []int{5, 197, 198} { ++ t.Run("attribute "+strconv.Itoa(attrID), func(t *testing.T) { ++ jsonPayload := []byte(fmt.Sprintf(`{ ++ "smartctl": {"exit_status": 0}, ++ "device": {"name": "/dev/sda", "type": "sat"}, ++ "model_name": "Example", ++ "serial_number": "WARNING%d", ++ "smart_status": {"passed": true}, ++ "temperature": {"current": 30}, ++ "ata_smart_attributes": {"table": [{"id": %d, "raw": {"value": 1, "string": "1"}}]} ++ }`, attrID, attrID)) ++ ++ sm := &SmartManager{SmartDataMap: make(map[string]*smart.SmartData)} ++ hasData, _ := sm.parseSmartForSata(jsonPayload, "") ++ require.True(t, hasData) ++ assert.Equal(t, "WARNING", sm.SmartDataMap[fmt.Sprintf("WARNING%d", attrID)].SmartStatus) ++ }) ++ } ++} ++ ++func TestParseSmartForSataPreservesFailedAndUnknownStatus(t *testing.T) { ++ for _, test := range []struct { ++ name string ++ temperature int ++ want string ++ }{ ++ {name: "failed", temperature: 30, want: "FAILED"}, ++ {name: "unknown", want: "UNKNOWN"}, ++ } { ++ t.Run(test.name, func(t *testing.T) { ++ jsonPayload := []byte(fmt.Sprintf(`{ ++ "device": {"name": "/dev/sda", "type": "sat"}, ++ "serial_number": "PRESERVE%s", ++ "temperature": {"current": %d}, ++ "ata_smart_attributes": {"table": [{"id": 197, "raw": {"value": 1, "string": "1"}}]} ++ }`, test.name, test.temperature)) ++ ++ sm := &SmartManager{SmartDataMap: make(map[string]*smart.SmartData)} ++ hasData, _ := sm.parseSmartForSata(jsonPayload, "") ++ require.True(t, hasData) ++ assert.Equal(t, test.want, sm.SmartDataMap["PRESERVE"+test.name].SmartStatus) ++ }) ++ } ++} ++ + func TestParseSmartForSataDeviceStatisticsTemperature(t *testing.T) { + jsonPayload := []byte(`{ + "smartctl": {"exit_status": 0}, diff --git a/tasks/henrygd__beszel-2275/solution/solve.sh b/tasks/henrygd__beszel-2275/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2275/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/henrygd__beszel-2275/task.toml b/tasks/henrygd__beszel-2275/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1db46bb2a022aabd6d43d97393dec49e50083736 --- /dev/null +++ b/tasks/henrygd__beszel-2275/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2275" +description = "Warn when critical ATA SMART attributes are nonzero" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "467f1767132b8b4e68ae6652b3763e3cbf609586" +reference = "https://github.com/henrygd/beszel/pull/2275" +source_access = "auto" +built_at = "2026-11-16T16:09:53.499101+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b274475c7c2106b31b603461ea67bd800c24473a62103bfeeed65e30ac8c9450" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-30T15:23:53Z" +diff_format = "unified" +context_files = [ + "agent/smart.go", + "agent/smart_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 51 +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:00.809290+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9a3de594d5c090383c1b0d196a10bde74e021f1bc3682b569dccb5dd65d03537" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2275/tests/capture.py b/tasks/henrygd__beszel-2275/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2275/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/henrygd__beszel-2275/tests/instruction.md b/tasks/henrygd__beszel-2275/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43f261678b4568c95cf822e2a182a3033d8a41aa --- /dev/null +++ b/tasks/henrygd__beszel-2275/tests/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** Warn when critical ATA SMART attributes are nonzero + +## Description + +## 📃 Description + +### Problem +ATA SMART health remained `PASSED` when smartctl's overall assessment passed, even if critical attributes 5 (reallocated sectors), 197 (pending sectors), or 198 (offline uncorrectable sectors) had a nonzero raw value. + +### Fix +Set the ATA drive health to `WARNING` after parsing one of those attributes with a nonzero raw value. Existing `FAILED` and `UNKNOWN` statuses remain unchanged. + +### User impact +Users receive a degraded SMART health state and its existing alert path for these early disk-failure indicators, without affecting NVMe, SCSI, eMMC, or mdraid devices. + +## 📖 Documentation + +N/A - no user-facing command or configuration changes. + +## 🪵 Changelog + +### 🔧 Fixed + +- Warn when critical ATA SMART attributes have nonzero raw values. + +## 📷 Screenshots + +N/A - no UI changes. + +## Verification + +- `go test -tags testing ./agent -run '^TestParseSmartForSata' -count=1` passed, including the new synthetic smartctl JSON cases for attributes 5, 197, and 198 and the `FAILED`/`UNKNOWN` preservation cases. +- `go test -tags testing ./agent -count=1` reached unrelated Windows-only failures: Unix error-text and path-separator assertions in `TestGetToken`, `TestAddExtraFilesystemFolders`, and `TestAddPartitionExtraFs`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `467f1767132b`. 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/henrygd__beszel-2275/tests/oracle.patch b/tasks/henrygd__beszel-2275/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c1aafaf6b732f1056dc63bdf76a439a0d54c2be2 --- /dev/null +++ b/tasks/henrygd__beszel-2275/tests/oracle.patch @@ -0,0 +1,82 @@ +diff --git a/agent/smart.go b/agent/smart.go +index 28a5ad81..bcbdd91a 100644 +--- a/agent/smart.go ++++ b/agent/smart.go +@@ -931,6 +931,9 @@ func (sm *SmartManager) parseSmartForSata(output []byte, deviceType string) (boo + if parsed, ok := smart.ParseSmartRawValueString(attr.Raw.String); ok { + rawValue = parsed + } ++ if smartData.SmartStatus == "PASSED" && rawValue > 0 && (attr.ID == 5 || attr.ID == 197 || attr.ID == 198) { ++ smartData.SmartStatus = "WARNING" ++ } + smartAttr := &smart.SmartAttribute{ + ID: attr.ID, + Name: attr.Name, +diff --git a/agent/smart_test.go b/agent/smart_test.go +index e2296db9..4850368e 100644 +--- a/agent/smart_test.go ++++ b/agent/smart_test.go +@@ -4,8 +4,10 @@ package agent + + import ( + "errors" ++ "fmt" + "os" + "path/filepath" ++ "strconv" + "testing" + + "github.com/henrygd/beszel/internal/entities/smart" +@@ -88,6 +90,52 @@ func TestParseSmartForSata(t *testing.T) { + } + } + ++func TestParseSmartForSataWarnsForCriticalAttributes(t *testing.T) { ++ for _, attrID := range []int{5, 197, 198} { ++ t.Run("attribute "+strconv.Itoa(attrID), func(t *testing.T) { ++ jsonPayload := []byte(fmt.Sprintf(`{ ++ "smartctl": {"exit_status": 0}, ++ "device": {"name": "/dev/sda", "type": "sat"}, ++ "model_name": "Example", ++ "serial_number": "WARNING%d", ++ "smart_status": {"passed": true}, ++ "temperature": {"current": 30}, ++ "ata_smart_attributes": {"table": [{"id": %d, "raw": {"value": 1, "string": "1"}}]} ++ }`, attrID, attrID)) ++ ++ sm := &SmartManager{SmartDataMap: make(map[string]*smart.SmartData)} ++ hasData, _ := sm.parseSmartForSata(jsonPayload, "") ++ require.True(t, hasData) ++ assert.Equal(t, "WARNING", sm.SmartDataMap[fmt.Sprintf("WARNING%d", attrID)].SmartStatus) ++ }) ++ } ++} ++ ++func TestParseSmartForSataPreservesFailedAndUnknownStatus(t *testing.T) { ++ for _, test := range []struct { ++ name string ++ temperature int ++ want string ++ }{ ++ {name: "failed", temperature: 30, want: "FAILED"}, ++ {name: "unknown", want: "UNKNOWN"}, ++ } { ++ t.Run(test.name, func(t *testing.T) { ++ jsonPayload := []byte(fmt.Sprintf(`{ ++ "device": {"name": "/dev/sda", "type": "sat"}, ++ "serial_number": "PRESERVE%s", ++ "temperature": {"current": %d}, ++ "ata_smart_attributes": {"table": [{"id": 197, "raw": {"value": 1, "string": "1"}}]} ++ }`, test.name, test.temperature)) ++ ++ sm := &SmartManager{SmartDataMap: make(map[string]*smart.SmartData)} ++ hasData, _ := sm.parseSmartForSata(jsonPayload, "") ++ require.True(t, hasData) ++ assert.Equal(t, test.want, sm.SmartDataMap["PRESERVE"+test.name].SmartStatus) ++ }) ++ } ++} ++ + func TestParseSmartForSataDeviceStatisticsTemperature(t *testing.T) { + jsonPayload := []byte(`{ + "smartctl": {"exit_status": 0}, diff --git a/tasks/henrygd__beszel-2275/tests/test.sh b/tasks/henrygd__beszel-2275/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ecb5785d98245cb721f62547c6d006f910a05b4b --- /dev/null +++ b/tasks/henrygd__beszel-2275/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 467f1767132b8b4e68ae6652b3763e3cbf609586 > "$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/henrygd__beszel-2275/tests/verifier.py b/tasks/henrygd__beszel-2275/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2275/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/henrygd__beszel-2286/environment/Dockerfile b/tasks/henrygd__beszel-2286/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0c6ebe934476a0580eee852cbbcf33a6432e2de9 --- /dev/null +++ b/tasks/henrygd__beszel-2286/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin bc21da9cb3b67139f115915d1e3e87954d6c120b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard bc21da9cb3b67139f115915d1e3e87954d6c120b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base bc21da9cb3b67139f115915d1e3e87954d6c120b \ + && 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/henrygd__beszel-2286/instruction.md b/tasks/henrygd__beszel-2286/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2190cd67dfb94a79244d8f12fdb8af98d1aa72f7 --- /dev/null +++ b/tasks/henrygd__beszel-2286/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(install): add beszel to operator group on FreeBSD for SMART device access + +## Description + +On FreeBSD, the beszel agent needs to be a member of the `operator` group to access SMART-capable devices via `smartctl` (e.g. `/dev/nvme*`, `/dev/xpt0*`). The install script already added the user to `wheel` for self-updates, but that does not grant device access. This change adds the beszel user to `operator` when that group exists, mirroring the existing Linux `disk` group handling. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bc21da9cb3b6`. 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/henrygd__beszel-2286/solution/patch.diff b/tasks/henrygd__beszel-2286/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..add23f72f577ce9c497dc3cbe55f5678d37ff58b --- /dev/null +++ b/tasks/henrygd__beszel-2286/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/supplemental/scripts/install-agent.sh b/supplemental/scripts/install-agent.sh +index e4e9dcea..b03978e9 100755 +--- a/supplemental/scripts/install-agent.sh ++++ b/supplemental/scripts/install-agent.sh +@@ -678,6 +678,11 @@ elif is_freebsd; then + echo "Adding beszel to wheel group for self-updates" + pw group mod wheel -m beszel + fi ++ # Add the user to the operator group for device access (SMART, /dev/xpt0, /dev/nvme*) ++ if pw group show operator >/dev/null 2>&1; then ++ echo "Adding beszel to operator group for device access" ++ pw group mod operator -m beszel ++ fi + fi + + else diff --git a/tasks/henrygd__beszel-2286/solution/solve.sh b/tasks/henrygd__beszel-2286/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2286/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/henrygd__beszel-2286/task.toml b/tasks/henrygd__beszel-2286/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..35c7096577274826217fa87a184f211fa7f10adc --- /dev/null +++ b/tasks/henrygd__beszel-2286/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2286" +description = "fix(install): add beszel to operator group on FreeBSD for SMART device access" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "bc21da9cb3b67139f115915d1e3e87954d6c120b" +reference = "https://github.com/henrygd/beszel/pull/2286" +source_access = "auto" +built_at = "2026-11-16T16:09:53.507788+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c6b7e5d1c568abb546e64bdf14c4b1e211367b22e62163267e67fe1b7cfd8bf0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-06T15:34:04Z" +diff_format = "unified" +context_files = [ + "supplemental/scripts/install-agent.sh", +] +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:00.809809+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6d846931b6d5cc46101a7299d4a266a8455dd0f8b3248414962338caff3eb001" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2286/tests/capture.py b/tasks/henrygd__beszel-2286/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2286/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/henrygd__beszel-2286/tests/instruction.md b/tasks/henrygd__beszel-2286/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2190cd67dfb94a79244d8f12fdb8af98d1aa72f7 --- /dev/null +++ b/tasks/henrygd__beszel-2286/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** fix(install): add beszel to operator group on FreeBSD for SMART device access + +## Description + +On FreeBSD, the beszel agent needs to be a member of the `operator` group to access SMART-capable devices via `smartctl` (e.g. `/dev/nvme*`, `/dev/xpt0*`). The install script already added the user to `wheel` for self-updates, but that does not grant device access. This change adds the beszel user to `operator` when that group exists, mirroring the existing Linux `disk` group handling. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bc21da9cb3b6`. 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/henrygd__beszel-2286/tests/oracle.patch b/tasks/henrygd__beszel-2286/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..add23f72f577ce9c497dc3cbe55f5678d37ff58b --- /dev/null +++ b/tasks/henrygd__beszel-2286/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/supplemental/scripts/install-agent.sh b/supplemental/scripts/install-agent.sh +index e4e9dcea..b03978e9 100755 +--- a/supplemental/scripts/install-agent.sh ++++ b/supplemental/scripts/install-agent.sh +@@ -678,6 +678,11 @@ elif is_freebsd; then + echo "Adding beszel to wheel group for self-updates" + pw group mod wheel -m beszel + fi ++ # Add the user to the operator group for device access (SMART, /dev/xpt0, /dev/nvme*) ++ if pw group show operator >/dev/null 2>&1; then ++ echo "Adding beszel to operator group for device access" ++ pw group mod operator -m beszel ++ fi + fi + + else diff --git a/tasks/henrygd__beszel-2286/tests/test.sh b/tasks/henrygd__beszel-2286/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2aa5fb358561c45b03b4256c2afc36b23a38515b --- /dev/null +++ b/tasks/henrygd__beszel-2286/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 bc21da9cb3b67139f115915d1e3e87954d6c120b > "$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/henrygd__beszel-2286/tests/verifier.py b/tasks/henrygd__beszel-2286/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2286/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/henrygd__beszel-2297/environment/Dockerfile b/tasks/henrygd__beszel-2297/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..352389aa09c9e150e723e9aa7620b479654ddf41 --- /dev/null +++ b/tasks/henrygd__beszel-2297/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 \ + && 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/henrygd__beszel-2297/instruction.md b/tasks/henrygd__beszel-2297/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d01dc0cd20534c6b34b67e8fa2116a21f6f50c2d --- /dev/null +++ b/tasks/henrygd__beszel-2297/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** fix(agent): avoid reconnect loops during slow collection + +## Description + +## 📃 Description + +The agent currently resets its WebSocket deadline to 70 seconds, while the hub default collection interval is 60 seconds. A slow collection can exceed that window and make the agent reconnect even though the hub is still servicing it. + +This change extends the deadline to 120 seconds and adds a regression test that keeps the slow-collection window from being reduced below two minutes. + +## 📖 Documentation + +No documentation changes are needed. + +## 🪵 Changelog + +### 🔧 Fixed + +- Prevent reconnect loops when a collection cycle takes longer than 70 seconds. + +## 📷 Screenshots + +N/A + +## Verification + +- `go test -tags=testing ./agent -run "Test(WebSocketClient|ConnectionManager|WebSocketDeadline)" -count=1` +- `go test -tags="testing no_ui" ./agent -skip TestDirectoryIsWritable -count=1` +- `go vet -tags=testing ./agent` +- `go build -o /tmp/beszel-agent ./internal/cmd/agent` +- `gofmt` and `git diff --check` + +The full agent suite was also compared before and after this change; both runs retain the same container-only `TestDirectoryIsWritable/non-writable_directory` failure because the test container runs as root. No additional failure was introduced. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c157c2026d03`. 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/henrygd__beszel-2297/solution/patch.diff b/tasks/henrygd__beszel-2297/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0aa5edba6339ff6c7b5016e752a05160b9fd6b85 --- /dev/null +++ b/tasks/henrygd__beszel-2297/solution/patch.diff @@ -0,0 +1,31 @@ +diff --git a/agent/client.go b/agent/client.go +index 0dc80fa6..9b1351f6 100644 +--- a/agent/client.go ++++ b/agent/client.go +@@ -25,7 +25,9 @@ import ( + ) + + const ( +- wsDeadline = 70 * time.Second ++ // Keep the connection alive long enough for a slow collection cycle to ++ // finish before the hub considers the agent disconnected. ++ wsDeadline = 120 * time.Second + ) + + type caCertFileError struct { +diff --git a/agent/client_test.go b/agent/client_test.go +index a4598fc1..97cb6654 100644 +--- a/agent/client_test.go ++++ b/agent/client_test.go +@@ -700,3 +700,11 @@ func TestGetToken(t *testing.T) { + assert.Equal(t, expectedToken, token, "Whitespace should be stripped from token file content") + }) + } ++ ++func TestWebSocketDeadlineCoversSlowCollection(t *testing.T) { ++ const minimumDeadline = 120 * time.Second ++ ++ if wsDeadline < minimumDeadline { ++ t.Fatalf("WebSocket deadline %s is shorter than the slow-collection window of %s", wsDeadline, minimumDeadline) ++ } ++} diff --git a/tasks/henrygd__beszel-2297/solution/solve.sh b/tasks/henrygd__beszel-2297/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2297/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/henrygd__beszel-2297/task.toml b/tasks/henrygd__beszel-2297/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d5c384aabbb6b97e0490893b4a6be12a618a585d --- /dev/null +++ b/tasks/henrygd__beszel-2297/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2297" +description = "fix(agent): avoid reconnect loops during slow collection" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "c157c2026d0348aabcfb37c3e9cfafba2b0f8b26" +reference = "https://github.com/henrygd/beszel/pull/2297" +source_access = "auto" +built_at = "2026-11-16T16:09:53.510557+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f18a29b3912dc1c64951dca3c334fcf45f076d6bbf3d4b274e71977db0747be1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-05T17:09:26Z" +diff_format = "unified" +context_files = [ + "agent/client.go", + "agent/client_test.go", +] +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:00.810279+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:aa05e20d6167ddfbf85263c52c72a43421968b8505219d601d1ac0de8c167851" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2297/tests/capture.py b/tasks/henrygd__beszel-2297/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2297/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/henrygd__beszel-2297/tests/instruction.md b/tasks/henrygd__beszel-2297/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d01dc0cd20534c6b34b67e8fa2116a21f6f50c2d --- /dev/null +++ b/tasks/henrygd__beszel-2297/tests/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** fix(agent): avoid reconnect loops during slow collection + +## Description + +## 📃 Description + +The agent currently resets its WebSocket deadline to 70 seconds, while the hub default collection interval is 60 seconds. A slow collection can exceed that window and make the agent reconnect even though the hub is still servicing it. + +This change extends the deadline to 120 seconds and adds a regression test that keeps the slow-collection window from being reduced below two minutes. + +## 📖 Documentation + +No documentation changes are needed. + +## 🪵 Changelog + +### 🔧 Fixed + +- Prevent reconnect loops when a collection cycle takes longer than 70 seconds. + +## 📷 Screenshots + +N/A + +## Verification + +- `go test -tags=testing ./agent -run "Test(WebSocketClient|ConnectionManager|WebSocketDeadline)" -count=1` +- `go test -tags="testing no_ui" ./agent -skip TestDirectoryIsWritable -count=1` +- `go vet -tags=testing ./agent` +- `go build -o /tmp/beszel-agent ./internal/cmd/agent` +- `gofmt` and `git diff --check` + +The full agent suite was also compared before and after this change; both runs retain the same container-only `TestDirectoryIsWritable/non-writable_directory` failure because the test container runs as root. No additional failure was introduced. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c157c2026d03`. 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/henrygd__beszel-2297/tests/oracle.patch b/tasks/henrygd__beszel-2297/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0aa5edba6339ff6c7b5016e752a05160b9fd6b85 --- /dev/null +++ b/tasks/henrygd__beszel-2297/tests/oracle.patch @@ -0,0 +1,31 @@ +diff --git a/agent/client.go b/agent/client.go +index 0dc80fa6..9b1351f6 100644 +--- a/agent/client.go ++++ b/agent/client.go +@@ -25,7 +25,9 @@ import ( + ) + + const ( +- wsDeadline = 70 * time.Second ++ // Keep the connection alive long enough for a slow collection cycle to ++ // finish before the hub considers the agent disconnected. ++ wsDeadline = 120 * time.Second + ) + + type caCertFileError struct { +diff --git a/agent/client_test.go b/agent/client_test.go +index a4598fc1..97cb6654 100644 +--- a/agent/client_test.go ++++ b/agent/client_test.go +@@ -700,3 +700,11 @@ func TestGetToken(t *testing.T) { + assert.Equal(t, expectedToken, token, "Whitespace should be stripped from token file content") + }) + } ++ ++func TestWebSocketDeadlineCoversSlowCollection(t *testing.T) { ++ const minimumDeadline = 120 * time.Second ++ ++ if wsDeadline < minimumDeadline { ++ t.Fatalf("WebSocket deadline %s is shorter than the slow-collection window of %s", wsDeadline, minimumDeadline) ++ } ++} diff --git a/tasks/henrygd__beszel-2297/tests/test.sh b/tasks/henrygd__beszel-2297/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d6be1a89c574b99fd94339c386a3cbfa4a0aae87 --- /dev/null +++ b/tasks/henrygd__beszel-2297/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 c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 > "$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/henrygd__beszel-2297/tests/verifier.py b/tasks/henrygd__beszel-2297/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2297/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/henrygd__beszel-2303/environment/Dockerfile b/tasks/henrygd__beszel-2303/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..352389aa09c9e150e723e9aa7620b479654ddf41 --- /dev/null +++ b/tasks/henrygd__beszel-2303/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 \ + && 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/henrygd__beszel-2303/instruction.md b/tasks/henrygd__beszel-2303/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1d04227088ade7a56f1da3aae960f378ca48e086 --- /dev/null +++ b/tasks/henrygd__beszel-2303/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** feat(site): display NVMe data units as human-readable GB/TB + +## Description + +## 📃 Description + +Displays NVMe Data Units Written and Data Units Read S.M.A.R.T. values as human-readable GB/TB instead of raw unit counts, reusing the existing `formatCapacity` function. Only these two attributes are affected. + +## 📖 Documentation + +No documentation changes required. + +## 🪵 Changelog + +### ✏️ Changed + +- NVMe Data Units Written/Read now show as GB/TB in the S.M.A.R.T. details sheet. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c157c2026d03`. 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/henrygd__beszel-2303/solution/patch.diff b/tasks/henrygd__beszel-2303/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d2d8d3474aceb4da8353c5d1e45beed65c96dffd --- /dev/null +++ b/tasks/henrygd__beszel-2303/solution/patch.diff @@ -0,0 +1,31 @@ +diff --git a/internal/site/src/components/routes/system/smart-table.tsx b/internal/site/src/components/routes/system/smart-table.tsx +index d6ec6730..2efeb791 100644 +--- a/internal/site/src/components/routes/system/smart-table.tsx ++++ b/internal/site/src/components/routes/system/smart-table.tsx +@@ -75,7 +75,12 @@ export const smartColumns: ColumnDef[] = [ + header: "Name", + }, + { +- accessorFn: (row) => row.rs || row.rv?.toString(), ++ accessorFn: (row) => { ++ if (row.n === "DataUnitsWritten" || row.n === "DataUnitsRead") { ++ return formatDataUnits(Number(row.rv ?? 0)) ++ } ++ return row.rs || row.rv?.toString() ++ }, + header: "Value", + }, + { +@@ -103,6 +108,12 @@ function formatCapacity(bytes: number): string { + return `${toFixedFloat(value, value >= 10 ? 1 : 2)} ${unit}` + } + ++// Function to format NVMe data units ++// (1 unit = 1000 * 512 bytes) as a human-readable size ++function formatDataUnits(units: number): string { ++ return formatCapacity(units * 1000 * 512) ++} ++ + const SMART_DEVICE_FIELDS = "id,system,name,model,state,capacity,temp,type,hours,cycles,updated" + + export const createColumns = ( diff --git a/tasks/henrygd__beszel-2303/solution/solve.sh b/tasks/henrygd__beszel-2303/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2303/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/henrygd__beszel-2303/task.toml b/tasks/henrygd__beszel-2303/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..97395243acebcbe3bd88de0d74a46e5b60204f04 --- /dev/null +++ b/tasks/henrygd__beszel-2303/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2303" +description = "feat(site): display NVMe data units as human-readable GB/TB" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "c157c2026d0348aabcfb37c3e9cfafba2b0f8b26" +reference = "https://github.com/henrygd/beszel/pull/2303" +source_access = "auto" +built_at = "2026-11-16T16:09:53.509084+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a6388b881ad237b35ed0f35c1989f35da24f8cfda8318a84007d76e2000231b6" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-05T18:44:03Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/routes/system/smart-table.tsx", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 13 +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:00.810778+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:aa05e20d6167ddfbf85263c52c72a43421968b8505219d601d1ac0de8c167851" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2303/tests/capture.py b/tasks/henrygd__beszel-2303/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2303/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/henrygd__beszel-2303/tests/instruction.md b/tasks/henrygd__beszel-2303/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1d04227088ade7a56f1da3aae960f378ca48e086 --- /dev/null +++ b/tasks/henrygd__beszel-2303/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** feat(site): display NVMe data units as human-readable GB/TB + +## Description + +## 📃 Description + +Displays NVMe Data Units Written and Data Units Read S.M.A.R.T. values as human-readable GB/TB instead of raw unit counts, reusing the existing `formatCapacity` function. Only these two attributes are affected. + +## 📖 Documentation + +No documentation changes required. + +## 🪵 Changelog + +### ✏️ Changed + +- NVMe Data Units Written/Read now show as GB/TB in the S.M.A.R.T. details sheet. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c157c2026d03`. 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/henrygd__beszel-2303/tests/oracle.patch b/tasks/henrygd__beszel-2303/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d2d8d3474aceb4da8353c5d1e45beed65c96dffd --- /dev/null +++ b/tasks/henrygd__beszel-2303/tests/oracle.patch @@ -0,0 +1,31 @@ +diff --git a/internal/site/src/components/routes/system/smart-table.tsx b/internal/site/src/components/routes/system/smart-table.tsx +index d6ec6730..2efeb791 100644 +--- a/internal/site/src/components/routes/system/smart-table.tsx ++++ b/internal/site/src/components/routes/system/smart-table.tsx +@@ -75,7 +75,12 @@ export const smartColumns: ColumnDef[] = [ + header: "Name", + }, + { +- accessorFn: (row) => row.rs || row.rv?.toString(), ++ accessorFn: (row) => { ++ if (row.n === "DataUnitsWritten" || row.n === "DataUnitsRead") { ++ return formatDataUnits(Number(row.rv ?? 0)) ++ } ++ return row.rs || row.rv?.toString() ++ }, + header: "Value", + }, + { +@@ -103,6 +108,12 @@ function formatCapacity(bytes: number): string { + return `${toFixedFloat(value, value >= 10 ? 1 : 2)} ${unit}` + } + ++// Function to format NVMe data units ++// (1 unit = 1000 * 512 bytes) as a human-readable size ++function formatDataUnits(units: number): string { ++ return formatCapacity(units * 1000 * 512) ++} ++ + const SMART_DEVICE_FIELDS = "id,system,name,model,state,capacity,temp,type,hours,cycles,updated" + + export const createColumns = ( diff --git a/tasks/henrygd__beszel-2303/tests/test.sh b/tasks/henrygd__beszel-2303/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d6be1a89c574b99fd94339c386a3cbfa4a0aae87 --- /dev/null +++ b/tasks/henrygd__beszel-2303/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 c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 > "$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/henrygd__beszel-2303/tests/verifier.py b/tasks/henrygd__beszel-2303/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2303/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/henrygd__beszel-2304/environment/Dockerfile b/tasks/henrygd__beszel-2304/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..352389aa09c9e150e723e9aa7620b479654ddf41 --- /dev/null +++ b/tasks/henrygd__beszel-2304/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 \ + && 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/henrygd__beszel-2304/instruction.md b/tasks/henrygd__beszel-2304/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6329efa6b9d633eddc565dc44be877ec8bdf9d75 --- /dev/null +++ b/tasks/henrygd__beszel-2304/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Improve agent installer error handling + +## Description + +fix: improve agent installer error handling (#1971, #1972) + +- Enable set -eu and handle expected failures explicitly +- Validate platform and service manager before making changes +- Fix argument parsing, version fallback, cron setup, and prompt EOF +- Verify downloads before stopping the existing agent +- Add atomic binary replacement, rollback, and cleanup + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c157c2026d03`. 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/henrygd__beszel-2304/solution/patch.diff b/tasks/henrygd__beszel-2304/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..892ec420d39cb00b2b07211485e5a89210ed6591 --- /dev/null +++ b/tasks/henrygd__beszel-2304/solution/patch.diff @@ -0,0 +1,578 @@ +diff --git a/supplemental/scripts/install-agent.sh b/supplemental/scripts/install-agent.sh +index e4e9dcea..4ffd7a6f 100755 +--- a/supplemental/scripts/install-agent.sh ++++ b/supplemental/scripts/install-agent.sh +@@ -43,7 +43,7 @@ is_glibc() { + set_selinux_context() { + # Check if SELinux is enabled and in enforcing or permissive mode + if command -v getenforce >/dev/null 2>&1; then +- SELINUX_MODE=$(getenforce) ++ SELINUX_MODE=$(getenforce) || { warn "Could not query SELinux mode."; return 0; } + if [ "$SELINUX_MODE" != "Disabled" ]; then + echo "SELinux is enabled (${SELINUX_MODE} mode). Setting appropriate context..." + +@@ -51,7 +51,7 @@ set_selinux_context() { + if command -v semanage >/dev/null 2>&1; then + echo "Attempting to set persistent SELinux context..." + if semanage fcontext -a -t bin_t "$BIN_PATH" >/dev/null 2>&1; then +- restorecon -v "$BIN_PATH" >/dev/null 2>&1 ++ restorecon -v "$BIN_PATH" >/dev/null 2>&1 || warn "Failed to restore persistent SELinux context; trying chcon." + else + echo "Warning: Failed to set persistent context, falling back to temporary context." + fi +@@ -271,7 +271,7 @@ detect_mips_endianness() { + for bin_to_check in $bins; do + if [ -f "$bin_to_check" ]; then + # The 6th byte in ELF header: 01 = little, 02 = big +- endian=$(hexdump -n 1 -s 5 -e '1/1 "%02x"' "$bin_to_check" 2>/dev/null) ++ endian=$(hexdump -n 1 -s 5 -e '1/1 "%02x"' "$bin_to_check" 2>/dev/null) || continue + if [ "$endian" = "01" ]; then + echo "mipsle" + return +@@ -286,6 +286,136 @@ detect_mips_endianness() { + echo "mips" + } + ++# Expected failures must be handled explicitly; unexpected failures abort installation. ++set -eu ++ ++fail() { ++ echo "Error: $*" >&2 ++ exit 1 ++} ++ ++warn() { ++ echo "Warning: $*" >&2 ++} ++ ++require_value() { ++ [ "$#" -ge 2 ] && [ -n "$2" ] || fail "Option $1 requires a value." ++} ++ ++validate_platform() { ++ case "$(uname -s)" in ++ Linux) ++ if is_alpine; then ++ command -v rc-service >/dev/null && command -v rc-update >/dev/null || fail "OpenRC is required." ++ elif is_openwrt; then ++ [ -f /etc/rc.common ] || fail "OpenWrt procd is required." ++ else ++ command -v systemctl >/dev/null && [ -d /run/systemd/system ] || fail "This Linux installer requires a running systemd, OpenRC (Alpine), or procd (OpenWrt)." ++ fi ++ ;; ++ FreeBSD) ++ command -v service >/dev/null && command -v sysrc >/dev/null || fail "FreeBSD service and sysrc commands are required." ++ ;; ++ Darwin) fail "For macOS, use the Homebrew installer: https://github.com/henrygd/beszel/blob/main/supplemental/scripts/install-agent-brew.sh" ;; ++ *) fail "Unsupported operating system: $(uname -s)" ;; ++ esac ++} ++ ++agent_service() { ++ if is_alpine; then ++ rc-service beszel-agent "$1" ++ elif is_openwrt; then ++ /etc/init.d/beszel-agent "$1" ++ elif is_freebsd; then ++ service beszel-agent "$1" ++ else ++ systemctl "$1" beszel-agent.service ++ fi ++} ++ ++# Match the files preserved by the service setup below. A binary or rc script ++# alone is not reusable configuration (FreeBSD stores its environment separately). ++agent_configuration_exists() { ++ if is_alpine || is_openwrt; then ++ [ -f /etc/init.d/beszel-agent ] ++ elif is_freebsd; then ++ [ -f "$AGENT_DIR/env" ] ++ else ++ [ -f /etc/systemd/system/beszel-agent.service ] ++ fi ++} ++ ++# An orphaned binary can remain after a failed install. It does not imply ++# that the service manager knows about the agent yet. ++agent_service_registered() { ++ if is_alpine || is_openwrt; then ++ [ -f /etc/init.d/beszel-agent ] ++ elif is_freebsd; then ++ [ -f /usr/local/etc/rc.d/beszel-agent ] ++ else ++ service_load_state=$(systemctl show --property=LoadState --value beszel-agent.service) || return 2 ++ case "$service_load_state" in ++ not-found) return 1 ;; ++ "") return 2 ;; ++ *) return 0 ;; ++ esac ++ fi ++} ++ ++TEMP_DIR="" ++STAGED_BINARY="" ++INSTALL_STEP="validating installation options" ++UPGRADE_PENDING=false ++cleanup() { ++ cleanup_status=$? ++ trap - 0 HUP INT TERM ++ if [ "$cleanup_status" -ne 0 ]; then ++ warn "Installer failed while $INSTALL_STEP (exit $cleanup_status)." ++ if [ "$UPGRADE_PENDING" = true ]; then ++ warn "Restoring the previous binary and restarting its service if registered." ++ if [ -n "$STAGED_BINARY" ]; then ++ rm -f "$STAGED_BINARY" || warn "Could not remove staged binary." ++ fi ++ if STAGED_BINARY=$(mktemp "$BIN_PATH.XXXXXX") && cp -p "$BIN_PATH.bak" "$STAGED_BINARY" && mv -f "$STAGED_BINARY" "$BIN_PATH"; then ++ # The temporary inode does not inherit the installed binary's SELinux label. ++ set_selinux_context || warn "Could not restore SELinux context on the previous agent." ++ if agent_service_registered; then ++ agent_service restart || warn "Could not restart the previous agent; check the service configuration and logs." ++ else ++ service_check_status=$? ++ [ "$service_check_status" -eq 1 ] || warn "Could not determine whether the previous agent service is registered; check it manually." ++ fi ++ else ++ warn "Could not restore $BIN_PATH.bak. Restore it manually before restarting the service." ++ fi ++ fi ++ fi ++ if [ -n "$STAGED_BINARY" ]; then ++ rm -f "$STAGED_BINARY" || warn "Could not remove staged binary." ++ fi ++ if [ -n "$TEMP_DIR" ]; then ++ rm -rf "$TEMP_DIR" || warn "Could not remove temporary directory $TEMP_DIR." ++ fi ++ exit "$cleanup_status" ++} ++trap cleanup 0 ++trap 'exit 129' HUP ++trap 'exit 130' INT ++trap 'exit 143' TERM ++ ++# A missing crontab is normal. Keep the producer alive so the new job is written. ++read_root_crontab() { ++ crontab -u root -l 2>/dev/null || true ++} ++ ++prompt_auto_update() { ++ printf "\nEnable automatic daily updates for beszel-agent? (y/n): " ++ if ! read -r AUTO_UPDATE; then ++ AUTO_UPDATE=n ++ echo "Skipping automatic updates (no input)." ++ fi ++} ++ + # Default values + PORT=45876 + UNINSTALL=false +@@ -304,7 +434,7 @@ HUB_URL_PROVIDED=false + VERSION="latest" + + # Check for help flag +-case "$1" in ++case "${1-}" in + -h | --help) + printf "Beszel Agent installation script\n\n" + printf "Usage: ./install-agent.sh [options]\n\n" +@@ -324,6 +454,9 @@ case "$1" in + ;; + esac + ++# Reject unsupported hosts before sudo or any system changes. ++validate_platform ++ + # Build sudo args by properly quoting everything + build_sudo_args() { + QUOTED_ARGS="" +@@ -354,26 +487,31 @@ fi + while [ $# -gt 0 ]; do + case "$1" in + -k) ++ require_value "$@" + shift + KEY="$1" + KEY_PROVIDED=true + ;; + -p) ++ require_value "$@" + shift + PORT="$1" + PORT_PROVIDED=true + ;; + -t) ++ require_value "$@" + shift + TOKEN="$1" + TOKEN_PROVIDED=true + ;; + -url) ++ require_value "$@" + shift + HUB_URL="$1" + HUB_URL_PROVIDED=true + ;; + -v | --version) ++ require_value "$@" + shift + VERSION="$1" + ;; +@@ -392,7 +530,7 @@ while [ $# -gt 0 ]; do + GITHUB_PROXY_URL="https://gh.beszel.dev" + GITHUB_URL="$GITHUB_PROXY_URL" + fi +- elif [ "$2" != "" ] && ! echo "$2" | grep -q '^-'; then ++ elif [ "${2-}" != "" ] && ! echo "$2" | grep -q '^-'; then + # use custom proxy URL provided as next argument + GITHUB_PROXY_URL="$2" + GITHUB_URL="$(ensure_trailing_slash "$2")https://github.com" +@@ -415,7 +553,7 @@ while [ $# -gt 0 ]; do + else + echo "Invalid value for --auto-update flag: $AUTO_UPDATE_VALUE. Using default (prompt)." + fi +- elif [ "$2" = "true" ] || [ "$2" = "false" ]; then ++ elif [ "${2-}" = "true" ] || [ "${2-}" = "false" ]; then + # Value provided as next argument + AUTO_UPDATE_FLAG="$2" + shift +@@ -443,20 +581,7 @@ else + BIN_PATH="/opt/beszel-agent/beszel-agent" + fi + +-# Stop existing service if it exists (for upgrades) +-if [ "$UNINSTALL" != true ] && [ -f "$BIN_PATH" ]; then +- echo "Existing installation detected. Stopping service for upgrade..." +- if is_alpine; then +- rc-service beszel-agent stop 2>/dev/null || true +- elif is_openwrt; then +- /etc/init.d/beszel-agent stop 2>/dev/null || true +- elif is_freebsd; then +- service beszel-agent stop 2>/dev/null || true +- else +- systemctl stop beszel-agent.service 2>/dev/null || true +- fi +-fi +- ++INSTALL_STEP="uninstalling the agent" + # Uninstall process + if [ "$UNINSTALL" = true ]; then + # Clean up SELinux contexts before removing files +@@ -464,8 +589,8 @@ if [ "$UNINSTALL" = true ]; then + + if is_alpine; then + echo "Stopping and disabling the agent service..." +- rc-service beszel-agent stop +- rc-update del beszel-agent default ++ rc-service beszel-agent stop || warn "Cleanup command failed: rc-service beszel-agent stop" ++ rc-update del beszel-agent default || warn "Cleanup command failed: rc-update del beszel-agent default" + + echo "Removing the OpenRC service files..." + rm -f /etc/init.d/beszel-agent +@@ -481,8 +606,8 @@ if [ "$UNINSTALL" = true ]; then + rm -f /var/log/beszel-agent.log /var/log/beszel-agent.err + elif is_openwrt; then + echo "Stopping and disabling the agent service..." +- /etc/init.d/beszel-agent stop +- /etc/init.d/beszel-agent disable ++ /etc/init.d/beszel-agent stop || warn "Cleanup command failed: /etc/init.d/beszel-agent stop" ++ /etc/init.d/beszel-agent disable || warn "Cleanup command failed: /etc/init.d/beszel-agent disable" + + echo "Removing the OpenWRT service files..." + rm -f /etc/init.d/beszel-agent +@@ -498,7 +623,7 @@ if [ "$UNINSTALL" = true ]; then + + elif is_freebsd; then + echo "Stopping and disabling the agent service..." +- service beszel-agent stop ++ service beszel-agent stop || warn "Cleanup command failed: service beszel-agent stop" + sysrc beszel_agent_enable="NO" + + echo "Removing the FreeBSD service files..." +@@ -525,16 +650,16 @@ if [ "$UNINSTALL" = true ]; then + + else + echo "Stopping and disabling the agent service..." +- systemctl stop beszel-agent.service +- systemctl disable beszel-agent.service >/dev/null 2>&1 ++ systemctl stop beszel-agent.service || warn "Cleanup command failed: systemctl stop beszel-agent.service" ++ systemctl disable beszel-agent.service >/dev/null 2>&1 || warn "Cleanup command failed: systemctl disable beszel-agent.service" + + echo "Removing the systemd service file..." +- rm /etc/systemd/system/beszel-agent.service ++ rm -f /etc/systemd/system/beszel-agent.service + + # Remove the update timer and service if they exist + echo "Removing the daily update service and timer..." +- systemctl stop beszel-agent-update.timer 2>/dev/null +- systemctl disable beszel-agent-update.timer >/dev/null 2>&1 ++ systemctl stop beszel-agent-update.timer 2>/dev/null || warn "Cleanup command failed: systemctl stop beszel-agent-update.timer" ++ systemctl disable beszel-agent-update.timer >/dev/null 2>&1 || warn "Cleanup command failed: systemctl disable beszel-agent-update.timer" + rm -f /etc/systemd/system/beszel-agent-update.service + rm -f /etc/systemd/system/beszel-agent-update.timer + +@@ -545,13 +670,15 @@ if [ "$UNINSTALL" = true ]; then + rm -rf "$AGENT_DIR" + + echo "Removing the dedicated user for the agent service..." +- killall beszel-agent 2>/dev/null +- if is_alpine || is_openwrt; then +- deluser beszel 2>/dev/null +- elif is_freebsd; then +- pw user del beszel 2>/dev/null +- else +- userdel beszel 2>/dev/null ++ killall beszel-agent 2>/dev/null || true # Usually already stopped by the service manager. ++ if id -u beszel >/dev/null 2>&1; then ++ if is_alpine || is_openwrt; then ++ deluser beszel || fail "Could not remove the beszel user." ++ elif is_freebsd; then ++ pw user del beszel || fail "Could not remove the beszel user." ++ else ++ userdel beszel || fail "Could not remove the beszel user." ++ fi + fi + + echo "Beszel Agent has been uninstalled successfully!" +@@ -563,6 +690,7 @@ package_installed() { + command -v "$1" >/dev/null 2>&1 + } + ++INSTALL_STEP="installing required packages" + # Check for package manager and install necessary packages if not installed + if package_installed apk; then + if ! package_installed tar || ! package_installed curl || ! package_installed sha256sum; then +@@ -596,13 +724,18 @@ else + echo "Warning: Please ensure 'tar' and 'curl' and 'sha256sum (coreutils)' are installed." + fi + +-# If no SSH key is provided, ask for the SSH key interactively (skip if upgrading) ++for required_command in tar curl; do ++ command -v "$required_command" >/dev/null || fail "Required command is missing: $required_command" ++done ++ ++# If no SSH key is provided, prompt unless service setup will reuse configuration. + if [ -z "$KEY" ]; then +- if [ -f "$BIN_PATH" ]; then +- echo "Upgrading existing installation. Using existing service configuration." ++ if agent_configuration_exists; then ++ echo "Using existing service configuration." + else + printf "Enter your SSH key: " +- read KEY ++ read -r KEY || fail "No SSH key received. Supply -k for noninteractive installation." ++ [ -n "$KEY" ] || fail "SSH key must not be empty." + fi + fi + +@@ -623,6 +756,7 @@ else + exit 1 + fi + ++INSTALL_STEP="configuring the service user" + # Create a dedicated user for the service if it doesn't exist + AGENT_USER="beszel" + echo "Configuring the dedicated user for the Beszel Agent service..." +@@ -696,6 +830,7 @@ else + fi + fi + ++INSTALL_STEP="creating installation directories" + # Create the directory for the Beszel Agent + + if [ ! -d "$AGENT_DIR" ]; then +@@ -709,6 +844,7 @@ if [ ! -d "$BIN_DIR" ]; then + mkdir -p "$BIN_DIR" + fi + ++INSTALL_STEP="downloading and verifying the agent" + # Download and install the Beszel Agent + + OS=$(uname -s | sed -e 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/') +@@ -720,11 +856,12 @@ fi + + # Determine version to install + if [ "$VERSION" = "latest" ]; then +- INSTALL_VERSION=$(curl -s "https://get.beszel.dev/latest-version") ++ INSTALL_VERSION=$(curl -fsS --connect-timeout 10 --max-time 30 "https://get.beszel.dev/latest-version") || INSTALL_VERSION="" + if [ -z "$INSTALL_VERSION" ]; then + # Fallback to GitHub API + API_RELEASE_URL="https://api.github.com/repos/henrygd/beszel/releases/latest" +- INSTALL_VERSION=$(curl -s "$API_RELEASE_URL" | grep -o '"tag_name": "v[^"]*"' | cut -d'"' -f4 | tr -d 'v') ++ RELEASE_JSON=$(curl -fsS --connect-timeout 10 --max-time 30 "$API_RELEASE_URL") || fail "Could not fetch the latest release from GitHub." ++ INSTALL_VERSION=$(printf '%s\n' "$RELEASE_JSON" | grep -o '"tag_name": "v[^"]*"' | cut -d'"' -f4 | tr -d 'v') + fi + if [ -z "$INSTALL_VERSION" ]; then + echo "Failed to get latest version" +@@ -741,7 +878,8 @@ echo "Downloading beszel-agent v${INSTALL_VERSION}..." + # Download checksums file + TEMP_DIR=$(mktemp -d) + cd "$TEMP_DIR" || exit 1 +-CHECKSUM=$(curl -fsSL "$GITHUB_URL/henrygd/beszel/releases/download/v${INSTALL_VERSION}/beszel_${INSTALL_VERSION}_checksums.txt" | grep "$FILE_NAME" | cut -d' ' -f1) ++curl -fsSL --connect-timeout 10 --max-time 60 "$GITHUB_URL/henrygd/beszel/releases/download/v${INSTALL_VERSION}/beszel_${INSTALL_VERSION}_checksums.txt" -o checksums.txt || fail "Could not download checksums. Try --mirror if GitHub is unreachable." ++CHECKSUM=$(awk -v name="$FILE_NAME" '$2 == name { print $1 }' checksums.txt) + if [ -z "$CHECKSUM" ] || ! echo "$CHECKSUM" | grep -qE "^[a-fA-F0-9]{64}$"; then + echo "Failed to get checksum or invalid checksum format" + echo "Try again with --mirror (or --mirror ) if GitHub is not reachable." +@@ -763,10 +901,10 @@ if ! tar -tzf "$FILE_NAME" >/dev/null 2>&1; then + exit 1 + fi + +-if [ "$($CHECK_CMD "$FILE_NAME" | cut -d' ' -f1)" != "$CHECKSUM" ]; then +- echo "Checksum verification failed: $($CHECK_CMD "$FILE_NAME" | cut -d' ' -f1) & $CHECKSUM" +- rm -rf "$TEMP_DIR" +- exit 1 ++ACTUAL_CHECKSUM=$($CHECK_CMD "$FILE_NAME") || fail "Could not calculate archive checksum." ++ACTUAL_CHECKSUM=${ACTUAL_CHECKSUM%% *} ++if [ "$ACTUAL_CHECKSUM" != "$CHECKSUM" ]; then ++ fail "Checksum verification failed: $ACTUAL_CHECKSUM != $CHECKSUM" + fi + + if ! tar -xzf "$FILE_NAME" beszel-agent; then +@@ -781,20 +919,34 @@ if [ ! -s "$TEMP_DIR/beszel-agent" ]; then + exit 1 + fi + ++INSTALL_STEP="replacing the agent binary" ++# Stage on the destination filesystem so replacement and rollback use atomic renames. ++STAGED_BINARY=$(mktemp "$BIN_PATH.XXXXXX") || fail "Could not create a staged binary." ++cp beszel-agent "$STAGED_BINARY" || fail "Could not stage the agent binary." ++chown "${AGENT_USER}:${AGENT_USER}" "$STAGED_BINARY" || fail "Could not set binary ownership." ++chmod 755 "$STAGED_BINARY" || fail "Could not set binary permissions." ++ + if [ -f "$BIN_PATH" ]; then + echo "Backing up existing binary..." +- cp "$BIN_PATH" "$BIN_PATH.bak" ++ cp -p "$BIN_PATH" "$BIN_PATH.bak" || fail "Could not back up the existing binary." ++ UPGRADE_PENDING=true ++ if agent_service_registered; then ++ agent_service stop || fail "Could not stop the existing agent." ++ else ++ service_check_status=$? ++ [ "$service_check_status" -eq 1 ] || fail "Could not determine whether the existing agent service is registered." ++ fi + fi + +-mv beszel-agent "$BIN_PATH" +-chown "${AGENT_USER}:${AGENT_USER}" "$BIN_PATH" +-chmod 755 "$BIN_PATH" ++mv -f "$STAGED_BINARY" "$BIN_PATH" || fail "Could not install the agent binary." ++STAGED_BINARY="" + + # Set SELinux context if needed + set_selinux_context + + # Cleanup + rm -rf "$TEMP_DIR" ++TEMP_DIR="" + + # Make sure /etc/machine-id exists and is non-empty for persistent fingerprint + if [ ! -s /etc/machine-id ]; then +@@ -819,6 +971,7 @@ detect_nvidia_devices() { + echo "$devices" + } + ++INSTALL_STEP="configuring and starting the service" + # Modify service installation part, add Alpine check before systemd service creation + if is_alpine; then + if [ ! -f /etc/init.d/beszel-agent ]; then +@@ -868,7 +1021,7 @@ EOF + chown "${AGENT_USER}:${AGENT_USER}" /var/log/beszel-agent.log /var/log/beszel-agent.err + + # Start the service +- rc-service beszel-agent restart ++ rc-service beszel-agent restart || fail "Could not start the agent; check service logs." + + # Check if service started successfully + sleep 2 +@@ -884,8 +1037,7 @@ EOF + elif [ "$AUTO_UPDATE_FLAG" = "false" ]; then + AUTO_UPDATE="n" + else +- printf "\nEnable automatic daily updates for beszel-agent? (y/n): " +- read AUTO_UPDATE ++ prompt_auto_update + fi + case "$AUTO_UPDATE" in + [Yy]*) +@@ -893,7 +1045,7 @@ EOF + + # Create cron job to run beszel-agent update command daily at midnight + if ! crontab -u root -l 2>/dev/null | grep -q "beszel-agent.*update"; then +- (crontab -u root -l 2>/dev/null; echo "12 0 * * * $BIN_PATH update >/dev/null 2>&1") | crontab -u root - ++ (read_root_crontab; echo "12 0 * * * $BIN_PATH update >/dev/null 2>&1") | crontab -u root - + fi + + printf "\nDaily updates have been enabled via cron job.\n" +@@ -963,7 +1115,7 @@ EOF + fi + + # Start the service +- /etc/init.d/beszel-agent restart ++ /etc/init.d/beszel-agent restart || fail "Could not start the agent; check service logs." + + # Auto-update service for OpenWRT using a crontab job + if [ "$AUTO_UPDATE_FLAG" = "true" ]; then +@@ -973,15 +1125,14 @@ EOF + AUTO_UPDATE="n" + sleep 1 # give time for the service to start + else +- printf "\nEnable automatic daily updates for beszel-agent? (y/n): " +- read AUTO_UPDATE ++ prompt_auto_update + fi + case "$AUTO_UPDATE" in + [Yy]*) + echo "Setting up daily automatic updates for beszel-agent..." + + if ! crontab -u root -l 2>/dev/null | grep -q "beszel-agent.*update"; then +- (crontab -u root -l 2>/dev/null; echo "12 0 * * * /etc/init.d/beszel-agent update") | crontab -u root - ++ (read_root_crontab; echo "12 0 * * * /etc/init.d/beszel-agent update") | crontab -u root - + fi + + /etc/init.d/cron restart +@@ -1072,7 +1223,7 @@ EOF + esac + fi + +- service beszel-agent restart ++ service beszel-agent restart || fail "Could not start the agent; check service logs." + + # Check if service started successfully + sleep 2 +@@ -1088,8 +1239,7 @@ EOF + elif [ "$AUTO_UPDATE_FLAG" = "false" ]; then + AUTO_UPDATE="n" + else +- printf "\nEnable automatic daily updates for beszel-agent? (y/n): " +- read AUTO_UPDATE ++ prompt_auto_update + fi + case "$AUTO_UPDATE" in + [Yy]*) +@@ -1170,7 +1320,7 @@ EOF + printf "\nLoading and starting the agent service...\n" + systemctl daemon-reload + systemctl enable beszel-agent.service >/dev/null 2>&1 +- systemctl restart beszel-agent.service ++ systemctl restart beszel-agent.service || fail "Could not start the agent; check service logs." + + + +@@ -1182,8 +1332,7 @@ EOF + AUTO_UPDATE="n" + sleep 1 # give time for the service to start + else +- printf "\nEnable automatic daily updates for beszel-agent? (y/n): " +- read AUTO_UPDATE ++ prompt_auto_update + fi + case "$AUTO_UPDATE" in + [Yy]*) +@@ -1229,6 +1378,7 @@ EOF + fi + fi + ++UPGRADE_PENDING=false + RUNNING_ADDRESS=$(configured_address) + [ -n "$RUNNING_ADDRESS" ] || RUNNING_ADDRESS=$PORT + diff --git a/tasks/henrygd__beszel-2304/solution/solve.sh b/tasks/henrygd__beszel-2304/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2304/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/henrygd__beszel-2304/task.toml b/tasks/henrygd__beszel-2304/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7e3571e09ffd546bc66300c95dda04145dfd267d --- /dev/null +++ b/tasks/henrygd__beszel-2304/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2304" +description = "Improve agent installer error handling" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "c157c2026d0348aabcfb37c3e9cfafba2b0f8b26" +reference = "https://github.com/henrygd/beszel/pull/2304" +source_access = "auto" +built_at = "2026-11-16T16:09:53.512239+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:80d0d791027b3947f9dc84d0a7abf0e3e5465c887fa9c8edd4b54deaf738e1f2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-05T17:06:35Z" +diff_format = "unified" +context_files = [ + "supplemental/scripts/install-agent.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 282 +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:00.811238+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:aa05e20d6167ddfbf85263c52c72a43421968b8505219d601d1ac0de8c167851" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2304/tests/capture.py b/tasks/henrygd__beszel-2304/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2304/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/henrygd__beszel-2304/tests/instruction.md b/tasks/henrygd__beszel-2304/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6329efa6b9d633eddc565dc44be877ec8bdf9d75 --- /dev/null +++ b/tasks/henrygd__beszel-2304/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** Improve agent installer error handling + +## Description + +fix: improve agent installer error handling (#1971, #1972) + +- Enable set -eu and handle expected failures explicitly +- Validate platform and service manager before making changes +- Fix argument parsing, version fallback, cron setup, and prompt EOF +- Verify downloads before stopping the existing agent +- Add atomic binary replacement, rollback, and cleanup + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c157c2026d03`. 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/henrygd__beszel-2304/tests/oracle.patch b/tasks/henrygd__beszel-2304/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..892ec420d39cb00b2b07211485e5a89210ed6591 --- /dev/null +++ b/tasks/henrygd__beszel-2304/tests/oracle.patch @@ -0,0 +1,578 @@ +diff --git a/supplemental/scripts/install-agent.sh b/supplemental/scripts/install-agent.sh +index e4e9dcea..4ffd7a6f 100755 +--- a/supplemental/scripts/install-agent.sh ++++ b/supplemental/scripts/install-agent.sh +@@ -43,7 +43,7 @@ is_glibc() { + set_selinux_context() { + # Check if SELinux is enabled and in enforcing or permissive mode + if command -v getenforce >/dev/null 2>&1; then +- SELINUX_MODE=$(getenforce) ++ SELINUX_MODE=$(getenforce) || { warn "Could not query SELinux mode."; return 0; } + if [ "$SELINUX_MODE" != "Disabled" ]; then + echo "SELinux is enabled (${SELINUX_MODE} mode). Setting appropriate context..." + +@@ -51,7 +51,7 @@ set_selinux_context() { + if command -v semanage >/dev/null 2>&1; then + echo "Attempting to set persistent SELinux context..." + if semanage fcontext -a -t bin_t "$BIN_PATH" >/dev/null 2>&1; then +- restorecon -v "$BIN_PATH" >/dev/null 2>&1 ++ restorecon -v "$BIN_PATH" >/dev/null 2>&1 || warn "Failed to restore persistent SELinux context; trying chcon." + else + echo "Warning: Failed to set persistent context, falling back to temporary context." + fi +@@ -271,7 +271,7 @@ detect_mips_endianness() { + for bin_to_check in $bins; do + if [ -f "$bin_to_check" ]; then + # The 6th byte in ELF header: 01 = little, 02 = big +- endian=$(hexdump -n 1 -s 5 -e '1/1 "%02x"' "$bin_to_check" 2>/dev/null) ++ endian=$(hexdump -n 1 -s 5 -e '1/1 "%02x"' "$bin_to_check" 2>/dev/null) || continue + if [ "$endian" = "01" ]; then + echo "mipsle" + return +@@ -286,6 +286,136 @@ detect_mips_endianness() { + echo "mips" + } + ++# Expected failures must be handled explicitly; unexpected failures abort installation. ++set -eu ++ ++fail() { ++ echo "Error: $*" >&2 ++ exit 1 ++} ++ ++warn() { ++ echo "Warning: $*" >&2 ++} ++ ++require_value() { ++ [ "$#" -ge 2 ] && [ -n "$2" ] || fail "Option $1 requires a value." ++} ++ ++validate_platform() { ++ case "$(uname -s)" in ++ Linux) ++ if is_alpine; then ++ command -v rc-service >/dev/null && command -v rc-update >/dev/null || fail "OpenRC is required." ++ elif is_openwrt; then ++ [ -f /etc/rc.common ] || fail "OpenWrt procd is required." ++ else ++ command -v systemctl >/dev/null && [ -d /run/systemd/system ] || fail "This Linux installer requires a running systemd, OpenRC (Alpine), or procd (OpenWrt)." ++ fi ++ ;; ++ FreeBSD) ++ command -v service >/dev/null && command -v sysrc >/dev/null || fail "FreeBSD service and sysrc commands are required." ++ ;; ++ Darwin) fail "For macOS, use the Homebrew installer: https://github.com/henrygd/beszel/blob/main/supplemental/scripts/install-agent-brew.sh" ;; ++ *) fail "Unsupported operating system: $(uname -s)" ;; ++ esac ++} ++ ++agent_service() { ++ if is_alpine; then ++ rc-service beszel-agent "$1" ++ elif is_openwrt; then ++ /etc/init.d/beszel-agent "$1" ++ elif is_freebsd; then ++ service beszel-agent "$1" ++ else ++ systemctl "$1" beszel-agent.service ++ fi ++} ++ ++# Match the files preserved by the service setup below. A binary or rc script ++# alone is not reusable configuration (FreeBSD stores its environment separately). ++agent_configuration_exists() { ++ if is_alpine || is_openwrt; then ++ [ -f /etc/init.d/beszel-agent ] ++ elif is_freebsd; then ++ [ -f "$AGENT_DIR/env" ] ++ else ++ [ -f /etc/systemd/system/beszel-agent.service ] ++ fi ++} ++ ++# An orphaned binary can remain after a failed install. It does not imply ++# that the service manager knows about the agent yet. ++agent_service_registered() { ++ if is_alpine || is_openwrt; then ++ [ -f /etc/init.d/beszel-agent ] ++ elif is_freebsd; then ++ [ -f /usr/local/etc/rc.d/beszel-agent ] ++ else ++ service_load_state=$(systemctl show --property=LoadState --value beszel-agent.service) || return 2 ++ case "$service_load_state" in ++ not-found) return 1 ;; ++ "") return 2 ;; ++ *) return 0 ;; ++ esac ++ fi ++} ++ ++TEMP_DIR="" ++STAGED_BINARY="" ++INSTALL_STEP="validating installation options" ++UPGRADE_PENDING=false ++cleanup() { ++ cleanup_status=$? ++ trap - 0 HUP INT TERM ++ if [ "$cleanup_status" -ne 0 ]; then ++ warn "Installer failed while $INSTALL_STEP (exit $cleanup_status)." ++ if [ "$UPGRADE_PENDING" = true ]; then ++ warn "Restoring the previous binary and restarting its service if registered." ++ if [ -n "$STAGED_BINARY" ]; then ++ rm -f "$STAGED_BINARY" || warn "Could not remove staged binary." ++ fi ++ if STAGED_BINARY=$(mktemp "$BIN_PATH.XXXXXX") && cp -p "$BIN_PATH.bak" "$STAGED_BINARY" && mv -f "$STAGED_BINARY" "$BIN_PATH"; then ++ # The temporary inode does not inherit the installed binary's SELinux label. ++ set_selinux_context || warn "Could not restore SELinux context on the previous agent." ++ if agent_service_registered; then ++ agent_service restart || warn "Could not restart the previous agent; check the service configuration and logs." ++ else ++ service_check_status=$? ++ [ "$service_check_status" -eq 1 ] || warn "Could not determine whether the previous agent service is registered; check it manually." ++ fi ++ else ++ warn "Could not restore $BIN_PATH.bak. Restore it manually before restarting the service." ++ fi ++ fi ++ fi ++ if [ -n "$STAGED_BINARY" ]; then ++ rm -f "$STAGED_BINARY" || warn "Could not remove staged binary." ++ fi ++ if [ -n "$TEMP_DIR" ]; then ++ rm -rf "$TEMP_DIR" || warn "Could not remove temporary directory $TEMP_DIR." ++ fi ++ exit "$cleanup_status" ++} ++trap cleanup 0 ++trap 'exit 129' HUP ++trap 'exit 130' INT ++trap 'exit 143' TERM ++ ++# A missing crontab is normal. Keep the producer alive so the new job is written. ++read_root_crontab() { ++ crontab -u root -l 2>/dev/null || true ++} ++ ++prompt_auto_update() { ++ printf "\nEnable automatic daily updates for beszel-agent? (y/n): " ++ if ! read -r AUTO_UPDATE; then ++ AUTO_UPDATE=n ++ echo "Skipping automatic updates (no input)." ++ fi ++} ++ + # Default values + PORT=45876 + UNINSTALL=false +@@ -304,7 +434,7 @@ HUB_URL_PROVIDED=false + VERSION="latest" + + # Check for help flag +-case "$1" in ++case "${1-}" in + -h | --help) + printf "Beszel Agent installation script\n\n" + printf "Usage: ./install-agent.sh [options]\n\n" +@@ -324,6 +454,9 @@ case "$1" in + ;; + esac + ++# Reject unsupported hosts before sudo or any system changes. ++validate_platform ++ + # Build sudo args by properly quoting everything + build_sudo_args() { + QUOTED_ARGS="" +@@ -354,26 +487,31 @@ fi + while [ $# -gt 0 ]; do + case "$1" in + -k) ++ require_value "$@" + shift + KEY="$1" + KEY_PROVIDED=true + ;; + -p) ++ require_value "$@" + shift + PORT="$1" + PORT_PROVIDED=true + ;; + -t) ++ require_value "$@" + shift + TOKEN="$1" + TOKEN_PROVIDED=true + ;; + -url) ++ require_value "$@" + shift + HUB_URL="$1" + HUB_URL_PROVIDED=true + ;; + -v | --version) ++ require_value "$@" + shift + VERSION="$1" + ;; +@@ -392,7 +530,7 @@ while [ $# -gt 0 ]; do + GITHUB_PROXY_URL="https://gh.beszel.dev" + GITHUB_URL="$GITHUB_PROXY_URL" + fi +- elif [ "$2" != "" ] && ! echo "$2" | grep -q '^-'; then ++ elif [ "${2-}" != "" ] && ! echo "$2" | grep -q '^-'; then + # use custom proxy URL provided as next argument + GITHUB_PROXY_URL="$2" + GITHUB_URL="$(ensure_trailing_slash "$2")https://github.com" +@@ -415,7 +553,7 @@ while [ $# -gt 0 ]; do + else + echo "Invalid value for --auto-update flag: $AUTO_UPDATE_VALUE. Using default (prompt)." + fi +- elif [ "$2" = "true" ] || [ "$2" = "false" ]; then ++ elif [ "${2-}" = "true" ] || [ "${2-}" = "false" ]; then + # Value provided as next argument + AUTO_UPDATE_FLAG="$2" + shift +@@ -443,20 +581,7 @@ else + BIN_PATH="/opt/beszel-agent/beszel-agent" + fi + +-# Stop existing service if it exists (for upgrades) +-if [ "$UNINSTALL" != true ] && [ -f "$BIN_PATH" ]; then +- echo "Existing installation detected. Stopping service for upgrade..." +- if is_alpine; then +- rc-service beszel-agent stop 2>/dev/null || true +- elif is_openwrt; then +- /etc/init.d/beszel-agent stop 2>/dev/null || true +- elif is_freebsd; then +- service beszel-agent stop 2>/dev/null || true +- else +- systemctl stop beszel-agent.service 2>/dev/null || true +- fi +-fi +- ++INSTALL_STEP="uninstalling the agent" + # Uninstall process + if [ "$UNINSTALL" = true ]; then + # Clean up SELinux contexts before removing files +@@ -464,8 +589,8 @@ if [ "$UNINSTALL" = true ]; then + + if is_alpine; then + echo "Stopping and disabling the agent service..." +- rc-service beszel-agent stop +- rc-update del beszel-agent default ++ rc-service beszel-agent stop || warn "Cleanup command failed: rc-service beszel-agent stop" ++ rc-update del beszel-agent default || warn "Cleanup command failed: rc-update del beszel-agent default" + + echo "Removing the OpenRC service files..." + rm -f /etc/init.d/beszel-agent +@@ -481,8 +606,8 @@ if [ "$UNINSTALL" = true ]; then + rm -f /var/log/beszel-agent.log /var/log/beszel-agent.err + elif is_openwrt; then + echo "Stopping and disabling the agent service..." +- /etc/init.d/beszel-agent stop +- /etc/init.d/beszel-agent disable ++ /etc/init.d/beszel-agent stop || warn "Cleanup command failed: /etc/init.d/beszel-agent stop" ++ /etc/init.d/beszel-agent disable || warn "Cleanup command failed: /etc/init.d/beszel-agent disable" + + echo "Removing the OpenWRT service files..." + rm -f /etc/init.d/beszel-agent +@@ -498,7 +623,7 @@ if [ "$UNINSTALL" = true ]; then + + elif is_freebsd; then + echo "Stopping and disabling the agent service..." +- service beszel-agent stop ++ service beszel-agent stop || warn "Cleanup command failed: service beszel-agent stop" + sysrc beszel_agent_enable="NO" + + echo "Removing the FreeBSD service files..." +@@ -525,16 +650,16 @@ if [ "$UNINSTALL" = true ]; then + + else + echo "Stopping and disabling the agent service..." +- systemctl stop beszel-agent.service +- systemctl disable beszel-agent.service >/dev/null 2>&1 ++ systemctl stop beszel-agent.service || warn "Cleanup command failed: systemctl stop beszel-agent.service" ++ systemctl disable beszel-agent.service >/dev/null 2>&1 || warn "Cleanup command failed: systemctl disable beszel-agent.service" + + echo "Removing the systemd service file..." +- rm /etc/systemd/system/beszel-agent.service ++ rm -f /etc/systemd/system/beszel-agent.service + + # Remove the update timer and service if they exist + echo "Removing the daily update service and timer..." +- systemctl stop beszel-agent-update.timer 2>/dev/null +- systemctl disable beszel-agent-update.timer >/dev/null 2>&1 ++ systemctl stop beszel-agent-update.timer 2>/dev/null || warn "Cleanup command failed: systemctl stop beszel-agent-update.timer" ++ systemctl disable beszel-agent-update.timer >/dev/null 2>&1 || warn "Cleanup command failed: systemctl disable beszel-agent-update.timer" + rm -f /etc/systemd/system/beszel-agent-update.service + rm -f /etc/systemd/system/beszel-agent-update.timer + +@@ -545,13 +670,15 @@ if [ "$UNINSTALL" = true ]; then + rm -rf "$AGENT_DIR" + + echo "Removing the dedicated user for the agent service..." +- killall beszel-agent 2>/dev/null +- if is_alpine || is_openwrt; then +- deluser beszel 2>/dev/null +- elif is_freebsd; then +- pw user del beszel 2>/dev/null +- else +- userdel beszel 2>/dev/null ++ killall beszel-agent 2>/dev/null || true # Usually already stopped by the service manager. ++ if id -u beszel >/dev/null 2>&1; then ++ if is_alpine || is_openwrt; then ++ deluser beszel || fail "Could not remove the beszel user." ++ elif is_freebsd; then ++ pw user del beszel || fail "Could not remove the beszel user." ++ else ++ userdel beszel || fail "Could not remove the beszel user." ++ fi + fi + + echo "Beszel Agent has been uninstalled successfully!" +@@ -563,6 +690,7 @@ package_installed() { + command -v "$1" >/dev/null 2>&1 + } + ++INSTALL_STEP="installing required packages" + # Check for package manager and install necessary packages if not installed + if package_installed apk; then + if ! package_installed tar || ! package_installed curl || ! package_installed sha256sum; then +@@ -596,13 +724,18 @@ else + echo "Warning: Please ensure 'tar' and 'curl' and 'sha256sum (coreutils)' are installed." + fi + +-# If no SSH key is provided, ask for the SSH key interactively (skip if upgrading) ++for required_command in tar curl; do ++ command -v "$required_command" >/dev/null || fail "Required command is missing: $required_command" ++done ++ ++# If no SSH key is provided, prompt unless service setup will reuse configuration. + if [ -z "$KEY" ]; then +- if [ -f "$BIN_PATH" ]; then +- echo "Upgrading existing installation. Using existing service configuration." ++ if agent_configuration_exists; then ++ echo "Using existing service configuration." + else + printf "Enter your SSH key: " +- read KEY ++ read -r KEY || fail "No SSH key received. Supply -k for noninteractive installation." ++ [ -n "$KEY" ] || fail "SSH key must not be empty." + fi + fi + +@@ -623,6 +756,7 @@ else + exit 1 + fi + ++INSTALL_STEP="configuring the service user" + # Create a dedicated user for the service if it doesn't exist + AGENT_USER="beszel" + echo "Configuring the dedicated user for the Beszel Agent service..." +@@ -696,6 +830,7 @@ else + fi + fi + ++INSTALL_STEP="creating installation directories" + # Create the directory for the Beszel Agent + + if [ ! -d "$AGENT_DIR" ]; then +@@ -709,6 +844,7 @@ if [ ! -d "$BIN_DIR" ]; then + mkdir -p "$BIN_DIR" + fi + ++INSTALL_STEP="downloading and verifying the agent" + # Download and install the Beszel Agent + + OS=$(uname -s | sed -e 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/') +@@ -720,11 +856,12 @@ fi + + # Determine version to install + if [ "$VERSION" = "latest" ]; then +- INSTALL_VERSION=$(curl -s "https://get.beszel.dev/latest-version") ++ INSTALL_VERSION=$(curl -fsS --connect-timeout 10 --max-time 30 "https://get.beszel.dev/latest-version") || INSTALL_VERSION="" + if [ -z "$INSTALL_VERSION" ]; then + # Fallback to GitHub API + API_RELEASE_URL="https://api.github.com/repos/henrygd/beszel/releases/latest" +- INSTALL_VERSION=$(curl -s "$API_RELEASE_URL" | grep -o '"tag_name": "v[^"]*"' | cut -d'"' -f4 | tr -d 'v') ++ RELEASE_JSON=$(curl -fsS --connect-timeout 10 --max-time 30 "$API_RELEASE_URL") || fail "Could not fetch the latest release from GitHub." ++ INSTALL_VERSION=$(printf '%s\n' "$RELEASE_JSON" | grep -o '"tag_name": "v[^"]*"' | cut -d'"' -f4 | tr -d 'v') + fi + if [ -z "$INSTALL_VERSION" ]; then + echo "Failed to get latest version" +@@ -741,7 +878,8 @@ echo "Downloading beszel-agent v${INSTALL_VERSION}..." + # Download checksums file + TEMP_DIR=$(mktemp -d) + cd "$TEMP_DIR" || exit 1 +-CHECKSUM=$(curl -fsSL "$GITHUB_URL/henrygd/beszel/releases/download/v${INSTALL_VERSION}/beszel_${INSTALL_VERSION}_checksums.txt" | grep "$FILE_NAME" | cut -d' ' -f1) ++curl -fsSL --connect-timeout 10 --max-time 60 "$GITHUB_URL/henrygd/beszel/releases/download/v${INSTALL_VERSION}/beszel_${INSTALL_VERSION}_checksums.txt" -o checksums.txt || fail "Could not download checksums. Try --mirror if GitHub is unreachable." ++CHECKSUM=$(awk -v name="$FILE_NAME" '$2 == name { print $1 }' checksums.txt) + if [ -z "$CHECKSUM" ] || ! echo "$CHECKSUM" | grep -qE "^[a-fA-F0-9]{64}$"; then + echo "Failed to get checksum or invalid checksum format" + echo "Try again with --mirror (or --mirror ) if GitHub is not reachable." +@@ -763,10 +901,10 @@ if ! tar -tzf "$FILE_NAME" >/dev/null 2>&1; then + exit 1 + fi + +-if [ "$($CHECK_CMD "$FILE_NAME" | cut -d' ' -f1)" != "$CHECKSUM" ]; then +- echo "Checksum verification failed: $($CHECK_CMD "$FILE_NAME" | cut -d' ' -f1) & $CHECKSUM" +- rm -rf "$TEMP_DIR" +- exit 1 ++ACTUAL_CHECKSUM=$($CHECK_CMD "$FILE_NAME") || fail "Could not calculate archive checksum." ++ACTUAL_CHECKSUM=${ACTUAL_CHECKSUM%% *} ++if [ "$ACTUAL_CHECKSUM" != "$CHECKSUM" ]; then ++ fail "Checksum verification failed: $ACTUAL_CHECKSUM != $CHECKSUM" + fi + + if ! tar -xzf "$FILE_NAME" beszel-agent; then +@@ -781,20 +919,34 @@ if [ ! -s "$TEMP_DIR/beszel-agent" ]; then + exit 1 + fi + ++INSTALL_STEP="replacing the agent binary" ++# Stage on the destination filesystem so replacement and rollback use atomic renames. ++STAGED_BINARY=$(mktemp "$BIN_PATH.XXXXXX") || fail "Could not create a staged binary." ++cp beszel-agent "$STAGED_BINARY" || fail "Could not stage the agent binary." ++chown "${AGENT_USER}:${AGENT_USER}" "$STAGED_BINARY" || fail "Could not set binary ownership." ++chmod 755 "$STAGED_BINARY" || fail "Could not set binary permissions." ++ + if [ -f "$BIN_PATH" ]; then + echo "Backing up existing binary..." +- cp "$BIN_PATH" "$BIN_PATH.bak" ++ cp -p "$BIN_PATH" "$BIN_PATH.bak" || fail "Could not back up the existing binary." ++ UPGRADE_PENDING=true ++ if agent_service_registered; then ++ agent_service stop || fail "Could not stop the existing agent." ++ else ++ service_check_status=$? ++ [ "$service_check_status" -eq 1 ] || fail "Could not determine whether the existing agent service is registered." ++ fi + fi + +-mv beszel-agent "$BIN_PATH" +-chown "${AGENT_USER}:${AGENT_USER}" "$BIN_PATH" +-chmod 755 "$BIN_PATH" ++mv -f "$STAGED_BINARY" "$BIN_PATH" || fail "Could not install the agent binary." ++STAGED_BINARY="" + + # Set SELinux context if needed + set_selinux_context + + # Cleanup + rm -rf "$TEMP_DIR" ++TEMP_DIR="" + + # Make sure /etc/machine-id exists and is non-empty for persistent fingerprint + if [ ! -s /etc/machine-id ]; then +@@ -819,6 +971,7 @@ detect_nvidia_devices() { + echo "$devices" + } + ++INSTALL_STEP="configuring and starting the service" + # Modify service installation part, add Alpine check before systemd service creation + if is_alpine; then + if [ ! -f /etc/init.d/beszel-agent ]; then +@@ -868,7 +1021,7 @@ EOF + chown "${AGENT_USER}:${AGENT_USER}" /var/log/beszel-agent.log /var/log/beszel-agent.err + + # Start the service +- rc-service beszel-agent restart ++ rc-service beszel-agent restart || fail "Could not start the agent; check service logs." + + # Check if service started successfully + sleep 2 +@@ -884,8 +1037,7 @@ EOF + elif [ "$AUTO_UPDATE_FLAG" = "false" ]; then + AUTO_UPDATE="n" + else +- printf "\nEnable automatic daily updates for beszel-agent? (y/n): " +- read AUTO_UPDATE ++ prompt_auto_update + fi + case "$AUTO_UPDATE" in + [Yy]*) +@@ -893,7 +1045,7 @@ EOF + + # Create cron job to run beszel-agent update command daily at midnight + if ! crontab -u root -l 2>/dev/null | grep -q "beszel-agent.*update"; then +- (crontab -u root -l 2>/dev/null; echo "12 0 * * * $BIN_PATH update >/dev/null 2>&1") | crontab -u root - ++ (read_root_crontab; echo "12 0 * * * $BIN_PATH update >/dev/null 2>&1") | crontab -u root - + fi + + printf "\nDaily updates have been enabled via cron job.\n" +@@ -963,7 +1115,7 @@ EOF + fi + + # Start the service +- /etc/init.d/beszel-agent restart ++ /etc/init.d/beszel-agent restart || fail "Could not start the agent; check service logs." + + # Auto-update service for OpenWRT using a crontab job + if [ "$AUTO_UPDATE_FLAG" = "true" ]; then +@@ -973,15 +1125,14 @@ EOF + AUTO_UPDATE="n" + sleep 1 # give time for the service to start + else +- printf "\nEnable automatic daily updates for beszel-agent? (y/n): " +- read AUTO_UPDATE ++ prompt_auto_update + fi + case "$AUTO_UPDATE" in + [Yy]*) + echo "Setting up daily automatic updates for beszel-agent..." + + if ! crontab -u root -l 2>/dev/null | grep -q "beszel-agent.*update"; then +- (crontab -u root -l 2>/dev/null; echo "12 0 * * * /etc/init.d/beszel-agent update") | crontab -u root - ++ (read_root_crontab; echo "12 0 * * * /etc/init.d/beszel-agent update") | crontab -u root - + fi + + /etc/init.d/cron restart +@@ -1072,7 +1223,7 @@ EOF + esac + fi + +- service beszel-agent restart ++ service beszel-agent restart || fail "Could not start the agent; check service logs." + + # Check if service started successfully + sleep 2 +@@ -1088,8 +1239,7 @@ EOF + elif [ "$AUTO_UPDATE_FLAG" = "false" ]; then + AUTO_UPDATE="n" + else +- printf "\nEnable automatic daily updates for beszel-agent? (y/n): " +- read AUTO_UPDATE ++ prompt_auto_update + fi + case "$AUTO_UPDATE" in + [Yy]*) +@@ -1170,7 +1320,7 @@ EOF + printf "\nLoading and starting the agent service...\n" + systemctl daemon-reload + systemctl enable beszel-agent.service >/dev/null 2>&1 +- systemctl restart beszel-agent.service ++ systemctl restart beszel-agent.service || fail "Could not start the agent; check service logs." + + + +@@ -1182,8 +1332,7 @@ EOF + AUTO_UPDATE="n" + sleep 1 # give time for the service to start + else +- printf "\nEnable automatic daily updates for beszel-agent? (y/n): " +- read AUTO_UPDATE ++ prompt_auto_update + fi + case "$AUTO_UPDATE" in + [Yy]*) +@@ -1229,6 +1378,7 @@ EOF + fi + fi + ++UPGRADE_PENDING=false + RUNNING_ADDRESS=$(configured_address) + [ -n "$RUNNING_ADDRESS" ] || RUNNING_ADDRESS=$PORT + diff --git a/tasks/henrygd__beszel-2304/tests/test.sh b/tasks/henrygd__beszel-2304/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d6be1a89c574b99fd94339c386a3cbfa4a0aae87 --- /dev/null +++ b/tasks/henrygd__beszel-2304/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 c157c2026d0348aabcfb37c3e9cfafba2b0f8b26 > "$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/henrygd__beszel-2304/tests/verifier.py b/tasks/henrygd__beszel-2304/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2304/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/henrygd__beszel-2310/environment/Dockerfile b/tasks/henrygd__beszel-2310/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb9800b9b152d42d53901199a73fc19896e9fe88 --- /dev/null +++ b/tasks/henrygd__beszel-2310/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6cb302fcf6eb489d299707c0ca1fd796a2cfe5de 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6cb302fcf6eb489d299707c0ca1fd796a2cfe5de \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6cb302fcf6eb489d299707c0ca1fd796a2cfe5de \ + && 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/henrygd__beszel-2310/instruction.md b/tasks/henrygd__beszel-2310/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c72f32647395c222fed9eb864ecc717c1da682b4 --- /dev/null +++ b/tasks/henrygd__beszel-2310/instruction.md @@ -0,0 +1,53 @@ +# Issue + +**Title:** fix(site): redirect to login when JWT expires + +## Description + +## Description + +This PR fixes the silent half-broken dashboard state when the PocketBase JWT expires while the hub is open. + +### Problem + +`$authenticated` in `src/lib/stores.ts` is initialized once from `pb.authStore.isValid` and only updated on explicit `authStore.onChange` events. PocketBase's `onChange` does not fire when a JWT's `exp` claim passes, so the dashboard keeps rendering, the 1m realtime chart keeps streaming, and all other REST requests start returning 401 without a visible redirect to login. + +### Triage + +The auth store still reports `isValid: false` once the token expires, but `App` only listens to `onChange`. Because natural JWT expiration does not trigger `onChange`, `$authenticated` stays `true` and `Layout` keeps showing the dashboard. + +### Fix + +In `src/main.tsx`, following @henrygd's : + +1. Register a `pb.afterSend` hook that runs a debounced `verifyAuth()` (100 ms, via the existing `debounce` util) whenever any API response returns 4xx while a token is set. The `auth-refresh` URL is excluded so `verifyAuth()`'s own failing refresh (which returns 401 when the token is no longer valid) can't loop. +2. `verifyAuth()` then calls `logOut()` on the failed refresh, which clears the auth store, fires `onChange`, and updates `$authenticated` so `Layout` renders `LoginPage` with a "Failed to authenticate" toast. + +Also removed per the same review: the empty-records `verifyAuth()` heuristic in `systemsManager.refresh()` — the hook now catches the actual 401 from the systems fetch instead of inferring auth trouble from an empty list. + +### Verification + +- `bunx biome check src/main.tsx src/lib/systemsManager.ts` — clean +- `bunx tsc --noEmit` — clean +- `bun run build` inside `internal/site` — production build succeeds +- Loop-guard check against the installed `pocketbase` ^0.26.2 source: `afterSend` fires for every `send()` response (including 4xx, before the `ClientResponseError` throw) and its return value is used as the response data, so the hook returns `data` unchanged. + +## Documentation + +No documentation changes needed. + +## Changelog + +### Fixed + +- Redirect to the login page when the JWT expires. + +## Screenshots + +No UI/UX changes to screenshot; the only visible behavior is the redirect to the login page on expiry. + +AI-assisted. I wrote and verified this change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6cb302fcf6eb`. 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/henrygd__beszel-2310/solution/patch.diff b/tasks/henrygd__beszel-2310/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..dd35728ad953e17b6e193de9ed2f8ae0034ef474 --- /dev/null +++ b/tasks/henrygd__beszel-2310/solution/patch.diff @@ -0,0 +1,69 @@ +diff --git a/internal/site/src/lib/api.ts b/internal/site/src/lib/api.ts +index 79f4b127..55245b4e 100644 +--- a/internal/site/src/lib/api.ts ++++ b/internal/site/src/lib/api.ts +@@ -4,7 +4,7 @@ import { basePath } from "@/components/router" + import { toast } from "@/components/ui/use-toast" + import type { ChartTimes, UserSettings } from "@/types" + import { $alerts, $allSystemsById, $allSystemsByName, $userSettings } from "./stores" +-import { chartTimeData } from "./utils" ++import { chartTimeData, debounce } from "./utils" + + /** PocketBase JS Client */ + export const pb = new PocketBase(basePath) +@@ -12,7 +12,7 @@ export const pb = new PocketBase(basePath) + export const isAdmin = () => pb.authStore.record?.role === "admin" + export const isReadOnlyUser = () => pb.authStore.record?.role === "readonly" + +-export const verifyAuth = () => { ++const verifyAuth = () => { + pb.collection("users") + .authRefresh() + .catch(() => { +@@ -25,6 +25,22 @@ export const verifyAuth = () => { + }) + } + ++const verifyAuthDebounced = debounce(verifyAuth, 100) ++ ++// verify the session whenever any API request returns a 4xx response (e.g. an ++// expired JWT). The auth-refresh endpoint is excluded to avoid a loop, since ++// it returns 401 itself when the token is no longer valid. ++pb.afterSend = (response, data) => { ++ if ( ++ (response.status === 401 || response.status === 403) && ++ pb.authStore.token && ++ !response.url.includes("auth-refresh") ++ ) { ++ verifyAuthDebounced() ++ } ++ return data ++} ++ + /** Logs the user out by clearing the auth store and unsubscribing from realtime updates. */ + export function logOut() { + $allSystemsByName.set({}) +diff --git a/internal/site/src/lib/systemsManager.ts b/internal/site/src/lib/systemsManager.ts +index 2ee58602..f3c87fbf 100644 +--- a/internal/site/src/lib/systemsManager.ts ++++ b/internal/site/src/lib/systemsManager.ts +@@ -1,6 +1,6 @@ + /** biome-ignore-all lint/suspicious/noAssignInExpressions: it's fine :) */ + import type { PreinitializedMapStore } from "nanostores" +-import { pb, verifyAuth } from "@/lib/api" ++import { pb } from "@/lib/api" + import { + $allSystemsById, + $allSystemsByName, +@@ -167,11 +167,6 @@ export async function subscribe() { + export async function refresh() { + try { + const records = await fetchSystems() +- if (!records.length) { +- // No systems found, verify authentication +- verifyAuth() +- return +- } + for (const record of records) { + add(record) + } diff --git a/tasks/henrygd__beszel-2310/solution/solve.sh b/tasks/henrygd__beszel-2310/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2310/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/henrygd__beszel-2310/task.toml b/tasks/henrygd__beszel-2310/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..308b6ec555317143e23f08896b0f7a3cf4e432d5 --- /dev/null +++ b/tasks/henrygd__beszel-2310/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2310" +description = "fix(site): redirect to login when JWT expires" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "6cb302fcf6eb489d299707c0ca1fd796a2cfe5de" +reference = "https://github.com/henrygd/beszel/pull/2310" +source_access = "auto" +built_at = "2026-11-16T16:09:53.504890+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:23b6566d8858b0d16baf74aaf01a752b090af67d92082c997fcfec719d488d97" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-08T12:21:00Z" +diff_format = "unified" +context_files = [ + "internal/site/src/lib/api.ts", + "internal/site/src/lib/systemsManager.ts", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 27 +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:00.811723+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6f338c8314bc22d05d6fdfd82f1e5f73ff3a7a05b1c56e847453c05c9ffc93b4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2310/tests/capture.py b/tasks/henrygd__beszel-2310/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2310/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/henrygd__beszel-2310/tests/instruction.md b/tasks/henrygd__beszel-2310/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c72f32647395c222fed9eb864ecc717c1da682b4 --- /dev/null +++ b/tasks/henrygd__beszel-2310/tests/instruction.md @@ -0,0 +1,53 @@ +# Issue + +**Title:** fix(site): redirect to login when JWT expires + +## Description + +## Description + +This PR fixes the silent half-broken dashboard state when the PocketBase JWT expires while the hub is open. + +### Problem + +`$authenticated` in `src/lib/stores.ts` is initialized once from `pb.authStore.isValid` and only updated on explicit `authStore.onChange` events. PocketBase's `onChange` does not fire when a JWT's `exp` claim passes, so the dashboard keeps rendering, the 1m realtime chart keeps streaming, and all other REST requests start returning 401 without a visible redirect to login. + +### Triage + +The auth store still reports `isValid: false` once the token expires, but `App` only listens to `onChange`. Because natural JWT expiration does not trigger `onChange`, `$authenticated` stays `true` and `Layout` keeps showing the dashboard. + +### Fix + +In `src/main.tsx`, following @henrygd's : + +1. Register a `pb.afterSend` hook that runs a debounced `verifyAuth()` (100 ms, via the existing `debounce` util) whenever any API response returns 4xx while a token is set. The `auth-refresh` URL is excluded so `verifyAuth()`'s own failing refresh (which returns 401 when the token is no longer valid) can't loop. +2. `verifyAuth()` then calls `logOut()` on the failed refresh, which clears the auth store, fires `onChange`, and updates `$authenticated` so `Layout` renders `LoginPage` with a "Failed to authenticate" toast. + +Also removed per the same review: the empty-records `verifyAuth()` heuristic in `systemsManager.refresh()` — the hook now catches the actual 401 from the systems fetch instead of inferring auth trouble from an empty list. + +### Verification + +- `bunx biome check src/main.tsx src/lib/systemsManager.ts` — clean +- `bunx tsc --noEmit` — clean +- `bun run build` inside `internal/site` — production build succeeds +- Loop-guard check against the installed `pocketbase` ^0.26.2 source: `afterSend` fires for every `send()` response (including 4xx, before the `ClientResponseError` throw) and its return value is used as the response data, so the hook returns `data` unchanged. + +## Documentation + +No documentation changes needed. + +## Changelog + +### Fixed + +- Redirect to the login page when the JWT expires. + +## Screenshots + +No UI/UX changes to screenshot; the only visible behavior is the redirect to the login page on expiry. + +AI-assisted. I wrote and verified this change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6cb302fcf6eb`. 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/henrygd__beszel-2310/tests/oracle.patch b/tasks/henrygd__beszel-2310/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..dd35728ad953e17b6e193de9ed2f8ae0034ef474 --- /dev/null +++ b/tasks/henrygd__beszel-2310/tests/oracle.patch @@ -0,0 +1,69 @@ +diff --git a/internal/site/src/lib/api.ts b/internal/site/src/lib/api.ts +index 79f4b127..55245b4e 100644 +--- a/internal/site/src/lib/api.ts ++++ b/internal/site/src/lib/api.ts +@@ -4,7 +4,7 @@ import { basePath } from "@/components/router" + import { toast } from "@/components/ui/use-toast" + import type { ChartTimes, UserSettings } from "@/types" + import { $alerts, $allSystemsById, $allSystemsByName, $userSettings } from "./stores" +-import { chartTimeData } from "./utils" ++import { chartTimeData, debounce } from "./utils" + + /** PocketBase JS Client */ + export const pb = new PocketBase(basePath) +@@ -12,7 +12,7 @@ export const pb = new PocketBase(basePath) + export const isAdmin = () => pb.authStore.record?.role === "admin" + export const isReadOnlyUser = () => pb.authStore.record?.role === "readonly" + +-export const verifyAuth = () => { ++const verifyAuth = () => { + pb.collection("users") + .authRefresh() + .catch(() => { +@@ -25,6 +25,22 @@ export const verifyAuth = () => { + }) + } + ++const verifyAuthDebounced = debounce(verifyAuth, 100) ++ ++// verify the session whenever any API request returns a 4xx response (e.g. an ++// expired JWT). The auth-refresh endpoint is excluded to avoid a loop, since ++// it returns 401 itself when the token is no longer valid. ++pb.afterSend = (response, data) => { ++ if ( ++ (response.status === 401 || response.status === 403) && ++ pb.authStore.token && ++ !response.url.includes("auth-refresh") ++ ) { ++ verifyAuthDebounced() ++ } ++ return data ++} ++ + /** Logs the user out by clearing the auth store and unsubscribing from realtime updates. */ + export function logOut() { + $allSystemsByName.set({}) +diff --git a/internal/site/src/lib/systemsManager.ts b/internal/site/src/lib/systemsManager.ts +index 2ee58602..f3c87fbf 100644 +--- a/internal/site/src/lib/systemsManager.ts ++++ b/internal/site/src/lib/systemsManager.ts +@@ -1,6 +1,6 @@ + /** biome-ignore-all lint/suspicious/noAssignInExpressions: it's fine :) */ + import type { PreinitializedMapStore } from "nanostores" +-import { pb, verifyAuth } from "@/lib/api" ++import { pb } from "@/lib/api" + import { + $allSystemsById, + $allSystemsByName, +@@ -167,11 +167,6 @@ export async function subscribe() { + export async function refresh() { + try { + const records = await fetchSystems() +- if (!records.length) { +- // No systems found, verify authentication +- verifyAuth() +- return +- } + for (const record of records) { + add(record) + } diff --git a/tasks/henrygd__beszel-2310/tests/test.sh b/tasks/henrygd__beszel-2310/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c32b03fb099ffcc1da4cfb502cdf9035fb98d2c6 --- /dev/null +++ b/tasks/henrygd__beszel-2310/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 6cb302fcf6eb489d299707c0ca1fd796a2cfe5de > "$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/henrygd__beszel-2310/tests/verifier.py b/tasks/henrygd__beszel-2310/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2310/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/henrygd__beszel-2311/environment/Dockerfile b/tasks/henrygd__beszel-2311/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb9800b9b152d42d53901199a73fc19896e9fe88 --- /dev/null +++ b/tasks/henrygd__beszel-2311/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6cb302fcf6eb489d299707c0ca1fd796a2cfe5de 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6cb302fcf6eb489d299707c0ca1fd796a2cfe5de \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6cb302fcf6eb489d299707c0ca1fd796a2cfe5de \ + && 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/henrygd__beszel-2311/instruction.md b/tasks/henrygd__beszel-2311/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6eb6d6c32160061d59b0b2f6119dd06ce799bf5e --- /dev/null +++ b/tasks/henrygd__beszel-2311/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** Feat: Adds ZFS utilities to nvidia docker images + +## Description + +## 📃 Description + +Adds ZFS userspace utilities (`zpool`, `zfs`) to the nvidia agent images. Without these binaries, `zpool list`/`zpool status`/`zfs list` can't run, so pool inventory, health, and scrub status are unavailable — only ARC size and pool I/O counters (read from procfs) still work. The alpine and intel agent images already install these via `apk add zfs`; the nvidia images were the odd ones out. + + + +## 🪵 Changelog + +### ➕ Added + +- `zfsutils-linux` installed in `dockerfile_agent_nvidia` (full Ubuntu/CUDA base) via `apt-get install`, matching the `apk add zfs` pattern already used in the alpine and intel images. +- New `zfsutils-builder` stage in `dockerfile_agent_nvidia_slim` that installs `zfsutils-linux` in a Debian builder image and copies `zpool`/`zfs` plus their resolved shared-library dependencies into the distroless final image, following the same builder-stage + `ldd`-copy pattern already used there for `smartmontools`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6cb302fcf6eb`. 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/henrygd__beszel-2311/solution/patch.diff b/tasks/henrygd__beszel-2311/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7304fb3e0f8be567d9a9d7b43e274f20f945a2bf --- /dev/null +++ b/tasks/henrygd__beszel-2311/solution/patch.diff @@ -0,0 +1,63 @@ +diff --git a/internal/dockerfile_agent_nvidia b/internal/dockerfile_agent_nvidia +index 5843bd68..aa5c3ff7 100644 +--- a/internal/dockerfile_agent_nvidia ++++ b/internal/dockerfile_agent_nvidia +@@ -43,6 +43,11 @@ COPY --from=builder /app/agent/test-data/amdgpu.ids /usr/share/libdrm/amdgpu.ids + # Copy smartmontools binaries and config files + COPY --from=smartmontools-builder /usr/sbin/smartctl /usr/sbin/smartctl + ++# Install ZFS userspace utilities (zpool, zfs) for pool/dataset monitoring ++RUN apt-get update && apt-get install -y --no-install-recommends \ ++ zfsutils-linux \ ++ && apt-get clean && rm -rf /var/lib/apt/lists/* ++ + # Ensure data persistence across container recreations + VOLUME ["/var/lib/beszel-agent"] + +diff --git a/internal/dockerfile_agent_nvidia_slim b/internal/dockerfile_agent_nvidia_slim +index 51144a5e..cfb6420b 100644 +--- a/internal/dockerfile_agent_nvidia_slim ++++ b/internal/dockerfile_agent_nvidia_slim +@@ -65,6 +65,32 @@ RUN set -eux; \ + cp -v "$interp" "/out/rootfs$interp"; \ + fi + ++# -------------------------- ++# ZFS utilities builder stage ++# -------------------------- ++FROM --platform=$TARGETPLATFORM debian:bookworm-slim AS zfsutils-builder ++ ++RUN apt-get update && apt-get install -y --no-install-recommends \ ++ zfsutils-linux \ ++ && rm -rf /var/lib/apt/lists/* ++ ++# Copy the zpool/zfs binaries and their required runtime libraries ++RUN set -eux; \ ++ mkdir -p /out/rootfs/lib /out/rootfs/lib64 /out/rootfs/usr/lib; \ ++ for bin in /usr/sbin/zpool /usr/sbin/zfs; do \ ++ mkdir -p "/out/rootfs$(dirname "$bin")"; \ ++ cp -v "$bin" "/out/rootfs$bin"; \ ++ ldd "$bin" \ ++ | awk '{print $3}' \ ++ | grep '^/' \ ++ | xargs -r -I '{}' sh -c 'mkdir -p "/out/rootfs$(dirname "{}")"; cp -v "{}" "/out/rootfs{}"'; \ ++ interp="$(ldd "$bin" | awk "/ld-linux/ {print \$1}")"; \ ++ if [ -n "$interp" ] && [ -e "$interp" ]; then \ ++ mkdir -p "/out/rootfs$(dirname "$interp")"; \ ++ cp -v "$interp" "/out/rootfs$interp"; \ ++ fi; \ ++ done ++ + # -------------------------- + # Final image: lightweight multi-arch NVIDIA agent (slim) + # -------------------------- +@@ -78,6 +104,9 @@ COPY --from=builder /app/agent/test-data/amdgpu.ids /usr/share/libdrm/amdgpu.ids + COPY --from=smartmontools-builder /usr/sbin/smartctl /usr/sbin/smartctl + COPY --from=smartmontools-builder /out/rootfs/ / + ++# Copy ZFS utilities (zpool, zfs) binaries and required runtime libraries ++COPY --from=zfsutils-builder /out/rootfs/ / ++ + # nvidia-smi is intentionally not bundled. + # Mount the host binary instead, for example: + # - /usr/bin/nvidia-smi:/usr/bin/nvidia-smi:ro diff --git a/tasks/henrygd__beszel-2311/solution/solve.sh b/tasks/henrygd__beszel-2311/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2311/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/henrygd__beszel-2311/task.toml b/tasks/henrygd__beszel-2311/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2f0f5b0d9df829aeca95c7b651bec87b0b1a8b56 --- /dev/null +++ b/tasks/henrygd__beszel-2311/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2311" +description = "Feat: Adds ZFS utilities to nvidia docker images" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "6cb302fcf6eb489d299707c0ca1fd796a2cfe5de" +reference = "https://github.com/henrygd/beszel/pull/2311" +source_access = "auto" +built_at = "2026-11-16T16:09:53.506410+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e741420271603e6e39ade05423edaa42dc831953f3ce0a2309f8fcdb4b7a8107" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T15:05:03Z" +diff_format = "unified" +context_files = [ + "internal/dockerfile_agent_nvidia", + "internal/dockerfile_agent_nvidia_slim", +] +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:00.812189+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6f338c8314bc22d05d6fdfd82f1e5f73ff3a7a05b1c56e847453c05c9ffc93b4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2311/tests/capture.py b/tasks/henrygd__beszel-2311/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2311/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/henrygd__beszel-2311/tests/instruction.md b/tasks/henrygd__beszel-2311/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6eb6d6c32160061d59b0b2f6119dd06ce799bf5e --- /dev/null +++ b/tasks/henrygd__beszel-2311/tests/instruction.md @@ -0,0 +1,22 @@ +# Issue + +**Title:** Feat: Adds ZFS utilities to nvidia docker images + +## Description + +## 📃 Description + +Adds ZFS userspace utilities (`zpool`, `zfs`) to the nvidia agent images. Without these binaries, `zpool list`/`zpool status`/`zfs list` can't run, so pool inventory, health, and scrub status are unavailable — only ARC size and pool I/O counters (read from procfs) still work. The alpine and intel agent images already install these via `apk add zfs`; the nvidia images were the odd ones out. + + + +## 🪵 Changelog + +### ➕ Added + +- `zfsutils-linux` installed in `dockerfile_agent_nvidia` (full Ubuntu/CUDA base) via `apt-get install`, matching the `apk add zfs` pattern already used in the alpine and intel images. +- New `zfsutils-builder` stage in `dockerfile_agent_nvidia_slim` that installs `zfsutils-linux` in a Debian builder image and copies `zpool`/`zfs` plus their resolved shared-library dependencies into the distroless final image, following the same builder-stage + `ldd`-copy pattern already used there for `smartmontools`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6cb302fcf6eb`. 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/henrygd__beszel-2311/tests/oracle.patch b/tasks/henrygd__beszel-2311/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7304fb3e0f8be567d9a9d7b43e274f20f945a2bf --- /dev/null +++ b/tasks/henrygd__beszel-2311/tests/oracle.patch @@ -0,0 +1,63 @@ +diff --git a/internal/dockerfile_agent_nvidia b/internal/dockerfile_agent_nvidia +index 5843bd68..aa5c3ff7 100644 +--- a/internal/dockerfile_agent_nvidia ++++ b/internal/dockerfile_agent_nvidia +@@ -43,6 +43,11 @@ COPY --from=builder /app/agent/test-data/amdgpu.ids /usr/share/libdrm/amdgpu.ids + # Copy smartmontools binaries and config files + COPY --from=smartmontools-builder /usr/sbin/smartctl /usr/sbin/smartctl + ++# Install ZFS userspace utilities (zpool, zfs) for pool/dataset monitoring ++RUN apt-get update && apt-get install -y --no-install-recommends \ ++ zfsutils-linux \ ++ && apt-get clean && rm -rf /var/lib/apt/lists/* ++ + # Ensure data persistence across container recreations + VOLUME ["/var/lib/beszel-agent"] + +diff --git a/internal/dockerfile_agent_nvidia_slim b/internal/dockerfile_agent_nvidia_slim +index 51144a5e..cfb6420b 100644 +--- a/internal/dockerfile_agent_nvidia_slim ++++ b/internal/dockerfile_agent_nvidia_slim +@@ -65,6 +65,32 @@ RUN set -eux; \ + cp -v "$interp" "/out/rootfs$interp"; \ + fi + ++# -------------------------- ++# ZFS utilities builder stage ++# -------------------------- ++FROM --platform=$TARGETPLATFORM debian:bookworm-slim AS zfsutils-builder ++ ++RUN apt-get update && apt-get install -y --no-install-recommends \ ++ zfsutils-linux \ ++ && rm -rf /var/lib/apt/lists/* ++ ++# Copy the zpool/zfs binaries and their required runtime libraries ++RUN set -eux; \ ++ mkdir -p /out/rootfs/lib /out/rootfs/lib64 /out/rootfs/usr/lib; \ ++ for bin in /usr/sbin/zpool /usr/sbin/zfs; do \ ++ mkdir -p "/out/rootfs$(dirname "$bin")"; \ ++ cp -v "$bin" "/out/rootfs$bin"; \ ++ ldd "$bin" \ ++ | awk '{print $3}' \ ++ | grep '^/' \ ++ | xargs -r -I '{}' sh -c 'mkdir -p "/out/rootfs$(dirname "{}")"; cp -v "{}" "/out/rootfs{}"'; \ ++ interp="$(ldd "$bin" | awk "/ld-linux/ {print \$1}")"; \ ++ if [ -n "$interp" ] && [ -e "$interp" ]; then \ ++ mkdir -p "/out/rootfs$(dirname "$interp")"; \ ++ cp -v "$interp" "/out/rootfs$interp"; \ ++ fi; \ ++ done ++ + # -------------------------- + # Final image: lightweight multi-arch NVIDIA agent (slim) + # -------------------------- +@@ -78,6 +104,9 @@ COPY --from=builder /app/agent/test-data/amdgpu.ids /usr/share/libdrm/amdgpu.ids + COPY --from=smartmontools-builder /usr/sbin/smartctl /usr/sbin/smartctl + COPY --from=smartmontools-builder /out/rootfs/ / + ++# Copy ZFS utilities (zpool, zfs) binaries and required runtime libraries ++COPY --from=zfsutils-builder /out/rootfs/ / ++ + # nvidia-smi is intentionally not bundled. + # Mount the host binary instead, for example: + # - /usr/bin/nvidia-smi:/usr/bin/nvidia-smi:ro diff --git a/tasks/henrygd__beszel-2311/tests/test.sh b/tasks/henrygd__beszel-2311/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c32b03fb099ffcc1da4cfb502cdf9035fb98d2c6 --- /dev/null +++ b/tasks/henrygd__beszel-2311/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 6cb302fcf6eb489d299707c0ca1fd796a2cfe5de > "$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/henrygd__beszel-2311/tests/verifier.py b/tasks/henrygd__beszel-2311/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2311/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/henrygd__beszel-2316/environment/Dockerfile b/tasks/henrygd__beszel-2316/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0b650cdffbfdd494e787a95334bffd64e83728d8 --- /dev/null +++ b/tasks/henrygd__beszel-2316/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6d82ee70b1f41ceaeaff3d10ab88ae27cd23e781 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6d82ee70b1f41ceaeaff3d10ab88ae27cd23e781 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6d82ee70b1f41ceaeaff3d10ab88ae27cd23e781 \ + && 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/henrygd__beszel-2316/instruction.md b/tasks/henrygd__beszel-2316/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af2c454efce46a97916c20d3e82d4348d77c8aea --- /dev/null +++ b/tasks/henrygd__beszel-2316/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** fix(agent): don't warn about unset HUB_URL in SSH-only mode + +## Description + +An agent with only `KEY` set runs in SSH-only mode, where the hub dials the agent and nothing outbound is expected. `newWebSocketClient` still returns an error in that case because `HUB_URL` isn't set, and `ConnectionManager.Start` logs everything it returns at warn level, so those agents print this on every start: + +``` +WARN Error creating WebSocket client err="HUB_URL environment variable not set" +``` + +Nothing is actually wrong, it's a supported config being reported as a failure. I have eight agents set up this way and the line has been in their logs since the day I installed them. + +This adds an `errNoHubURL` sentinel and logs that one case at debug. A malformed `HUB_URL` or a missing token still warns exactly as before, and the message text doesn't change, so the existing table test still covers it. The same block special-cases `caCertFileError` three lines up, so it follows that shape. + +The only workaround right now is `LOG_LEVEL=error`, which also drops `INFO SSH connected` and `INFO SSH connection established`. Those are the lines you want when you're checking whether the hub is actually reaching an agent, so trading them away to silence this one is a bad deal. + +The test asserts `errors.Is(err, errNoHubURL)`. Putting the old `errors.New` back makes it fail, so it isn't just matching on the message string. + +Ran `gofmt`, `go vet`, and `go test -tags testing ./agent/...` on darwin. The GPU collector tests fail there with or without this change since nvidia-smi and friends aren't installed, and the failure set is identical both ways. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6d82ee70b1f4`. 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/henrygd__beszel-2316/solution/patch.diff b/tasks/henrygd__beszel-2316/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a7b029b08d74d1d4dde782f3e82293c9b55b1496 --- /dev/null +++ b/tasks/henrygd__beszel-2316/solution/patch.diff @@ -0,0 +1,79 @@ +diff --git a/agent/client.go b/agent/client.go +index 9b1351f6..292f6307 100644 +--- a/agent/client.go ++++ b/agent/client.go +@@ -30,6 +30,11 @@ const ( + wsDeadline = 120 * time.Second + ) + ++// errNoHubURL is returned when HUB_URL is unset. This is not a failure ++// condition: an agent configured with only a public key runs in SSH-only mode, ++// where the hub dials the agent and no outbound WebSocket client is expected. ++var errNoHubURL = errors.New("HUB_URL environment variable not set") ++ + type caCertFileError struct { + err error + } +@@ -63,7 +68,7 @@ type WebSocketClient struct { + func newWebSocketClient(agent *Agent) (client *WebSocketClient, err error) { + hubURLStr, exists := utils.GetEnv("HUB_URL") + if !exists { +- return nil, errors.New("HUB_URL environment variable not set") ++ return nil, errNoHubURL + } + + client = &WebSocketClient{} +diff --git a/agent/client_test.go b/agent/client_test.go +index 97cb6654..0478ac7c 100644 +--- a/agent/client_test.go ++++ b/agent/client_test.go +@@ -32,6 +32,28 @@ import ( + "golang.org/x/crypto/ssh" + ) + ++// TestNewWebSocketClientNoHubURL verifies that an unset HUB_URL returns the ++// errNoHubURL sentinel rather than an opaque error. Callers rely on this to ++// distinguish SSH-only mode -- a supported configuration in which the hub dials ++// the agent -- from an actual misconfiguration. ++func TestNewWebSocketClientNoHubURL(t *testing.T) { ++ agent := createTestAgent(t) ++ ++ // t.Setenv registers restoration of the original value; unset afterwards so ++ // GetEnv's LookupEnv reports the variable as absent rather than empty. ++ t.Setenv("BESZEL_AGENT_HUB_URL", "") ++ os.Unsetenv("BESZEL_AGENT_HUB_URL") ++ t.Setenv("HUB_URL", "") ++ os.Unsetenv("HUB_URL") ++ t.Setenv("BESZEL_AGENT_TOKEN", "test-token") ++ ++ client, err := newWebSocketClient(agent) ++ ++ require.Error(t, err) ++ assert.Nil(t, client) ++ assert.ErrorIs(t, err, errNoHubURL) ++} ++ + // TestNewWebSocketClient tests WebSocket client creation + func TestNewWebSocketClient(t *testing.T) { + agent := createTestAgent(t) +diff --git a/agent/connection_manager.go b/agent/connection_manager.go +index d9b16d24..28ea98ae 100644 +--- a/agent/connection_manager.go ++++ b/agent/connection_manager.go +@@ -91,7 +91,15 @@ func (c *ConnectionManager) Start(serverOptions ServerOptions) error { + if errors.As(err, &caCertErr) { + return err + } +- slog.Warn("Error creating WebSocket client", "err", err) ++ disableSSH, _ := utils.GetEnv("DISABLE_SSH") ++ if errors.Is(err, errNoHubURL) && disableSSH != "true" { ++ // SSH-only mode: the hub dials the agent, so there is nothing to warn ++ // about. With SSH also disabled there is no connection method at all, ++ // so that case still warns. ++ slog.Debug("WebSocket client not configured", "err", err) ++ } else { ++ slog.Warn("Error creating WebSocket client", "err", err) ++ } + } + c.wsClient = wsClient + diff --git a/tasks/henrygd__beszel-2316/solution/solve.sh b/tasks/henrygd__beszel-2316/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2316/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/henrygd__beszel-2316/task.toml b/tasks/henrygd__beszel-2316/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..121676cbf6eba6e9c3c708ac1c6fd0636248e9dc --- /dev/null +++ b/tasks/henrygd__beszel-2316/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2316" +description = "fix(agent): don't warn about unset HUB_URL in SSH-only mode" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "6d82ee70b1f41ceaeaff3d10ab88ae27cd23e781" +reference = "https://github.com/henrygd/beszel/pull/2316" +source_access = "auto" +built_at = "2026-11-16T16:09:53.503306+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:080fe190faaa61fc7dbcec2951c981d1c8bece6e2a9328837cd6e900d435f4ef" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T20:58:13Z" +diff_format = "unified" +context_files = [ + "agent/client.go", + "agent/client_test.go", + "agent/connection_manager.go", +] +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:00.812690+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:01fa9cb119d42700f442ddebae4d36f78f117d1c5c41f1d5d5e988c3063aba2c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2316/tests/capture.py b/tasks/henrygd__beszel-2316/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2316/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/henrygd__beszel-2316/tests/instruction.md b/tasks/henrygd__beszel-2316/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af2c454efce46a97916c20d3e82d4348d77c8aea --- /dev/null +++ b/tasks/henrygd__beszel-2316/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** fix(agent): don't warn about unset HUB_URL in SSH-only mode + +## Description + +An agent with only `KEY` set runs in SSH-only mode, where the hub dials the agent and nothing outbound is expected. `newWebSocketClient` still returns an error in that case because `HUB_URL` isn't set, and `ConnectionManager.Start` logs everything it returns at warn level, so those agents print this on every start: + +``` +WARN Error creating WebSocket client err="HUB_URL environment variable not set" +``` + +Nothing is actually wrong, it's a supported config being reported as a failure. I have eight agents set up this way and the line has been in their logs since the day I installed them. + +This adds an `errNoHubURL` sentinel and logs that one case at debug. A malformed `HUB_URL` or a missing token still warns exactly as before, and the message text doesn't change, so the existing table test still covers it. The same block special-cases `caCertFileError` three lines up, so it follows that shape. + +The only workaround right now is `LOG_LEVEL=error`, which also drops `INFO SSH connected` and `INFO SSH connection established`. Those are the lines you want when you're checking whether the hub is actually reaching an agent, so trading them away to silence this one is a bad deal. + +The test asserts `errors.Is(err, errNoHubURL)`. Putting the old `errors.New` back makes it fail, so it isn't just matching on the message string. + +Ran `gofmt`, `go vet`, and `go test -tags testing ./agent/...` on darwin. The GPU collector tests fail there with or without this change since nvidia-smi and friends aren't installed, and the failure set is identical both ways. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6d82ee70b1f4`. 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/henrygd__beszel-2316/tests/oracle.patch b/tasks/henrygd__beszel-2316/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a7b029b08d74d1d4dde782f3e82293c9b55b1496 --- /dev/null +++ b/tasks/henrygd__beszel-2316/tests/oracle.patch @@ -0,0 +1,79 @@ +diff --git a/agent/client.go b/agent/client.go +index 9b1351f6..292f6307 100644 +--- a/agent/client.go ++++ b/agent/client.go +@@ -30,6 +30,11 @@ const ( + wsDeadline = 120 * time.Second + ) + ++// errNoHubURL is returned when HUB_URL is unset. This is not a failure ++// condition: an agent configured with only a public key runs in SSH-only mode, ++// where the hub dials the agent and no outbound WebSocket client is expected. ++var errNoHubURL = errors.New("HUB_URL environment variable not set") ++ + type caCertFileError struct { + err error + } +@@ -63,7 +68,7 @@ type WebSocketClient struct { + func newWebSocketClient(agent *Agent) (client *WebSocketClient, err error) { + hubURLStr, exists := utils.GetEnv("HUB_URL") + if !exists { +- return nil, errors.New("HUB_URL environment variable not set") ++ return nil, errNoHubURL + } + + client = &WebSocketClient{} +diff --git a/agent/client_test.go b/agent/client_test.go +index 97cb6654..0478ac7c 100644 +--- a/agent/client_test.go ++++ b/agent/client_test.go +@@ -32,6 +32,28 @@ import ( + "golang.org/x/crypto/ssh" + ) + ++// TestNewWebSocketClientNoHubURL verifies that an unset HUB_URL returns the ++// errNoHubURL sentinel rather than an opaque error. Callers rely on this to ++// distinguish SSH-only mode -- a supported configuration in which the hub dials ++// the agent -- from an actual misconfiguration. ++func TestNewWebSocketClientNoHubURL(t *testing.T) { ++ agent := createTestAgent(t) ++ ++ // t.Setenv registers restoration of the original value; unset afterwards so ++ // GetEnv's LookupEnv reports the variable as absent rather than empty. ++ t.Setenv("BESZEL_AGENT_HUB_URL", "") ++ os.Unsetenv("BESZEL_AGENT_HUB_URL") ++ t.Setenv("HUB_URL", "") ++ os.Unsetenv("HUB_URL") ++ t.Setenv("BESZEL_AGENT_TOKEN", "test-token") ++ ++ client, err := newWebSocketClient(agent) ++ ++ require.Error(t, err) ++ assert.Nil(t, client) ++ assert.ErrorIs(t, err, errNoHubURL) ++} ++ + // TestNewWebSocketClient tests WebSocket client creation + func TestNewWebSocketClient(t *testing.T) { + agent := createTestAgent(t) +diff --git a/agent/connection_manager.go b/agent/connection_manager.go +index d9b16d24..28ea98ae 100644 +--- a/agent/connection_manager.go ++++ b/agent/connection_manager.go +@@ -91,7 +91,15 @@ func (c *ConnectionManager) Start(serverOptions ServerOptions) error { + if errors.As(err, &caCertErr) { + return err + } +- slog.Warn("Error creating WebSocket client", "err", err) ++ disableSSH, _ := utils.GetEnv("DISABLE_SSH") ++ if errors.Is(err, errNoHubURL) && disableSSH != "true" { ++ // SSH-only mode: the hub dials the agent, so there is nothing to warn ++ // about. With SSH also disabled there is no connection method at all, ++ // so that case still warns. ++ slog.Debug("WebSocket client not configured", "err", err) ++ } else { ++ slog.Warn("Error creating WebSocket client", "err", err) ++ } + } + c.wsClient = wsClient + diff --git a/tasks/henrygd__beszel-2316/tests/test.sh b/tasks/henrygd__beszel-2316/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9da28ce5cf3d77047374d85db28b6fae2660d69b --- /dev/null +++ b/tasks/henrygd__beszel-2316/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 6d82ee70b1f41ceaeaff3d10ab88ae27cd23e781 > "$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/henrygd__beszel-2316/tests/verifier.py b/tasks/henrygd__beszel-2316/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2316/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/henrygd__beszel-2327/environment/Dockerfile b/tasks/henrygd__beszel-2327/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d752dce0935b34577b4b65278369f1327c7d0520 --- /dev/null +++ b/tasks/henrygd__beszel-2327/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f204dc17e64bba444478c60210d018e43a777193 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f204dc17e64bba444478c60210d018e43a777193 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f204dc17e64bba444478c60210d018e43a777193 \ + && 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/henrygd__beszel-2327/instruction.md b/tasks/henrygd__beszel-2327/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5b25f1c3551693e571b0085ab231c0d7304e5d97 --- /dev/null +++ b/tasks/henrygd__beszel-2327/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** feat(hub): add TRUSTED_PROXY_IPS allowlist for TRUSTED_AUTH_HEADER + +## Description + +## 📃 Description + +. It follows the sketch @tikket1 gave there. + +With `TRUSTED_AUTH_HEADER` set, the hub authenticates a request from the header alone, whichever address it comes from. That is right when every request passes through the reverse proxy, and not when the hub can also be reached directly, since anyone who can reach it can set the header themselves. + +This adds `TRUSTED_PROXY_IPS`, a comma-separated list of IPs or CIDR ranges. When set, the header is only honored on requests whose peer address is in the list; other requests fall through to the normal authentication. When unset, nothing changes. + +Details: + +- The check uses the connection's `RemoteAddr`, not `e.RealIP()`: PocketBase's trusted proxy setting only decides which forwarded header names the client, and that header is exactly what a direct connection can forge. The list names the proxy itself. IPv4-mapped IPv6 entries are treated as IPv4, and zones on the peer address are ignored. +- Entries that do not parse are skipped with a warning on the console, the way `config.yml` problems are reported. A list with no valid entry trusts nobody, so a typo narrows the allowlist instead of widening it. +- The list is parsed once when the middleware is registered. + +Tests: `TestTrustedHeaderProxyAllowlist` runs the same `/api/beszel/getkey` scenario as `TestTrustedHeaderMiddleware` with the allowlist set (the test client connects from `192.0.2.1`): a range that contains the peer and the exact address both authenticate, a range that does not and a list with no valid entry both get 401. Against the current middleware those last two return 200. `TestParseTrustedProxies` and `TestIsTrustedProxy` cover the parsing (single addresses, masked CIDRs, IPv4-mapped entries, blanks, invalid entries, the `BESZEL_HUB_` prefix) and the peer matching (IPv6, zones, missing port, garbage). `go test -tags='testing no_ui' ./internal/hub/...` passes. + +Checked end to end with the hub in a container on a user-defined Docker network, `TRUSTED_AUTH_HEADER=X-Remote-Email` and a user with that email: without `TRUSTED_PROXY_IPS`, both the host (peer `172.22.0.1`) and another container on the network get 200 from `/api/beszel/getkey` with the header. With `TRUSTED_PROXY_IPS=172.22.0.1` the host still gets 200 and the other container gets 401. With `TRUSTED_PROXY_IPS=proxy.internal` everyone gets 401, and `TRUSTED_PROXY_IPS="proxy.internal, ::ffff:172.22.0.1"` logs `Ignoring invalid TRUSTED_PROXY_IPS entry "proxy.internal"` on the console and behaves like the second case. + +## 📖 Documentation + +henrygd/beszel-docs#82 + +## 🪵 Changelog + +### ➕ Added + +- `TRUSTED_PROXY_IPS`: optional allowlist of peer addresses from which `TRUSTED_AUTH_HEADER` is honored. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f204dc17e64b`. 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/henrygd__beszel-2327/solution/patch.diff b/tasks/henrygd__beszel-2327/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..983f523ed8a9ae1d15caeddc3ba48f443e16fc8e --- /dev/null +++ b/tasks/henrygd__beszel-2327/solution/patch.diff @@ -0,0 +1,315 @@ +diff --git a/internal/hub/api.go b/internal/hub/api.go +index 599c4eff..a97819cb 100644 +--- a/internal/hub/api.go ++++ b/internal/hub/api.go +@@ -2,7 +2,11 @@ package hub + + import ( + "context" ++ "fmt" ++ "log/slog" ++ "net" + "net/http" ++ "net/netip" + "regexp" + "strings" + "time" +@@ -78,12 +82,81 @@ func (h *Hub) registerMiddlewares(se *core.ServeEvent) { + } + // authenticate with trusted header + if trustedHeader, _ := utils.GetEnv("TRUSTED_AUTH_HEADER"); trustedHeader != "" { ++ // only honor the header from these peers, if set ++ trustedProxies, restricted := parseTrustedProxies() + se.Router.BindFunc(func(e *core.RequestEvent) error { ++ if restricted && !isTrustedProxy(trustedProxies, e.Request.RemoteAddr) { ++ return e.Next() ++ } + return authorizeRequestWithEmail(e, e.Request.Header.Get(trustedHeader)) + }) + } + } + ++// parseTrustedProxies reads TRUSTED_PROXY_IPS (comma-separated IPs or CIDRs). ++// restricted is false when the variable is unset or empty, meaning the trusted ++// header is accepted from any peer. Invalid entries are skipped with a warning, ++// so a typo narrows the allowlist rather than widening it. ++func parseTrustedProxies() (prefixes []netip.Prefix, restricted bool) { ++ value, _ := utils.GetEnv("TRUSTED_PROXY_IPS") ++ if value == "" { ++ return nil, false ++ } ++ for entry := range strings.SplitSeq(value, ",") { ++ entry = strings.TrimSpace(entry) ++ if entry == "" { ++ continue ++ } ++ if prefix, err := parseProxyPrefix(entry); err == nil { ++ prefixes = append(prefixes, prefix) ++ } else { ++ slog.Warn("Ignoring invalid TRUSTED_PROXY_IPS entry", "entry", entry) ++ } ++ } ++ return prefixes, true ++} ++ ++// parseProxyPrefix parses an IP or CIDR into a masked prefix. IPv4-mapped IPv6 ++// entries are converted to IPv4 so they match IPv4 peers. ++func parseProxyPrefix(entry string) (netip.Prefix, error) { ++ prefix, err := netip.ParsePrefix(entry) ++ if err != nil { ++ addr, err := netip.ParseAddr(entry) ++ if err != nil { ++ return netip.Prefix{}, err ++ } ++ addr = addr.Unmap() ++ return netip.PrefixFrom(addr, addr.BitLen()), nil ++ } ++ if prefix.Addr().Is4In6() { ++ if prefix.Bits() < 96 { ++ return netip.Prefix{}, fmt.Errorf("%s covers more than the IPv4-mapped range", entry) ++ } ++ prefix = netip.PrefixFrom(prefix.Addr().Unmap(), prefix.Bits()-96) ++ } ++ return prefix.Masked(), nil ++} ++ ++// isTrustedProxy reports whether the peer address of a request (host:port) is ++// within one of the prefixes. ++func isTrustedProxy(prefixes []netip.Prefix, remoteAddr string) bool { ++ host, _, err := net.SplitHostPort(remoteAddr) ++ if err != nil { ++ host = remoteAddr ++ } ++ addr, err := netip.ParseAddr(host) ++ if err != nil { ++ return false ++ } ++ addr = addr.Unmap().WithZone("") ++ for _, prefix := range prefixes { ++ if prefix.Contains(addr) { ++ return true ++ } ++ } ++ return false ++} ++ + // registerApiRoutes registers custom API routes + func (h *Hub) registerApiRoutes(se *core.ServeEvent) error { + // auth protected routes +diff --git a/internal/hub/api_test.go b/internal/hub/api_test.go +index bbe3ff0c..2040de8e 100644 +--- a/internal/hub/api_test.go ++++ b/internal/hub/api_test.go +@@ -969,6 +969,79 @@ func TestTrustedHeaderMiddleware(t *testing.T) { + } + } + ++func TestTrustedHeaderProxyAllowlist(t *testing.T) { ++ var hubs []*beszelTests.TestHub ++ ++ defer func() { ++ for _, hub := range hubs { ++ hub.Cleanup() ++ } ++ }() ++ ++ testAppFactory := func(t testing.TB) *pbTests.TestApp { ++ hub, _ := beszelTests.NewTestHub(t.TempDir()) ++ hubs = append(hubs, hub) ++ hub.StartHub() ++ return hub.TestApp ++ } ++ ++ // httptest requests arrive from 192.0.2.1:1234 ++ testCases := []struct { ++ name string ++ proxies string ++ expectedStatus int ++ expectedContent []string ++ }{ ++ { ++ name: "peer inside an allowed range", ++ proxies: "10.0.0.0/8, 192.0.2.0/24", ++ expectedStatus: 200, ++ expectedContent: []string{"\"key\":", "\"v\":"}, ++ }, ++ { ++ name: "peer is the listed address", ++ proxies: "192.0.2.1", ++ expectedStatus: 200, ++ expectedContent: []string{"\"key\":", "\"v\":"}, ++ }, ++ { ++ name: "peer outside the allowlist", ++ proxies: "10.0.0.0/8", ++ expectedStatus: 401, ++ expectedContent: []string{"requires valid"}, ++ }, ++ { ++ name: "allowlist with no valid entry", ++ proxies: "proxy.internal", ++ expectedStatus: 401, ++ expectedContent: []string{"requires valid"}, ++ }, ++ } ++ ++ for _, tc := range testCases { ++ t.Run(tc.name, func(t *testing.T) { ++ t.Setenv("TRUSTED_AUTH_HEADER", "X-Beszel-Trusted") ++ t.Setenv("TRUSTED_PROXY_IPS", tc.proxies) ++ ++ scenario := beszelTests.ApiScenario{ ++ Name: "GET /getkey - with trusted header", ++ Method: http.MethodGet, ++ URL: "/api/beszel/getkey", ++ Headers: map[string]string{ ++ "X-Beszel-Trusted": "user@test.com", ++ }, ++ ExpectedStatus: tc.expectedStatus, ++ ExpectedContent: tc.expectedContent, ++ TestAppFactory: testAppFactory, ++ BeforeTestFunc: func(t testing.TB, app *pbTests.TestApp, e *core.ServeEvent) { ++ beszelTests.CreateUser(app, "user@test.com", "password123") ++ }, ++ } ++ scenario.Test(t) ++ }) ++ } ++} ++ + func TestUpdateEndpoint(t *testing.T) { + t.Setenv("CHECK_UPDATES", "true") + +diff --git a/internal/hub/trusted_proxy_test.go b/internal/hub/trusted_proxy_test.go +new file mode 100644 +index 00000000..32140330 +--- /dev/null ++++ b/internal/hub/trusted_proxy_test.go +@@ -0,0 +1,127 @@ ++//go:build testing ++ ++package hub ++ ++import ( ++ "net/netip" ++ "os" ++ "testing" ++ ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/require" ++) ++ ++func TestParseTrustedProxies(t *testing.T) { ++ testCases := []struct { ++ name string ++ value string ++ prefixes []string ++ restricted bool ++ }{ ++ { ++ name: "empty", ++ value: "", ++ restricted: false, ++ }, ++ { ++ name: "blank", ++ value: " , ", ++ prefixes: nil, ++ restricted: true, ++ }, ++ { ++ name: "single addresses become host prefixes", ++ value: "10.0.0.5, 2001:db8::1", ++ prefixes: []string{"10.0.0.5/32", "2001:db8::1/128"}, ++ restricted: true, ++ }, ++ { ++ name: "cidrs are masked", ++ value: "172.16.5.9/12,fd00::1/64", ++ prefixes: []string{"172.16.0.0/12", "fd00::/64"}, ++ restricted: true, ++ }, ++ { ++ name: "ipv4-mapped entries become ipv4", ++ value: "::ffff:10.0.0.5, ::ffff:10.0.0.0/104", ++ prefixes: []string{"10.0.0.5/32", "10.0.0.0/8"}, ++ restricted: true, ++ }, ++ { ++ name: "invalid entries are skipped, valid ones kept", ++ value: "proxy.internal, 10.0.0.0/8, 300.1.1.1, ::ffff:0.0.0.0/64", ++ prefixes: []string{"10.0.0.0/8"}, ++ restricted: true, ++ }, ++ { ++ name: "only invalid entries trust nobody", ++ value: "proxy.internal", ++ prefixes: nil, ++ restricted: true, ++ }, ++ } ++ ++ for _, tc := range testCases { ++ t.Run(tc.name, func(t *testing.T) { ++ t.Setenv("TRUSTED_PROXY_IPS", tc.value) ++ prefixes, restricted := parseTrustedProxies() ++ assert.Equal(t, tc.restricted, restricted) ++ var got []string ++ for _, p := range prefixes { ++ got = append(got, p.String()) ++ } ++ assert.Equal(t, tc.prefixes, got) ++ }) ++ } ++ ++ t.Run("unset", func(t *testing.T) { ++ t.Setenv("TRUSTED_PROXY_IPS", "") ++ os.Unsetenv("TRUSTED_PROXY_IPS") ++ prefixes, restricted := parseTrustedProxies() ++ assert.False(t, restricted) ++ assert.Nil(t, prefixes) ++ }) ++ ++ t.Run("prefixed env var takes precedence", func(t *testing.T) { ++ t.Setenv("TRUSTED_PROXY_IPS", "10.0.0.0/8") ++ t.Setenv("BESZEL_HUB_TRUSTED_PROXY_IPS", "192.168.0.0/16") ++ prefixes, restricted := parseTrustedProxies() ++ assert.True(t, restricted) ++ require.Len(t, prefixes, 1) ++ assert.Equal(t, "192.168.0.0/16", prefixes[0].String()) ++ }) ++} ++ ++func TestIsTrustedProxy(t *testing.T) { ++ prefixes := []netip.Prefix{ ++ netip.MustParsePrefix("10.0.0.0/8"), ++ netip.MustParsePrefix("2001:db8::/32"), ++ netip.MustParsePrefix("fe80::/10"), ++ } ++ ++ testCases := []struct { ++ name string ++ remoteAddr string ++ trusted bool ++ }{ ++ {"ipv4 in prefix", "10.20.30.40:51234", true}, ++ {"ipv4 outside prefix", "11.0.0.1:51234", false}, ++ {"ipv6 in prefix", "[2001:db8:1::2]:443", true}, ++ {"ipv6 outside prefix", "[2001:db9::1]:443", false}, ++ {"ipv4-mapped ipv6 matches ipv4 prefix", "[::ffff:10.1.2.3]:80", true}, ++ {"zone is ignored", "[fe80::1%eth0]:80", true}, ++ {"no port", "10.1.2.3", true}, ++ {"empty", "", false}, ++ {"garbage", "not-an-address:80", false}, ++ } ++ ++ for _, tc := range testCases { ++ t.Run(tc.name, func(t *testing.T) { ++ assert.Equal(t, tc.trusted, isTrustedProxy(prefixes, tc.remoteAddr)) ++ }) ++ } ++ ++ t.Run("empty allowlist trusts nobody", func(t *testing.T) { ++ assert.False(t, isTrustedProxy(nil, "10.0.0.1:1")) ++ }) ++} diff --git a/tasks/henrygd__beszel-2327/solution/solve.sh b/tasks/henrygd__beszel-2327/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2327/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/henrygd__beszel-2327/task.toml b/tasks/henrygd__beszel-2327/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0dbfbc4a93802de675c889096c0b5f59b15524d6 --- /dev/null +++ b/tasks/henrygd__beszel-2327/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2327" +description = "feat(hub): add TRUSTED_PROXY_IPS allowlist for TRUSTED_AUTH_HEADER" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "f204dc17e64bba444478c60210d018e43a777193" +reference = "https://github.com/henrygd/beszel/pull/2327" +source_access = "auto" +built_at = "2026-11-16T16:09:53.497313+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9670ce52a5e2efd5d699ce6d696013a781291fd06604890727b5cf59482855b4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-17T17:48:47Z" +diff_format = "unified" +context_files = [ + "internal/hub/api.go", + "internal/hub/api_test.go", + "internal/hub/trusted_proxy_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 273 +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:00.813167+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7a89109ade77bcfb74ec05d73b3c5fb6a7e28fc437ddbbcba3529ffab8fd2680" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2327/tests/capture.py b/tasks/henrygd__beszel-2327/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2327/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/henrygd__beszel-2327/tests/instruction.md b/tasks/henrygd__beszel-2327/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5b25f1c3551693e571b0085ab231c0d7304e5d97 --- /dev/null +++ b/tasks/henrygd__beszel-2327/tests/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** feat(hub): add TRUSTED_PROXY_IPS allowlist for TRUSTED_AUTH_HEADER + +## Description + +## 📃 Description + +. It follows the sketch @tikket1 gave there. + +With `TRUSTED_AUTH_HEADER` set, the hub authenticates a request from the header alone, whichever address it comes from. That is right when every request passes through the reverse proxy, and not when the hub can also be reached directly, since anyone who can reach it can set the header themselves. + +This adds `TRUSTED_PROXY_IPS`, a comma-separated list of IPs or CIDR ranges. When set, the header is only honored on requests whose peer address is in the list; other requests fall through to the normal authentication. When unset, nothing changes. + +Details: + +- The check uses the connection's `RemoteAddr`, not `e.RealIP()`: PocketBase's trusted proxy setting only decides which forwarded header names the client, and that header is exactly what a direct connection can forge. The list names the proxy itself. IPv4-mapped IPv6 entries are treated as IPv4, and zones on the peer address are ignored. +- Entries that do not parse are skipped with a warning on the console, the way `config.yml` problems are reported. A list with no valid entry trusts nobody, so a typo narrows the allowlist instead of widening it. +- The list is parsed once when the middleware is registered. + +Tests: `TestTrustedHeaderProxyAllowlist` runs the same `/api/beszel/getkey` scenario as `TestTrustedHeaderMiddleware` with the allowlist set (the test client connects from `192.0.2.1`): a range that contains the peer and the exact address both authenticate, a range that does not and a list with no valid entry both get 401. Against the current middleware those last two return 200. `TestParseTrustedProxies` and `TestIsTrustedProxy` cover the parsing (single addresses, masked CIDRs, IPv4-mapped entries, blanks, invalid entries, the `BESZEL_HUB_` prefix) and the peer matching (IPv6, zones, missing port, garbage). `go test -tags='testing no_ui' ./internal/hub/...` passes. + +Checked end to end with the hub in a container on a user-defined Docker network, `TRUSTED_AUTH_HEADER=X-Remote-Email` and a user with that email: without `TRUSTED_PROXY_IPS`, both the host (peer `172.22.0.1`) and another container on the network get 200 from `/api/beszel/getkey` with the header. With `TRUSTED_PROXY_IPS=172.22.0.1` the host still gets 200 and the other container gets 401. With `TRUSTED_PROXY_IPS=proxy.internal` everyone gets 401, and `TRUSTED_PROXY_IPS="proxy.internal, ::ffff:172.22.0.1"` logs `Ignoring invalid TRUSTED_PROXY_IPS entry "proxy.internal"` on the console and behaves like the second case. + +## 📖 Documentation + +henrygd/beszel-docs#82 + +## 🪵 Changelog + +### ➕ Added + +- `TRUSTED_PROXY_IPS`: optional allowlist of peer addresses from which `TRUSTED_AUTH_HEADER` is honored. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f204dc17e64b`. 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/henrygd__beszel-2327/tests/oracle.patch b/tasks/henrygd__beszel-2327/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..983f523ed8a9ae1d15caeddc3ba48f443e16fc8e --- /dev/null +++ b/tasks/henrygd__beszel-2327/tests/oracle.patch @@ -0,0 +1,315 @@ +diff --git a/internal/hub/api.go b/internal/hub/api.go +index 599c4eff..a97819cb 100644 +--- a/internal/hub/api.go ++++ b/internal/hub/api.go +@@ -2,7 +2,11 @@ package hub + + import ( + "context" ++ "fmt" ++ "log/slog" ++ "net" + "net/http" ++ "net/netip" + "regexp" + "strings" + "time" +@@ -78,12 +82,81 @@ func (h *Hub) registerMiddlewares(se *core.ServeEvent) { + } + // authenticate with trusted header + if trustedHeader, _ := utils.GetEnv("TRUSTED_AUTH_HEADER"); trustedHeader != "" { ++ // only honor the header from these peers, if set ++ trustedProxies, restricted := parseTrustedProxies() + se.Router.BindFunc(func(e *core.RequestEvent) error { ++ if restricted && !isTrustedProxy(trustedProxies, e.Request.RemoteAddr) { ++ return e.Next() ++ } + return authorizeRequestWithEmail(e, e.Request.Header.Get(trustedHeader)) + }) + } + } + ++// parseTrustedProxies reads TRUSTED_PROXY_IPS (comma-separated IPs or CIDRs). ++// restricted is false when the variable is unset or empty, meaning the trusted ++// header is accepted from any peer. Invalid entries are skipped with a warning, ++// so a typo narrows the allowlist rather than widening it. ++func parseTrustedProxies() (prefixes []netip.Prefix, restricted bool) { ++ value, _ := utils.GetEnv("TRUSTED_PROXY_IPS") ++ if value == "" { ++ return nil, false ++ } ++ for entry := range strings.SplitSeq(value, ",") { ++ entry = strings.TrimSpace(entry) ++ if entry == "" { ++ continue ++ } ++ if prefix, err := parseProxyPrefix(entry); err == nil { ++ prefixes = append(prefixes, prefix) ++ } else { ++ slog.Warn("Ignoring invalid TRUSTED_PROXY_IPS entry", "entry", entry) ++ } ++ } ++ return prefixes, true ++} ++ ++// parseProxyPrefix parses an IP or CIDR into a masked prefix. IPv4-mapped IPv6 ++// entries are converted to IPv4 so they match IPv4 peers. ++func parseProxyPrefix(entry string) (netip.Prefix, error) { ++ prefix, err := netip.ParsePrefix(entry) ++ if err != nil { ++ addr, err := netip.ParseAddr(entry) ++ if err != nil { ++ return netip.Prefix{}, err ++ } ++ addr = addr.Unmap() ++ return netip.PrefixFrom(addr, addr.BitLen()), nil ++ } ++ if prefix.Addr().Is4In6() { ++ if prefix.Bits() < 96 { ++ return netip.Prefix{}, fmt.Errorf("%s covers more than the IPv4-mapped range", entry) ++ } ++ prefix = netip.PrefixFrom(prefix.Addr().Unmap(), prefix.Bits()-96) ++ } ++ return prefix.Masked(), nil ++} ++ ++// isTrustedProxy reports whether the peer address of a request (host:port) is ++// within one of the prefixes. ++func isTrustedProxy(prefixes []netip.Prefix, remoteAddr string) bool { ++ host, _, err := net.SplitHostPort(remoteAddr) ++ if err != nil { ++ host = remoteAddr ++ } ++ addr, err := netip.ParseAddr(host) ++ if err != nil { ++ return false ++ } ++ addr = addr.Unmap().WithZone("") ++ for _, prefix := range prefixes { ++ if prefix.Contains(addr) { ++ return true ++ } ++ } ++ return false ++} ++ + // registerApiRoutes registers custom API routes + func (h *Hub) registerApiRoutes(se *core.ServeEvent) error { + // auth protected routes +diff --git a/internal/hub/api_test.go b/internal/hub/api_test.go +index bbe3ff0c..2040de8e 100644 +--- a/internal/hub/api_test.go ++++ b/internal/hub/api_test.go +@@ -969,6 +969,79 @@ func TestTrustedHeaderMiddleware(t *testing.T) { + } + } + ++func TestTrustedHeaderProxyAllowlist(t *testing.T) { ++ var hubs []*beszelTests.TestHub ++ ++ defer func() { ++ for _, hub := range hubs { ++ hub.Cleanup() ++ } ++ }() ++ ++ testAppFactory := func(t testing.TB) *pbTests.TestApp { ++ hub, _ := beszelTests.NewTestHub(t.TempDir()) ++ hubs = append(hubs, hub) ++ hub.StartHub() ++ return hub.TestApp ++ } ++ ++ // httptest requests arrive from 192.0.2.1:1234 ++ testCases := []struct { ++ name string ++ proxies string ++ expectedStatus int ++ expectedContent []string ++ }{ ++ { ++ name: "peer inside an allowed range", ++ proxies: "10.0.0.0/8, 192.0.2.0/24", ++ expectedStatus: 200, ++ expectedContent: []string{"\"key\":", "\"v\":"}, ++ }, ++ { ++ name: "peer is the listed address", ++ proxies: "192.0.2.1", ++ expectedStatus: 200, ++ expectedContent: []string{"\"key\":", "\"v\":"}, ++ }, ++ { ++ name: "peer outside the allowlist", ++ proxies: "10.0.0.0/8", ++ expectedStatus: 401, ++ expectedContent: []string{"requires valid"}, ++ }, ++ { ++ name: "allowlist with no valid entry", ++ proxies: "proxy.internal", ++ expectedStatus: 401, ++ expectedContent: []string{"requires valid"}, ++ }, ++ } ++ ++ for _, tc := range testCases { ++ t.Run(tc.name, func(t *testing.T) { ++ t.Setenv("TRUSTED_AUTH_HEADER", "X-Beszel-Trusted") ++ t.Setenv("TRUSTED_PROXY_IPS", tc.proxies) ++ ++ scenario := beszelTests.ApiScenario{ ++ Name: "GET /getkey - with trusted header", ++ Method: http.MethodGet, ++ URL: "/api/beszel/getkey", ++ Headers: map[string]string{ ++ "X-Beszel-Trusted": "user@test.com", ++ }, ++ ExpectedStatus: tc.expectedStatus, ++ ExpectedContent: tc.expectedContent, ++ TestAppFactory: testAppFactory, ++ BeforeTestFunc: func(t testing.TB, app *pbTests.TestApp, e *core.ServeEvent) { ++ beszelTests.CreateUser(app, "user@test.com", "password123") ++ }, ++ } ++ scenario.Test(t) ++ }) ++ } ++} ++ + func TestUpdateEndpoint(t *testing.T) { + t.Setenv("CHECK_UPDATES", "true") + +diff --git a/internal/hub/trusted_proxy_test.go b/internal/hub/trusted_proxy_test.go +new file mode 100644 +index 00000000..32140330 +--- /dev/null ++++ b/internal/hub/trusted_proxy_test.go +@@ -0,0 +1,127 @@ ++//go:build testing ++ ++package hub ++ ++import ( ++ "net/netip" ++ "os" ++ "testing" ++ ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/require" ++) ++ ++func TestParseTrustedProxies(t *testing.T) { ++ testCases := []struct { ++ name string ++ value string ++ prefixes []string ++ restricted bool ++ }{ ++ { ++ name: "empty", ++ value: "", ++ restricted: false, ++ }, ++ { ++ name: "blank", ++ value: " , ", ++ prefixes: nil, ++ restricted: true, ++ }, ++ { ++ name: "single addresses become host prefixes", ++ value: "10.0.0.5, 2001:db8::1", ++ prefixes: []string{"10.0.0.5/32", "2001:db8::1/128"}, ++ restricted: true, ++ }, ++ { ++ name: "cidrs are masked", ++ value: "172.16.5.9/12,fd00::1/64", ++ prefixes: []string{"172.16.0.0/12", "fd00::/64"}, ++ restricted: true, ++ }, ++ { ++ name: "ipv4-mapped entries become ipv4", ++ value: "::ffff:10.0.0.5, ::ffff:10.0.0.0/104", ++ prefixes: []string{"10.0.0.5/32", "10.0.0.0/8"}, ++ restricted: true, ++ }, ++ { ++ name: "invalid entries are skipped, valid ones kept", ++ value: "proxy.internal, 10.0.0.0/8, 300.1.1.1, ::ffff:0.0.0.0/64", ++ prefixes: []string{"10.0.0.0/8"}, ++ restricted: true, ++ }, ++ { ++ name: "only invalid entries trust nobody", ++ value: "proxy.internal", ++ prefixes: nil, ++ restricted: true, ++ }, ++ } ++ ++ for _, tc := range testCases { ++ t.Run(tc.name, func(t *testing.T) { ++ t.Setenv("TRUSTED_PROXY_IPS", tc.value) ++ prefixes, restricted := parseTrustedProxies() ++ assert.Equal(t, tc.restricted, restricted) ++ var got []string ++ for _, p := range prefixes { ++ got = append(got, p.String()) ++ } ++ assert.Equal(t, tc.prefixes, got) ++ }) ++ } ++ ++ t.Run("unset", func(t *testing.T) { ++ t.Setenv("TRUSTED_PROXY_IPS", "") ++ os.Unsetenv("TRUSTED_PROXY_IPS") ++ prefixes, restricted := parseTrustedProxies() ++ assert.False(t, restricted) ++ assert.Nil(t, prefixes) ++ }) ++ ++ t.Run("prefixed env var takes precedence", func(t *testing.T) { ++ t.Setenv("TRUSTED_PROXY_IPS", "10.0.0.0/8") ++ t.Setenv("BESZEL_HUB_TRUSTED_PROXY_IPS", "192.168.0.0/16") ++ prefixes, restricted := parseTrustedProxies() ++ assert.True(t, restricted) ++ require.Len(t, prefixes, 1) ++ assert.Equal(t, "192.168.0.0/16", prefixes[0].String()) ++ }) ++} ++ ++func TestIsTrustedProxy(t *testing.T) { ++ prefixes := []netip.Prefix{ ++ netip.MustParsePrefix("10.0.0.0/8"), ++ netip.MustParsePrefix("2001:db8::/32"), ++ netip.MustParsePrefix("fe80::/10"), ++ } ++ ++ testCases := []struct { ++ name string ++ remoteAddr string ++ trusted bool ++ }{ ++ {"ipv4 in prefix", "10.20.30.40:51234", true}, ++ {"ipv4 outside prefix", "11.0.0.1:51234", false}, ++ {"ipv6 in prefix", "[2001:db8:1::2]:443", true}, ++ {"ipv6 outside prefix", "[2001:db9::1]:443", false}, ++ {"ipv4-mapped ipv6 matches ipv4 prefix", "[::ffff:10.1.2.3]:80", true}, ++ {"zone is ignored", "[fe80::1%eth0]:80", true}, ++ {"no port", "10.1.2.3", true}, ++ {"empty", "", false}, ++ {"garbage", "not-an-address:80", false}, ++ } ++ ++ for _, tc := range testCases { ++ t.Run(tc.name, func(t *testing.T) { ++ assert.Equal(t, tc.trusted, isTrustedProxy(prefixes, tc.remoteAddr)) ++ }) ++ } ++ ++ t.Run("empty allowlist trusts nobody", func(t *testing.T) { ++ assert.False(t, isTrustedProxy(nil, "10.0.0.1:1")) ++ }) ++} diff --git a/tasks/henrygd__beszel-2327/tests/test.sh b/tasks/henrygd__beszel-2327/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c70649546468b7abfc4786362d83548960d08e2f --- /dev/null +++ b/tasks/henrygd__beszel-2327/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 f204dc17e64bba444478c60210d018e43a777193 > "$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/henrygd__beszel-2327/tests/verifier.py b/tasks/henrygd__beszel-2327/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2327/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/henrygd__beszel-2328/environment/Dockerfile b/tasks/henrygd__beszel-2328/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d752dce0935b34577b4b65278369f1327c7d0520 --- /dev/null +++ b/tasks/henrygd__beszel-2328/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f204dc17e64bba444478c60210d018e43a777193 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f204dc17e64bba444478c60210d018e43a777193 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f204dc17e64bba444478c60210d018e43a777193 \ + && 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/henrygd__beszel-2328/instruction.md b/tasks/henrygd__beszel-2328/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ded0704979598a8a1a8cdb147d68323a2060d800 --- /dev/null +++ b/tasks/henrygd__beszel-2328/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** fix(site): switch theme live when system preference changes + +## Description + +## 📃 Description + +When theme is set to "system", changing the OS light/dark preference did not update the app until a hard refresh. `ThemeProvider` read `prefers-color-scheme` only once, when the theme was applied. + +This PR subscribes to `prefers-color-scheme` changes and applies the resolved theme immediately. It also exposes `resolvedTheme` through context, so components can react to the active theme instead of the stored preference (the login page used `theme`, which treats "system" as dark). + +## 🪵 Changelog + +### 🔧 Fixed + +- System theme (OS light/dark changes) now applies live, without a page refresh. +- Login page border color now follows the resolved theme when "system" is selected. + +## 📷 Screenshots + +No visual changes beyond the correct colors being applied live. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f204dc17e64b`. 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/henrygd__beszel-2328/solution/patch.diff b/tasks/henrygd__beszel-2328/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8a1ff409d17947ae867d3116fe8702ca223d219b --- /dev/null +++ b/tasks/henrygd__beszel-2328/solution/patch.diff @@ -0,0 +1,86 @@ +diff --git a/internal/site/src/components/login/login.tsx b/internal/site/src/components/login/login.tsx +index b03284f7..a463e408 100644 +--- a/internal/site/src/components/login/login.tsx ++++ b/internal/site/src/components/login/login.tsx +@@ -15,7 +15,7 @@ export default function () { + const page = useStore($router) + const [isFirstRun, setFirstRun] = useState(false) + const [authMethods, setAuthMethods] = useState() +- const { theme } = useTheme() ++ const { resolvedTheme } = useTheme() + + useEffect(() => { + document.title = t`Login` + " / Beszel" +@@ -54,7 +54,7 @@ export default function () { +
+
+ +diff --git a/internal/site/src/components/theme-provider.tsx b/internal/site/src/components/theme-provider.tsx +index 475c07c1..2813503b 100644 +--- a/internal/site/src/components/theme-provider.tsx ++++ b/internal/site/src/components/theme-provider.tsx +@@ -1,6 +1,7 @@ + import { createContext, useContext, useEffect, useState } from "react" + + type Theme = "dark" | "light" | "system" ++type ResolvedTheme = "dark" | "light" + + type ThemeProviderProps = { + children: React.ReactNode +@@ -10,11 +11,13 @@ type ThemeProviderProps = { + + type ThemeProviderState = { + theme: Theme ++ resolvedTheme: ResolvedTheme + setTheme: (theme: Theme) => void + } + + const initialState: ThemeProviderState = { + theme: "system", ++ resolvedTheme: "light", + setTheme: () => null, + } + +@@ -27,24 +30,28 @@ export function ThemeProvider({ + ...props + }: ThemeProviderProps) { + const [theme, setTheme] = useState(() => (localStorage.getItem(storageKey) as Theme) || defaultTheme) ++ const [systemDark, setSystemDark] = useState(() => window.matchMedia("(prefers-color-scheme: dark)").matches) + + useEffect(() => { +- const root = window.document.documentElement ++ const media = window.matchMedia("(prefers-color-scheme: dark)") ++ const onChange = (event: MediaQueryListEvent) => setSystemDark(event.matches) + +- root.classList.remove("light", "dark") ++ media.addEventListener("change", onChange) ++ return () => media.removeEventListener("change", onChange) ++ }, []) + +- if (theme === "system") { +- const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" ++ const resolvedTheme = theme === "system" ? (systemDark ? "dark" : "light") : theme + +- root.classList.add(systemTheme) +- return +- } ++ useEffect(() => { ++ const root = window.document.documentElement + +- root.classList.add(theme) +- }, [theme]) ++ root.classList.remove("light", "dark") ++ root.classList.add(resolvedTheme) ++ }, [resolvedTheme]) + + const value = { + theme, ++ resolvedTheme, + setTheme: (theme: Theme) => { + localStorage.setItem(storageKey, theme) + setTheme(theme) diff --git a/tasks/henrygd__beszel-2328/solution/solve.sh b/tasks/henrygd__beszel-2328/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2328/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/henrygd__beszel-2328/task.toml b/tasks/henrygd__beszel-2328/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..083ad075daafa1d5beab0be15648f665f18cac84 --- /dev/null +++ b/tasks/henrygd__beszel-2328/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2328" +description = "fix(site): switch theme live when system preference changes" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "f204dc17e64bba444478c60210d018e43a777193" +reference = "https://github.com/henrygd/beszel/pull/2328" +source_access = "auto" +built_at = "2026-11-16T16:09:53.500568+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:91e19b7d1092abb04b39819ef195b8ff462e41072137a52e46181ab6b5c962a4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-13T16:40:22Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/login/login.tsx", + "internal/site/src/components/theme-provider.tsx", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 29 +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:00.813741+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7a89109ade77bcfb74ec05d73b3c5fb6a7e28fc437ddbbcba3529ffab8fd2680" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2328/tests/capture.py b/tasks/henrygd__beszel-2328/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2328/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/henrygd__beszel-2328/tests/instruction.md b/tasks/henrygd__beszel-2328/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ded0704979598a8a1a8cdb147d68323a2060d800 --- /dev/null +++ b/tasks/henrygd__beszel-2328/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** fix(site): switch theme live when system preference changes + +## Description + +## 📃 Description + +When theme is set to "system", changing the OS light/dark preference did not update the app until a hard refresh. `ThemeProvider` read `prefers-color-scheme` only once, when the theme was applied. + +This PR subscribes to `prefers-color-scheme` changes and applies the resolved theme immediately. It also exposes `resolvedTheme` through context, so components can react to the active theme instead of the stored preference (the login page used `theme`, which treats "system" as dark). + +## 🪵 Changelog + +### 🔧 Fixed + +- System theme (OS light/dark changes) now applies live, without a page refresh. +- Login page border color now follows the resolved theme when "system" is selected. + +## 📷 Screenshots + +No visual changes beyond the correct colors being applied live. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f204dc17e64b`. 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/henrygd__beszel-2328/tests/oracle.patch b/tasks/henrygd__beszel-2328/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8a1ff409d17947ae867d3116fe8702ca223d219b --- /dev/null +++ b/tasks/henrygd__beszel-2328/tests/oracle.patch @@ -0,0 +1,86 @@ +diff --git a/internal/site/src/components/login/login.tsx b/internal/site/src/components/login/login.tsx +index b03284f7..a463e408 100644 +--- a/internal/site/src/components/login/login.tsx ++++ b/internal/site/src/components/login/login.tsx +@@ -15,7 +15,7 @@ export default function () { + const page = useStore($router) + const [isFirstRun, setFirstRun] = useState(false) + const [authMethods, setAuthMethods] = useState() +- const { theme } = useTheme() ++ const { resolvedTheme } = useTheme() + + useEffect(() => { + document.title = t`Login` + " / Beszel" +@@ -54,7 +54,7 @@ export default function () { +
+
+ +diff --git a/internal/site/src/components/theme-provider.tsx b/internal/site/src/components/theme-provider.tsx +index 475c07c1..2813503b 100644 +--- a/internal/site/src/components/theme-provider.tsx ++++ b/internal/site/src/components/theme-provider.tsx +@@ -1,6 +1,7 @@ + import { createContext, useContext, useEffect, useState } from "react" + + type Theme = "dark" | "light" | "system" ++type ResolvedTheme = "dark" | "light" + + type ThemeProviderProps = { + children: React.ReactNode +@@ -10,11 +11,13 @@ type ThemeProviderProps = { + + type ThemeProviderState = { + theme: Theme ++ resolvedTheme: ResolvedTheme + setTheme: (theme: Theme) => void + } + + const initialState: ThemeProviderState = { + theme: "system", ++ resolvedTheme: "light", + setTheme: () => null, + } + +@@ -27,24 +30,28 @@ export function ThemeProvider({ + ...props + }: ThemeProviderProps) { + const [theme, setTheme] = useState(() => (localStorage.getItem(storageKey) as Theme) || defaultTheme) ++ const [systemDark, setSystemDark] = useState(() => window.matchMedia("(prefers-color-scheme: dark)").matches) + + useEffect(() => { +- const root = window.document.documentElement ++ const media = window.matchMedia("(prefers-color-scheme: dark)") ++ const onChange = (event: MediaQueryListEvent) => setSystemDark(event.matches) + +- root.classList.remove("light", "dark") ++ media.addEventListener("change", onChange) ++ return () => media.removeEventListener("change", onChange) ++ }, []) + +- if (theme === "system") { +- const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" ++ const resolvedTheme = theme === "system" ? (systemDark ? "dark" : "light") : theme + +- root.classList.add(systemTheme) +- return +- } ++ useEffect(() => { ++ const root = window.document.documentElement + +- root.classList.add(theme) +- }, [theme]) ++ root.classList.remove("light", "dark") ++ root.classList.add(resolvedTheme) ++ }, [resolvedTheme]) + + const value = { + theme, ++ resolvedTheme, + setTheme: (theme: Theme) => { + localStorage.setItem(storageKey, theme) + setTheme(theme) diff --git a/tasks/henrygd__beszel-2328/tests/test.sh b/tasks/henrygd__beszel-2328/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c70649546468b7abfc4786362d83548960d08e2f --- /dev/null +++ b/tasks/henrygd__beszel-2328/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 f204dc17e64bba444478c60210d018e43a777193 > "$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/henrygd__beszel-2328/tests/verifier.py b/tasks/henrygd__beszel-2328/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2328/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/henrygd__beszel-2329/environment/Dockerfile b/tasks/henrygd__beszel-2329/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4f11b8e50ae0eae7d72315785f9858db39e5c5cc --- /dev/null +++ b/tasks/henrygd__beszel-2329/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b3feff9a28273c7b2f74dd0c0fdc834c295ae4d7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b3feff9a28273c7b2f74dd0c0fdc834c295ae4d7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b3feff9a28273c7b2f74dd0c0fdc834c295ae4d7 \ + && 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/henrygd__beszel-2329/instruction.md b/tasks/henrygd__beszel-2329/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..815777615568ad13000712bb1ab6e6806a3d07ab --- /dev/null +++ b/tasks/henrygd__beszel-2329/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** fix(agent): keep reconnecting after an async WebSocket handshake failure + +## Description + +## 📃 Description + +Fixes a bug where the agent could freeze permanently in the disconnected state and never reconnect to the hub, requiring a manual restart to recover (#2326). The freeze happened when a WebSocket handshake failed *asynchronously* — after `connect()` had already returned `nil` but before auth completed — leaving the reconnect ticker stopped with nothing left to trigger another attempt. + +While fixing this, also closed a data race on the connection manager's internal state (`State`/`isConnecting`), which were read and written from both the main event loop and the async reconnect goroutine without synchronization, and bumped `gws` to fix a related goroutine leak on timed-out handshakes. + +## 📖 Documentation + +N/A — no user-facing behavior or configuration changes. + +## 🪵 Changelog + +### 🔧 Fixed + +- Agent no longer freezes permanently after a WebSocket handshake fails asynchronously while disconnected — the reconnect ticker is now always re-armed on entering the `Disconnected` state () +- Fixed a data race on the connection manager's `State`/`isConnecting` fields, guarded now with a mutex, that could otherwise corrupt reconnect-loop state under concurrent access + + +## 📷 Screenshots + +N/A — backend-only change, no UI/UX impact. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b3feff9a2827`. 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/henrygd__beszel-2329/solution/patch.diff b/tasks/henrygd__beszel-2329/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..710ed343e06f288cf3ce652ad59abdcda66118b2 --- /dev/null +++ b/tasks/henrygd__beszel-2329/solution/patch.diff @@ -0,0 +1,272 @@ +diff --git a/agent/connection_manager.go b/agent/connection_manager.go +index 8152817e..3527c796 100644 +--- a/agent/connection_manager.go ++++ b/agent/connection_manager.go +@@ -8,6 +8,7 @@ import ( + "os" + "os/signal" + "strings" ++ "sync" + "syscall" + "time" + +@@ -20,7 +21,10 @@ import ( + // It handles both WebSocket and SSH connections, automatically switching between + // them based on availability and managing reconnection attempts. + type ConnectionManager struct { +- agent *Agent // Reference to the parent agent ++ agent *Agent // Reference to the parent agent ++ // mu guards State and isConnecting, which are read and written from both ++ // the main event loop and the goroutine spawned by connect(). ++ mu sync.Mutex + State ConnectionState // Current connection state + eventChan chan ConnectionEvent // Channel for connection events + wsClient *WebSocketClient // WebSocket client for hub communication +@@ -78,6 +82,29 @@ func (c *ConnectionManager) stopWsTicker() { + } + } + ++// getState returns the current connection state. ++func (c *ConnectionManager) getState() ConnectionState { ++ c.mu.Lock() ++ defer c.mu.Unlock() ++ return c.State ++} ++ ++// setConnecting sets the isConnecting flag and reports its previous value. ++func (c *ConnectionManager) setConnecting(v bool) (previous bool) { ++ c.mu.Lock() ++ defer c.mu.Unlock() ++ previous = c.isConnecting ++ c.isConnecting = v ++ return previous ++} ++ ++// isConnectingNow reports whether a reconnection attempt is currently in flight. ++func (c *ConnectionManager) isConnectingNow() bool { ++ c.mu.Lock() ++ defer c.mu.Unlock() ++ return c.isConnecting ++} ++ + // Start begins connection attempts and enters the main event loop. + // It handles connection events, periodic health updates, and graceful shutdown. + func (c *ConnectionManager) Start(serverOptions ServerOptions) error { +@@ -122,7 +149,10 @@ func (c *ConnectionManager) Start(serverOptions ServerOptions) error { + case connectionEvent := <-c.eventChan: + c.handleEvent(connectionEvent) + case <-c.wsTicker.C: +- _ = c.startWebSocketConnection() ++ // skip if connect() is still running its own attempt ++ if !c.isConnectingNow() { ++ _ = c.startWebSocketConnection() ++ } + case <-healthTicker: + _ = health.Update() + case <-sigCtx.Done(): +@@ -165,15 +195,15 @@ func (c *ConnectionManager) handleEvent(event ConnectionEvent) { + case WebSocketConnect: + c.handleStateChange(WebSocketConnected) + case SSHConnect: +- if c.State == Disconnected { ++ if c.getState() == Disconnected { + c.handleStateChange(SSHConnected) + } + case WebSocketDisconnect: +- if c.State == WebSocketConnected { ++ if c.getState() == WebSocketConnected { + c.handleStateChange(Disconnected) + } + case SSHDisconnect: +- if c.State == SSHConnected { ++ if c.getState() == SSHConnected { + c.handleStateChange(Disconnected) + } + } +@@ -182,30 +212,40 @@ func (c *ConnectionManager) handleEvent(event ConnectionEvent) { + // handleStateChange updates the connection state and performs necessary actions + // based on the new state, including stopping services and initiating reconnections. + func (c *ConnectionManager) handleStateChange(newState ConnectionState) { ++ c.mu.Lock() + if c.State == newState { ++ c.mu.Unlock() + return + } + c.State = newState ++ c.mu.Unlock() ++ + switch newState { + case WebSocketConnected: + slog.Info("WebSocket connected", "host", c.wsClient.hubURL.Host) + c.ConnectionType = system.ConnectionTypeWebSocket + c.stopWsTicker() + _ = c.agent.StopServer() +- c.isConnecting = false ++ c.setConnecting(false) + case SSHConnected: + // stop new ws connection attempts + slog.Info("SSH connection established") + c.ConnectionType = system.ConnectionTypeSSH + c.stopWsTicker() +- c.isConnecting = false ++ c.setConnecting(false) + case Disconnected: + c.ConnectionType = system.ConnectionTypeNone +- if c.isConnecting { ++ // Always keep the ticker running while disconnected. A pending WebSocket ++ // handshake started by connect() can fail asynchronously (e.g. the hub ++ // closes the socket, or the deadline set in OnOpen expires) after ++ // connect() has already returned with a nil error, in which case the ++ // ticker would otherwise never get re-armed and the agent would stop ++ // retrying entirely (#2326). ++ c.startWsTicker() ++ if c.setConnecting(true) { + // Already handling reconnection, avoid duplicate attempts + return + } +- c.isConnecting = true + slog.Warn("Disconnected from hub") + // make sure old ws connection is closed + c.closeWebSocket() +@@ -217,10 +257,8 @@ func (c *ConnectionManager) handleStateChange(newState ConnectionState) { + // connect handles the connection logic with proper delays and priority. + // It attempts WebSocket connection first, falling back to SSH server if needed. + func (c *ConnectionManager) connect() { +- c.isConnecting = true +- defer func() { +- c.isConnecting = false +- }() ++ c.setConnecting(true) ++ defer c.setConnecting(false) + + if c.wsClient != nil && time.Since(c.wsClient.lastConnectAttempt) < 5*time.Second { + time.Sleep(5 * time.Second) +@@ -234,7 +272,7 @@ func (c *ConnectionManager) connect() { + _ = c.stop() + os.Exit(1) + } +- if c.State == Disconnected { ++ if c.getState() == Disconnected { + c.startSSHServer() + c.startWsTicker() + } +@@ -243,7 +281,7 @@ func (c *ConnectionManager) connect() { + + // startWebSocketConnection attempts to establish a WebSocket connection to the hub. + func (c *ConnectionManager) startWebSocketConnection() error { +- if c.State != Disconnected { ++ if c.getState() != Disconnected { + return errors.New("already connected") + } + if c.wsClient == nil { +@@ -263,7 +301,7 @@ func (c *ConnectionManager) startWebSocketConnection() error { + + // startSSHServer starts the SSH server if the agent is currently disconnected. + func (c *ConnectionManager) startSSHServer() { +- if c.State == Disconnected { ++ if c.getState() == Disconnected { + go c.agent.StartServer(c.serverOptions) + } + } +diff --git a/agent/connection_manager_test.go b/agent/connection_manager_test.go +index ef9222bd..4a00c7d6 100644 +--- a/agent/connection_manager_test.go ++++ b/agent/connection_manager_test.go +@@ -9,6 +9,7 @@ import ( + "net" + "net/url" + "testing" ++ "testing/synctest" + "time" + + "github.com/stretchr/testify/assert" +@@ -77,6 +78,10 @@ func TestConnectionManager_StateTransitions(t *testing.T) { + cm.handleStateChange(SSHConnected) + assert.Equal(t, SSHConnected, cm.State, "State should change to SSHConnected") + ++ // Prevent handleStateChange from spawning its async reconnect goroutine: ++ // this test only checks the synchronous state machine, and the goroutine ++ // would otherwise race with the direct field writes below. ++ cm.setConnecting(true) + cm.handleStateChange(Disconnected) + assert.Equal(t, Disconnected, cm.State, "State should change to Disconnected") + +@@ -95,7 +100,6 @@ func TestConnectionManager_EventHandling(t *testing.T) { + Host: "localhost:8080", + }, + } +- + testCases := []struct { + name string + initialState ConnectionState +@@ -148,6 +152,11 @@ func TestConnectionManager_EventHandling(t *testing.T) { + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { ++ // Prevent handleStateChange from spawning its async reconnect ++ // goroutine: this test only checks the synchronous state machine, ++ // and the goroutine would otherwise race with the direct field ++ // writes here and in later subtests. ++ cm.setConnecting(true) + cm.State = tc.initialState + cm.handleEvent(tc.event) + assert.Equal(t, tc.expectedState, cm.State, "State should match expected after event") +@@ -221,12 +230,56 @@ func TestConnectionManager_ReconnectionLogic(t *testing.T) { + // Test that isConnecting flag prevents duplicate reconnection attempts + // Start from connected state, then simulate disconnect + cm.State = WebSocketConnected +- cm.isConnecting = false ++ cm.setConnecting(false) + + // First disconnect should trigger reconnection logic + cm.handleStateChange(Disconnected) + assert.Equal(t, Disconnected, cm.State, "Should change to disconnected") +- assert.True(t, cm.isConnecting, "Should set isConnecting flag") ++ assert.True(t, cm.isConnectingNow(), "Should set isConnecting flag") ++} ++ ++// TestConnectionManager_TickerSurvivesStaleDisconnect reproduces the freeze from ++// https://github.com/henrygd/beszel/issues/2326: a reconnect attempt's handshake ++// can fail asynchronously (after connect() already returned with a nil error) ++// while the manager is still in the Disconnected state. Previously the ticker ++// was only re-armed from connect()'s synchronous error branch, so once that ++// window was missed, the agent stopped retrying forever. The ticker must keep ++// running any time the manager transitions into Disconnected, regardless of ++// what happens to the in-flight handshake afterwards. ++func TestConnectionManager_TickerSurvivesStaleDisconnect(t *testing.T) { ++ agent := createTestAgent(t) ++ cm := agent.connectionManager ++ cm.eventChan = make(chan ConnectionEvent, 1) ++ ++ // Run on synctest's fake clock so the ticker fires without waiting a real ++ // wsTickerInterval. The ticker must be created inside the bubble. ++ synctest.Test(t, func(t *testing.T) { ++ // Simulate a healthy WebSocket connection, then a disconnect - mirroring ++ // handleStateChange's own Disconnected branch, but without launching the ++ // real async connect() goroutine so the ticker state can be asserted ++ // deterministically. ++ cm.State = WebSocketConnected ++ cm.stopWsTicker() ++ cm.setConnecting(true) ++ cm.handleStateChange(Disconnected) ++ require.NotNil(t, cm.wsTicker, "ticker must be armed as soon as the manager becomes Disconnected") ++ defer cm.stopWsTicker() ++ ++ // Now simulate connect()'s in-flight handshake dying asynchronously with the ++ // manager still Disconnected (e.g. a late OnClose on an unauthenticated ++ // connection). This event is dropped by handleEvent since State is not ++ // WebSocketConnected, but the ticker armed above must still be running so ++ // the manager keeps retrying. ++ cm.setConnecting(false) ++ cm.handleEvent(WebSocketDisconnect) ++ assert.Equal(t, Disconnected, cm.State) ++ ++ select { ++ case <-cm.wsTicker.C: ++ case <-time.After(wsTickerInterval + 2*time.Second): ++ t.Fatal("ticker did not fire after a stale disconnect event - agent would freeze forever") ++ } ++ }) + } + + // TestConnectionManager_ConnectWithRateLimit tests connection rate limiting diff --git a/tasks/henrygd__beszel-2329/solution/solve.sh b/tasks/henrygd__beszel-2329/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2329/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/henrygd__beszel-2329/task.toml b/tasks/henrygd__beszel-2329/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..df3fdaae8de954ffc5d94d9f414ccde60f5fc6c7 --- /dev/null +++ b/tasks/henrygd__beszel-2329/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2329" +description = "fix(agent): keep reconnecting after an async WebSocket handshake failure (#2326)" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "b3feff9a28273c7b2f74dd0c0fdc834c295ae4d7" +reference = "https://github.com/henrygd/beszel/pull/2329" +source_access = "auto" +built_at = "2026-11-16T16:09:53.476378+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:873e0fa14a54124c138431f16f287355f532923e4d81f83638fd3aab039c1c58" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-26T17:30:53Z" +diff_format = "unified" +context_files = [ + "agent/connection_manager.go", + "agent/connection_manager_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 129 +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:00.814206+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8dba5ad7aade85976050acf74853e370a7f62ac9a2eee32f6335a46003e39258" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2329/tests/capture.py b/tasks/henrygd__beszel-2329/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2329/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/henrygd__beszel-2329/tests/instruction.md b/tasks/henrygd__beszel-2329/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..815777615568ad13000712bb1ab6e6806a3d07ab --- /dev/null +++ b/tasks/henrygd__beszel-2329/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** fix(agent): keep reconnecting after an async WebSocket handshake failure + +## Description + +## 📃 Description + +Fixes a bug where the agent could freeze permanently in the disconnected state and never reconnect to the hub, requiring a manual restart to recover (#2326). The freeze happened when a WebSocket handshake failed *asynchronously* — after `connect()` had already returned `nil` but before auth completed — leaving the reconnect ticker stopped with nothing left to trigger another attempt. + +While fixing this, also closed a data race on the connection manager's internal state (`State`/`isConnecting`), which were read and written from both the main event loop and the async reconnect goroutine without synchronization, and bumped `gws` to fix a related goroutine leak on timed-out handshakes. + +## 📖 Documentation + +N/A — no user-facing behavior or configuration changes. + +## 🪵 Changelog + +### 🔧 Fixed + +- Agent no longer freezes permanently after a WebSocket handshake fails asynchronously while disconnected — the reconnect ticker is now always re-armed on entering the `Disconnected` state () +- Fixed a data race on the connection manager's `State`/`isConnecting` fields, guarded now with a mutex, that could otherwise corrupt reconnect-loop state under concurrent access + + +## 📷 Screenshots + +N/A — backend-only change, no UI/UX impact. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b3feff9a2827`. 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/henrygd__beszel-2329/tests/oracle.patch b/tasks/henrygd__beszel-2329/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..710ed343e06f288cf3ce652ad59abdcda66118b2 --- /dev/null +++ b/tasks/henrygd__beszel-2329/tests/oracle.patch @@ -0,0 +1,272 @@ +diff --git a/agent/connection_manager.go b/agent/connection_manager.go +index 8152817e..3527c796 100644 +--- a/agent/connection_manager.go ++++ b/agent/connection_manager.go +@@ -8,6 +8,7 @@ import ( + "os" + "os/signal" + "strings" ++ "sync" + "syscall" + "time" + +@@ -20,7 +21,10 @@ import ( + // It handles both WebSocket and SSH connections, automatically switching between + // them based on availability and managing reconnection attempts. + type ConnectionManager struct { +- agent *Agent // Reference to the parent agent ++ agent *Agent // Reference to the parent agent ++ // mu guards State and isConnecting, which are read and written from both ++ // the main event loop and the goroutine spawned by connect(). ++ mu sync.Mutex + State ConnectionState // Current connection state + eventChan chan ConnectionEvent // Channel for connection events + wsClient *WebSocketClient // WebSocket client for hub communication +@@ -78,6 +82,29 @@ func (c *ConnectionManager) stopWsTicker() { + } + } + ++// getState returns the current connection state. ++func (c *ConnectionManager) getState() ConnectionState { ++ c.mu.Lock() ++ defer c.mu.Unlock() ++ return c.State ++} ++ ++// setConnecting sets the isConnecting flag and reports its previous value. ++func (c *ConnectionManager) setConnecting(v bool) (previous bool) { ++ c.mu.Lock() ++ defer c.mu.Unlock() ++ previous = c.isConnecting ++ c.isConnecting = v ++ return previous ++} ++ ++// isConnectingNow reports whether a reconnection attempt is currently in flight. ++func (c *ConnectionManager) isConnectingNow() bool { ++ c.mu.Lock() ++ defer c.mu.Unlock() ++ return c.isConnecting ++} ++ + // Start begins connection attempts and enters the main event loop. + // It handles connection events, periodic health updates, and graceful shutdown. + func (c *ConnectionManager) Start(serverOptions ServerOptions) error { +@@ -122,7 +149,10 @@ func (c *ConnectionManager) Start(serverOptions ServerOptions) error { + case connectionEvent := <-c.eventChan: + c.handleEvent(connectionEvent) + case <-c.wsTicker.C: +- _ = c.startWebSocketConnection() ++ // skip if connect() is still running its own attempt ++ if !c.isConnectingNow() { ++ _ = c.startWebSocketConnection() ++ } + case <-healthTicker: + _ = health.Update() + case <-sigCtx.Done(): +@@ -165,15 +195,15 @@ func (c *ConnectionManager) handleEvent(event ConnectionEvent) { + case WebSocketConnect: + c.handleStateChange(WebSocketConnected) + case SSHConnect: +- if c.State == Disconnected { ++ if c.getState() == Disconnected { + c.handleStateChange(SSHConnected) + } + case WebSocketDisconnect: +- if c.State == WebSocketConnected { ++ if c.getState() == WebSocketConnected { + c.handleStateChange(Disconnected) + } + case SSHDisconnect: +- if c.State == SSHConnected { ++ if c.getState() == SSHConnected { + c.handleStateChange(Disconnected) + } + } +@@ -182,30 +212,40 @@ func (c *ConnectionManager) handleEvent(event ConnectionEvent) { + // handleStateChange updates the connection state and performs necessary actions + // based on the new state, including stopping services and initiating reconnections. + func (c *ConnectionManager) handleStateChange(newState ConnectionState) { ++ c.mu.Lock() + if c.State == newState { ++ c.mu.Unlock() + return + } + c.State = newState ++ c.mu.Unlock() ++ + switch newState { + case WebSocketConnected: + slog.Info("WebSocket connected", "host", c.wsClient.hubURL.Host) + c.ConnectionType = system.ConnectionTypeWebSocket + c.stopWsTicker() + _ = c.agent.StopServer() +- c.isConnecting = false ++ c.setConnecting(false) + case SSHConnected: + // stop new ws connection attempts + slog.Info("SSH connection established") + c.ConnectionType = system.ConnectionTypeSSH + c.stopWsTicker() +- c.isConnecting = false ++ c.setConnecting(false) + case Disconnected: + c.ConnectionType = system.ConnectionTypeNone +- if c.isConnecting { ++ // Always keep the ticker running while disconnected. A pending WebSocket ++ // handshake started by connect() can fail asynchronously (e.g. the hub ++ // closes the socket, or the deadline set in OnOpen expires) after ++ // connect() has already returned with a nil error, in which case the ++ // ticker would otherwise never get re-armed and the agent would stop ++ // retrying entirely (#2326). ++ c.startWsTicker() ++ if c.setConnecting(true) { + // Already handling reconnection, avoid duplicate attempts + return + } +- c.isConnecting = true + slog.Warn("Disconnected from hub") + // make sure old ws connection is closed + c.closeWebSocket() +@@ -217,10 +257,8 @@ func (c *ConnectionManager) handleStateChange(newState ConnectionState) { + // connect handles the connection logic with proper delays and priority. + // It attempts WebSocket connection first, falling back to SSH server if needed. + func (c *ConnectionManager) connect() { +- c.isConnecting = true +- defer func() { +- c.isConnecting = false +- }() ++ c.setConnecting(true) ++ defer c.setConnecting(false) + + if c.wsClient != nil && time.Since(c.wsClient.lastConnectAttempt) < 5*time.Second { + time.Sleep(5 * time.Second) +@@ -234,7 +272,7 @@ func (c *ConnectionManager) connect() { + _ = c.stop() + os.Exit(1) + } +- if c.State == Disconnected { ++ if c.getState() == Disconnected { + c.startSSHServer() + c.startWsTicker() + } +@@ -243,7 +281,7 @@ func (c *ConnectionManager) connect() { + + // startWebSocketConnection attempts to establish a WebSocket connection to the hub. + func (c *ConnectionManager) startWebSocketConnection() error { +- if c.State != Disconnected { ++ if c.getState() != Disconnected { + return errors.New("already connected") + } + if c.wsClient == nil { +@@ -263,7 +301,7 @@ func (c *ConnectionManager) startWebSocketConnection() error { + + // startSSHServer starts the SSH server if the agent is currently disconnected. + func (c *ConnectionManager) startSSHServer() { +- if c.State == Disconnected { ++ if c.getState() == Disconnected { + go c.agent.StartServer(c.serverOptions) + } + } +diff --git a/agent/connection_manager_test.go b/agent/connection_manager_test.go +index ef9222bd..4a00c7d6 100644 +--- a/agent/connection_manager_test.go ++++ b/agent/connection_manager_test.go +@@ -9,6 +9,7 @@ import ( + "net" + "net/url" + "testing" ++ "testing/synctest" + "time" + + "github.com/stretchr/testify/assert" +@@ -77,6 +78,10 @@ func TestConnectionManager_StateTransitions(t *testing.T) { + cm.handleStateChange(SSHConnected) + assert.Equal(t, SSHConnected, cm.State, "State should change to SSHConnected") + ++ // Prevent handleStateChange from spawning its async reconnect goroutine: ++ // this test only checks the synchronous state machine, and the goroutine ++ // would otherwise race with the direct field writes below. ++ cm.setConnecting(true) + cm.handleStateChange(Disconnected) + assert.Equal(t, Disconnected, cm.State, "State should change to Disconnected") + +@@ -95,7 +100,6 @@ func TestConnectionManager_EventHandling(t *testing.T) { + Host: "localhost:8080", + }, + } +- + testCases := []struct { + name string + initialState ConnectionState +@@ -148,6 +152,11 @@ func TestConnectionManager_EventHandling(t *testing.T) { + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { ++ // Prevent handleStateChange from spawning its async reconnect ++ // goroutine: this test only checks the synchronous state machine, ++ // and the goroutine would otherwise race with the direct field ++ // writes here and in later subtests. ++ cm.setConnecting(true) + cm.State = tc.initialState + cm.handleEvent(tc.event) + assert.Equal(t, tc.expectedState, cm.State, "State should match expected after event") +@@ -221,12 +230,56 @@ func TestConnectionManager_ReconnectionLogic(t *testing.T) { + // Test that isConnecting flag prevents duplicate reconnection attempts + // Start from connected state, then simulate disconnect + cm.State = WebSocketConnected +- cm.isConnecting = false ++ cm.setConnecting(false) + + // First disconnect should trigger reconnection logic + cm.handleStateChange(Disconnected) + assert.Equal(t, Disconnected, cm.State, "Should change to disconnected") +- assert.True(t, cm.isConnecting, "Should set isConnecting flag") ++ assert.True(t, cm.isConnectingNow(), "Should set isConnecting flag") ++} ++ ++// TestConnectionManager_TickerSurvivesStaleDisconnect reproduces the freeze from ++// https://github.com/henrygd/beszel/issues/2326: a reconnect attempt's handshake ++// can fail asynchronously (after connect() already returned with a nil error) ++// while the manager is still in the Disconnected state. Previously the ticker ++// was only re-armed from connect()'s synchronous error branch, so once that ++// window was missed, the agent stopped retrying forever. The ticker must keep ++// running any time the manager transitions into Disconnected, regardless of ++// what happens to the in-flight handshake afterwards. ++func TestConnectionManager_TickerSurvivesStaleDisconnect(t *testing.T) { ++ agent := createTestAgent(t) ++ cm := agent.connectionManager ++ cm.eventChan = make(chan ConnectionEvent, 1) ++ ++ // Run on synctest's fake clock so the ticker fires without waiting a real ++ // wsTickerInterval. The ticker must be created inside the bubble. ++ synctest.Test(t, func(t *testing.T) { ++ // Simulate a healthy WebSocket connection, then a disconnect - mirroring ++ // handleStateChange's own Disconnected branch, but without launching the ++ // real async connect() goroutine so the ticker state can be asserted ++ // deterministically. ++ cm.State = WebSocketConnected ++ cm.stopWsTicker() ++ cm.setConnecting(true) ++ cm.handleStateChange(Disconnected) ++ require.NotNil(t, cm.wsTicker, "ticker must be armed as soon as the manager becomes Disconnected") ++ defer cm.stopWsTicker() ++ ++ // Now simulate connect()'s in-flight handshake dying asynchronously with the ++ // manager still Disconnected (e.g. a late OnClose on an unauthenticated ++ // connection). This event is dropped by handleEvent since State is not ++ // WebSocketConnected, but the ticker armed above must still be running so ++ // the manager keeps retrying. ++ cm.setConnecting(false) ++ cm.handleEvent(WebSocketDisconnect) ++ assert.Equal(t, Disconnected, cm.State) ++ ++ select { ++ case <-cm.wsTicker.C: ++ case <-time.After(wsTickerInterval + 2*time.Second): ++ t.Fatal("ticker did not fire after a stale disconnect event - agent would freeze forever") ++ } ++ }) + } + + // TestConnectionManager_ConnectWithRateLimit tests connection rate limiting diff --git a/tasks/henrygd__beszel-2329/tests/test.sh b/tasks/henrygd__beszel-2329/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c80928ff46df50738ce258c1f296b93b1027f755 --- /dev/null +++ b/tasks/henrygd__beszel-2329/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 b3feff9a28273c7b2f74dd0c0fdc834c295ae4d7 > "$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/henrygd__beszel-2329/tests/verifier.py b/tasks/henrygd__beszel-2329/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2329/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/henrygd__beszel-2333/environment/Dockerfile b/tasks/henrygd__beszel-2333/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d752dce0935b34577b4b65278369f1327c7d0520 --- /dev/null +++ b/tasks/henrygd__beszel-2333/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f204dc17e64bba444478c60210d018e43a777193 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f204dc17e64bba444478c60210d018e43a777193 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f204dc17e64bba444478c60210d018e43a777193 \ + && 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/henrygd__beszel-2333/instruction.md b/tasks/henrygd__beszel-2333/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8be1d8d7bd5a66830eb4fc0db4074572c96bd94e --- /dev/null +++ b/tasks/henrygd__beszel-2333/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** fix(site): discard pending history when switching to live charts + +## Description + +Switching to the 1-minute live chart while a historical request is pending can replace live points with old data when that request finishes. The effect returns before incrementing the request ID, so the previous response still passes the stale-request check. Moving the increment above the early return invalidates it when entering live mode too. + +Reproduced in Chromium using the actual hook and controlled PocketBase responses: hold a 1-hour request, switch to 1 minute, deliver a live CPU sample of 20%, then complete the historical request with a 30-minute-old sample of 81%. The original code replaces 20% with 81%; this change keeps 20%. These are sample responses, without a running hub or agent. + +The browser regression check, Biome check, catalog compilation, and Vite production build pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f204dc17e64b`. 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/henrygd__beszel-2333/solution/patch.diff b/tasks/henrygd__beszel-2333/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..496145925b2d08bcaf0901f610a5f55432a33064 --- /dev/null +++ b/tasks/henrygd__beszel-2333/solution/patch.diff @@ -0,0 +1,29 @@ +diff --git a/internal/site/src/components/routes/system/use-system-data.ts b/internal/site/src/components/routes/system/use-system-data.ts +index c83d2dff..ef143637 100644 +--- a/internal/site/src/components/routes/system/use-system-data.ts ++++ b/internal/site/src/components/routes/system/use-system-data.ts +@@ -171,6 +171,7 @@ export function useSystemData(id: string) { + // get stats when system "changes." (Not just system to system, + // also when new info comes in via systemManager realtime connection, indicating an update) + useEffect(() => { ++ const requestId = ++statsRequestId.current + if (!system.id || !chartTime || chartTime === "1m") { + return + } +@@ -179,7 +180,6 @@ export function useSystemData(id: string) { + const { expectedInterval } = chartTimeData[chartTime] + const ss_cache_key = `${systemId}_${chartTime}_system_stats` + const cs_cache_key = `${systemId}_${chartTime}_container_stats` +- const requestId = ++statsRequestId.current + + const cachedSystemStats = cache.get(ss_cache_key) as SystemStatsRecord[] | undefined + const cachedContainerData = cache.get(cs_cache_key) as ChartData["containerData"] | undefined +@@ -203,7 +203,7 @@ export function useSystemData(id: string) { + getStats("system_stats", systemId, chartTime), + getStats("container_stats", systemId, chartTime), + ]).then(([systemStats, containerStats]) => { +- // If another request has been made since this one, ignore the results ++ // Ignore responses for a previous system or chart time + if (requestId !== statsRequestId.current) { + return + } diff --git a/tasks/henrygd__beszel-2333/solution/solve.sh b/tasks/henrygd__beszel-2333/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2333/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/henrygd__beszel-2333/task.toml b/tasks/henrygd__beszel-2333/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7e31d4ef5760aaf628c13eb54ee31e359cc16f22 --- /dev/null +++ b/tasks/henrygd__beszel-2333/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2333" +description = "fix(site): discard pending history when switching to live charts" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "f204dc17e64bba444478c60210d018e43a777193" +reference = "https://github.com/henrygd/beszel/pull/2333" +source_access = "auto" +built_at = "2026-11-16T16:09:53.501923+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:903fbaf10f27c9e34ff09960f92f066feb25be1e2cec18b31c354fb6e53efec5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-13T16:32:05Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/routes/system/use-system-data.ts", +] +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:00.814662+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7a89109ade77bcfb74ec05d73b3c5fb6a7e28fc437ddbbcba3529ffab8fd2680" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2333/tests/capture.py b/tasks/henrygd__beszel-2333/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2333/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/henrygd__beszel-2333/tests/instruction.md b/tasks/henrygd__beszel-2333/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8be1d8d7bd5a66830eb4fc0db4074572c96bd94e --- /dev/null +++ b/tasks/henrygd__beszel-2333/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** fix(site): discard pending history when switching to live charts + +## Description + +Switching to the 1-minute live chart while a historical request is pending can replace live points with old data when that request finishes. The effect returns before incrementing the request ID, so the previous response still passes the stale-request check. Moving the increment above the early return invalidates it when entering live mode too. + +Reproduced in Chromium using the actual hook and controlled PocketBase responses: hold a 1-hour request, switch to 1 minute, deliver a live CPU sample of 20%, then complete the historical request with a 30-minute-old sample of 81%. The original code replaces 20% with 81%; this change keeps 20%. These are sample responses, without a running hub or agent. + +The browser regression check, Biome check, catalog compilation, and Vite production build pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f204dc17e64b`. 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/henrygd__beszel-2333/tests/oracle.patch b/tasks/henrygd__beszel-2333/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..496145925b2d08bcaf0901f610a5f55432a33064 --- /dev/null +++ b/tasks/henrygd__beszel-2333/tests/oracle.patch @@ -0,0 +1,29 @@ +diff --git a/internal/site/src/components/routes/system/use-system-data.ts b/internal/site/src/components/routes/system/use-system-data.ts +index c83d2dff..ef143637 100644 +--- a/internal/site/src/components/routes/system/use-system-data.ts ++++ b/internal/site/src/components/routes/system/use-system-data.ts +@@ -171,6 +171,7 @@ export function useSystemData(id: string) { + // get stats when system "changes." (Not just system to system, + // also when new info comes in via systemManager realtime connection, indicating an update) + useEffect(() => { ++ const requestId = ++statsRequestId.current + if (!system.id || !chartTime || chartTime === "1m") { + return + } +@@ -179,7 +180,6 @@ export function useSystemData(id: string) { + const { expectedInterval } = chartTimeData[chartTime] + const ss_cache_key = `${systemId}_${chartTime}_system_stats` + const cs_cache_key = `${systemId}_${chartTime}_container_stats` +- const requestId = ++statsRequestId.current + + const cachedSystemStats = cache.get(ss_cache_key) as SystemStatsRecord[] | undefined + const cachedContainerData = cache.get(cs_cache_key) as ChartData["containerData"] | undefined +@@ -203,7 +203,7 @@ export function useSystemData(id: string) { + getStats("system_stats", systemId, chartTime), + getStats("container_stats", systemId, chartTime), + ]).then(([systemStats, containerStats]) => { +- // If another request has been made since this one, ignore the results ++ // Ignore responses for a previous system or chart time + if (requestId !== statsRequestId.current) { + return + } diff --git a/tasks/henrygd__beszel-2333/tests/test.sh b/tasks/henrygd__beszel-2333/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c70649546468b7abfc4786362d83548960d08e2f --- /dev/null +++ b/tasks/henrygd__beszel-2333/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 f204dc17e64bba444478c60210d018e43a777193 > "$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/henrygd__beszel-2333/tests/verifier.py b/tasks/henrygd__beszel-2333/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2333/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/henrygd__beszel-2340/environment/Dockerfile b/tasks/henrygd__beszel-2340/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b1295d2c4e82d56f4212ffc5243f7288991d5b4f --- /dev/null +++ b/tasks/henrygd__beszel-2340/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1997984325de5057bee0bd5b309fa534dac5d639 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1997984325de5057bee0bd5b309fa534dac5d639 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1997984325de5057bee0bd5b309fa534dac5d639 \ + && 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/henrygd__beszel-2340/instruction.md b/tasks/henrygd__beszel-2340/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c61a4a962dab9833bca2f25a9ddec1d6a4f86c17 --- /dev/null +++ b/tasks/henrygd__beszel-2340/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(agent): handle partial NVMe SMART data + +## Description + +## 📃 Description + +Fix NVMe SMART parsing by rejecting partial smartctl responses that contain device identity but no health log. This prevents misleading zero values and allows the existing namespace-path fallback to query /dev/nvmeXn1. + +## 📷 Screenshots + +Before +1 + +After +2 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1997984325de`. 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/henrygd__beszel-2340/solution/patch.diff b/tasks/henrygd__beszel-2340/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..eb95e9f75014776fc3576f9ca74858906cc0a9fa --- /dev/null +++ b/tasks/henrygd__beszel-2340/solution/patch.diff @@ -0,0 +1,144 @@ +diff --git a/agent/smart.go b/agent/smart.go +index 28a5ad81..3490e7fb 100644 +--- a/agent/smart.go ++++ b/agent/smart.go +@@ -311,11 +311,13 @@ func (sm *SmartManager) filterExcludedDevices(devices []*DeviceInfo) []*DeviceIn + return filtered + } + +-// detectSmartOutputType inspects sections that are unique to each smartctl +-// JSON schema (NVMe, ATA/SATA, SCSI) to determine which parser should be used +-// when the reported device type is ambiguous or missing. ++// detectSmartOutputType inspects protocol-specific sections and the reported ++// device type to choose a parser, including when the NVMe health log is missing. + func detectSmartOutputType(output []byte) string { + var hints struct { ++ Device struct { ++ Type string `json:"type"` ++ } `json:"device"` + AtaSmartAttributes json.RawMessage `json:"ata_smart_attributes"` + NVMeSmartHealthInformationLog json.RawMessage `json:"nvme_smart_health_information_log"` + ScsiErrorCounterLog json.RawMessage `json:"scsi_error_counter_log"` +@@ -326,7 +328,7 @@ func detectSmartOutputType(output []byte) string { + } + + switch { +- case hasJSONValue(hints.NVMeSmartHealthInformationLog): ++ case hasJSONValue(hints.NVMeSmartHealthInformationLog), normalizeParserType(hints.Device.Type) == "nvme": + return "nvme" + case hasJSONValue(hints.AtaSmartAttributes): + return "sat" +@@ -397,11 +399,11 @@ func (sm *SmartManager) parseSmartOutput(deviceInfo *DeviceInfo, output []byte) + } + } + +- // Only run the type detection when we do not yet know which parser works +- // or the previous attempt failed. ++ // Inspect every response so a failed NVMe query cannot reach other parsers. ++ structureType := detectSmartOutputType(output) ++ // Update the stored parser only when it is not yet verified. + needsDetection := deviceType == "" || !deviceInfo.typeVerified + if needsDetection { +- structureType := detectSmartOutputType(output) + if deviceType != structureType { + deviceType = structureType + deviceInfo.parserType = structureType +@@ -442,6 +444,11 @@ func (sm *SmartManager) parseSmartOutput(deviceInfo *DeviceInfo, output []byte) + + // Try the selected parsers in order until we find one that succeeds. + for _, parser := range selectedParsers { ++ // A failed NVMe response may still contain a serial number, which is ++ // enough for the SATA and SCSI parsers to accept incorrect zero values. ++ if structureType == "nvme" && parser.Type != "nvme" { ++ continue ++ } + hasData, _ := parser.Parse(output) + if hasData { + deviceInfo.parserType = parser.Type +@@ -1145,6 +1152,16 @@ func (sm *SmartManager) parseSmartForNvme(output []byte, deviceType string) (boo + return false, data.Smartctl.ExitStatus + } + ++ // smartctl may return device identity fields before failing to read the NVMe ++ // health log (for example, on an unsupported controller path or with insufficient ++ // permissions). Do not accept that partial response as valid SMART data: doing ++ // so stores incorrect zero values and prevents the namespace-path fallback. ++ log := data.NVMeSmartHealthInformationLog ++ if log == nil { ++ slog.Debug("no NVMe SMART health information", "device", data.Device.Name) ++ return false, data.Smartctl.ExitStatus ++ } ++ + sm.Lock() + defer sm.Unlock() + +@@ -1167,7 +1184,7 @@ func (sm *SmartManager) parseSmartForNvme(output []byte, deviceType string) (boo + if smartData.Capacity == 0 && (runtime.GOOS == "darwin" || sm.darwinNvmeProvider != nil) { + smartData.Capacity = sm.lookupDarwinNvmeCapacity(data.SerialNumber) + } +- smartData.Temperature = data.NVMeSmartHealthInformationLog.Temperature ++ smartData.Temperature = log.Temperature + smartData.SmartStatus = getSmartStatus(smartData.Temperature, data.SmartStatus.Passed) + smartData.DiskName = data.Device.Name + smartData.DiskType = data.Device.Type +@@ -1177,7 +1194,6 @@ func (sm *SmartManager) parseSmartForNvme(output []byte, deviceType string) (boo + + // nvme attributes does not follow the same format as ata attributes, + // so we manually map each field to SmartAttributes +- log := data.NVMeSmartHealthInformationLog + smartData.Attributes = []*smart.SmartAttribute{ + {Name: "CriticalWarning", RawValue: uint64(log.CriticalWarning)}, + {Name: "Temperature", RawValue: uint64(log.Temperature)}, +diff --git a/agent/smart_test.go b/agent/smart_test.go +index f77d109a..8b3071c8 100644 +--- a/agent/smart_test.go ++++ b/agent/smart_test.go +@@ -837,6 +837,27 @@ func TestParseSmartOutputMarksVerified(t *testing.T) { + assert.True(t, device.typeVerified) + } + ++func TestParseSmartForNvmeRejectsIdentityOnlyResponse(t *testing.T) { ++ jsonPayload := []byte(`{ ++ "smartctl": {"exit_status": 2}, ++ "device": {"name": "/dev/nvme0", "type": "nvme"}, ++ "model_name": "Netac NVMe SSD 500GB", ++ "serial_number": "IDENTITY-ONLY", ++ "user_capacity": {"bytes": 500107862016} ++ }`) ++ ++ sm := &SmartManager{SmartDataMap: make(map[string]*smart.SmartData)} ++ hasData, exitStatus := sm.parseSmartForNvme(jsonPayload, "") ++ ++ assert.False(t, hasData) ++ assert.Equal(t, 2, exitStatus) ++ assert.NotContains(t, sm.SmartDataMap, "IDENTITY-ONLY") ++ ++ device := &DeviceInfo{Name: "/dev/nvme0", Type: "nvme"} ++ assert.False(t, sm.parseSmartOutput(device, jsonPayload)) ++ assert.NotContains(t, sm.SmartDataMap, "IDENTITY-ONLY") ++} ++ + func TestParseSmartOutputKeepsCustomType(t *testing.T) { + fixturePath := filepath.Join("test-data", "smart", "sda.json") + data, err := os.ReadFile(fixturePath) +diff --git a/internal/entities/smart/smart.go b/internal/entities/smart/smart.go +index 6d832e70..ef452a58 100644 +--- a/internal/entities/smart/smart.go ++++ b/internal/entities/smart/smart.go +@@ -503,11 +503,11 @@ type SmartInfoForNvme struct { + UserCapacity UserCapacity `json:"user_capacity"` + // LogicalBlockSize int `json:"logical_block_size"` + // LocalTime LocalTime `json:"local_time"` +- SmartStatus SmartStatusInfoNvme `json:"smart_status"` +- NVMeSmartHealthInformationLog NVMeSmartHealthInformationLog `json:"nvme_smart_health_information_log"` +- Temperature TemperatureInfoNvme `json:"temperature"` +- PowerCycleCount uint16 `json:"power_cycle_count"` +- PowerOnTime PowerOnTimeInfoNvme `json:"power_on_time"` ++ SmartStatus SmartStatusInfoNvme `json:"smart_status"` ++ NVMeSmartHealthInformationLog *NVMeSmartHealthInformationLog `json:"nvme_smart_health_information_log"` ++ Temperature TemperatureInfoNvme `json:"temperature"` ++ PowerCycleCount uint16 `json:"power_cycle_count"` ++ PowerOnTime PowerOnTimeInfoNvme `json:"power_on_time"` + } + + type TemperatureInfoNvme struct { diff --git a/tasks/henrygd__beszel-2340/solution/solve.sh b/tasks/henrygd__beszel-2340/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2340/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/henrygd__beszel-2340/task.toml b/tasks/henrygd__beszel-2340/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8f88b4d9a1ebd0b77d822095162de4d8b551ad5a --- /dev/null +++ b/tasks/henrygd__beszel-2340/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2340" +description = "fix(agent): handle partial NVMe SMART data" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "1997984325de5057bee0bd5b309fa534dac5d639" +reference = "https://github.com/henrygd/beszel/pull/2340" +source_access = "auto" +built_at = "2026-11-16T16:09:53.454294+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:381ecdbf6930827a884291dd1ea69c7547a02db1a55ae2f03f1f60317df9a36c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-29T16:09:32Z" +diff_format = "unified" +context_files = [ + "agent/smart.go", + "agent/smart_test.go", + "internal/entities/smart/smart.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 65 +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:00.815141+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:fc119fcb7b48406aebffdc0e349147f84af75c1050dab7a862bec3bcabd4bb19" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2340/tests/capture.py b/tasks/henrygd__beszel-2340/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2340/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/henrygd__beszel-2340/tests/instruction.md b/tasks/henrygd__beszel-2340/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c61a4a962dab9833bca2f25a9ddec1d6a4f86c17 --- /dev/null +++ b/tasks/henrygd__beszel-2340/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(agent): handle partial NVMe SMART data + +## Description + +## 📃 Description + +Fix NVMe SMART parsing by rejecting partial smartctl responses that contain device identity but no health log. This prevents misleading zero values and allows the existing namespace-path fallback to query /dev/nvmeXn1. + +## 📷 Screenshots + +Before +1 + +After +2 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1997984325de`. 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/henrygd__beszel-2340/tests/oracle.patch b/tasks/henrygd__beszel-2340/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..eb95e9f75014776fc3576f9ca74858906cc0a9fa --- /dev/null +++ b/tasks/henrygd__beszel-2340/tests/oracle.patch @@ -0,0 +1,144 @@ +diff --git a/agent/smart.go b/agent/smart.go +index 28a5ad81..3490e7fb 100644 +--- a/agent/smart.go ++++ b/agent/smart.go +@@ -311,11 +311,13 @@ func (sm *SmartManager) filterExcludedDevices(devices []*DeviceInfo) []*DeviceIn + return filtered + } + +-// detectSmartOutputType inspects sections that are unique to each smartctl +-// JSON schema (NVMe, ATA/SATA, SCSI) to determine which parser should be used +-// when the reported device type is ambiguous or missing. ++// detectSmartOutputType inspects protocol-specific sections and the reported ++// device type to choose a parser, including when the NVMe health log is missing. + func detectSmartOutputType(output []byte) string { + var hints struct { ++ Device struct { ++ Type string `json:"type"` ++ } `json:"device"` + AtaSmartAttributes json.RawMessage `json:"ata_smart_attributes"` + NVMeSmartHealthInformationLog json.RawMessage `json:"nvme_smart_health_information_log"` + ScsiErrorCounterLog json.RawMessage `json:"scsi_error_counter_log"` +@@ -326,7 +328,7 @@ func detectSmartOutputType(output []byte) string { + } + + switch { +- case hasJSONValue(hints.NVMeSmartHealthInformationLog): ++ case hasJSONValue(hints.NVMeSmartHealthInformationLog), normalizeParserType(hints.Device.Type) == "nvme": + return "nvme" + case hasJSONValue(hints.AtaSmartAttributes): + return "sat" +@@ -397,11 +399,11 @@ func (sm *SmartManager) parseSmartOutput(deviceInfo *DeviceInfo, output []byte) + } + } + +- // Only run the type detection when we do not yet know which parser works +- // or the previous attempt failed. ++ // Inspect every response so a failed NVMe query cannot reach other parsers. ++ structureType := detectSmartOutputType(output) ++ // Update the stored parser only when it is not yet verified. + needsDetection := deviceType == "" || !deviceInfo.typeVerified + if needsDetection { +- structureType := detectSmartOutputType(output) + if deviceType != structureType { + deviceType = structureType + deviceInfo.parserType = structureType +@@ -442,6 +444,11 @@ func (sm *SmartManager) parseSmartOutput(deviceInfo *DeviceInfo, output []byte) + + // Try the selected parsers in order until we find one that succeeds. + for _, parser := range selectedParsers { ++ // A failed NVMe response may still contain a serial number, which is ++ // enough for the SATA and SCSI parsers to accept incorrect zero values. ++ if structureType == "nvme" && parser.Type != "nvme" { ++ continue ++ } + hasData, _ := parser.Parse(output) + if hasData { + deviceInfo.parserType = parser.Type +@@ -1145,6 +1152,16 @@ func (sm *SmartManager) parseSmartForNvme(output []byte, deviceType string) (boo + return false, data.Smartctl.ExitStatus + } + ++ // smartctl may return device identity fields before failing to read the NVMe ++ // health log (for example, on an unsupported controller path or with insufficient ++ // permissions). Do not accept that partial response as valid SMART data: doing ++ // so stores incorrect zero values and prevents the namespace-path fallback. ++ log := data.NVMeSmartHealthInformationLog ++ if log == nil { ++ slog.Debug("no NVMe SMART health information", "device", data.Device.Name) ++ return false, data.Smartctl.ExitStatus ++ } ++ + sm.Lock() + defer sm.Unlock() + +@@ -1167,7 +1184,7 @@ func (sm *SmartManager) parseSmartForNvme(output []byte, deviceType string) (boo + if smartData.Capacity == 0 && (runtime.GOOS == "darwin" || sm.darwinNvmeProvider != nil) { + smartData.Capacity = sm.lookupDarwinNvmeCapacity(data.SerialNumber) + } +- smartData.Temperature = data.NVMeSmartHealthInformationLog.Temperature ++ smartData.Temperature = log.Temperature + smartData.SmartStatus = getSmartStatus(smartData.Temperature, data.SmartStatus.Passed) + smartData.DiskName = data.Device.Name + smartData.DiskType = data.Device.Type +@@ -1177,7 +1194,6 @@ func (sm *SmartManager) parseSmartForNvme(output []byte, deviceType string) (boo + + // nvme attributes does not follow the same format as ata attributes, + // so we manually map each field to SmartAttributes +- log := data.NVMeSmartHealthInformationLog + smartData.Attributes = []*smart.SmartAttribute{ + {Name: "CriticalWarning", RawValue: uint64(log.CriticalWarning)}, + {Name: "Temperature", RawValue: uint64(log.Temperature)}, +diff --git a/agent/smart_test.go b/agent/smart_test.go +index f77d109a..8b3071c8 100644 +--- a/agent/smart_test.go ++++ b/agent/smart_test.go +@@ -837,6 +837,27 @@ func TestParseSmartOutputMarksVerified(t *testing.T) { + assert.True(t, device.typeVerified) + } + ++func TestParseSmartForNvmeRejectsIdentityOnlyResponse(t *testing.T) { ++ jsonPayload := []byte(`{ ++ "smartctl": {"exit_status": 2}, ++ "device": {"name": "/dev/nvme0", "type": "nvme"}, ++ "model_name": "Netac NVMe SSD 500GB", ++ "serial_number": "IDENTITY-ONLY", ++ "user_capacity": {"bytes": 500107862016} ++ }`) ++ ++ sm := &SmartManager{SmartDataMap: make(map[string]*smart.SmartData)} ++ hasData, exitStatus := sm.parseSmartForNvme(jsonPayload, "") ++ ++ assert.False(t, hasData) ++ assert.Equal(t, 2, exitStatus) ++ assert.NotContains(t, sm.SmartDataMap, "IDENTITY-ONLY") ++ ++ device := &DeviceInfo{Name: "/dev/nvme0", Type: "nvme"} ++ assert.False(t, sm.parseSmartOutput(device, jsonPayload)) ++ assert.NotContains(t, sm.SmartDataMap, "IDENTITY-ONLY") ++} ++ + func TestParseSmartOutputKeepsCustomType(t *testing.T) { + fixturePath := filepath.Join("test-data", "smart", "sda.json") + data, err := os.ReadFile(fixturePath) +diff --git a/internal/entities/smart/smart.go b/internal/entities/smart/smart.go +index 6d832e70..ef452a58 100644 +--- a/internal/entities/smart/smart.go ++++ b/internal/entities/smart/smart.go +@@ -503,11 +503,11 @@ type SmartInfoForNvme struct { + UserCapacity UserCapacity `json:"user_capacity"` + // LogicalBlockSize int `json:"logical_block_size"` + // LocalTime LocalTime `json:"local_time"` +- SmartStatus SmartStatusInfoNvme `json:"smart_status"` +- NVMeSmartHealthInformationLog NVMeSmartHealthInformationLog `json:"nvme_smart_health_information_log"` +- Temperature TemperatureInfoNvme `json:"temperature"` +- PowerCycleCount uint16 `json:"power_cycle_count"` +- PowerOnTime PowerOnTimeInfoNvme `json:"power_on_time"` ++ SmartStatus SmartStatusInfoNvme `json:"smart_status"` ++ NVMeSmartHealthInformationLog *NVMeSmartHealthInformationLog `json:"nvme_smart_health_information_log"` ++ Temperature TemperatureInfoNvme `json:"temperature"` ++ PowerCycleCount uint16 `json:"power_cycle_count"` ++ PowerOnTime PowerOnTimeInfoNvme `json:"power_on_time"` + } + + type TemperatureInfoNvme struct { diff --git a/tasks/henrygd__beszel-2340/tests/test.sh b/tasks/henrygd__beszel-2340/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2a744d67116cde2edbb4af4788bc1b9912fdf8d8 --- /dev/null +++ b/tasks/henrygd__beszel-2340/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 1997984325de5057bee0bd5b309fa534dac5d639 > "$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/henrygd__beszel-2340/tests/verifier.py b/tasks/henrygd__beszel-2340/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2340/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/henrygd__beszel-2341/environment/Dockerfile b/tasks/henrygd__beszel-2341/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..38eaf3bed3db23c3defbd12e293f50fb1732862b --- /dev/null +++ b/tasks/henrygd__beszel-2341/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c394a6b5b16f029bacd8d093cc6893c2d1bcc13d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c394a6b5b16f029bacd8d093cc6893c2d1bcc13d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c394a6b5b16f029bacd8d093cc6893c2d1bcc13d \ + && 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/henrygd__beszel-2341/instruction.md b/tasks/henrygd__beszel-2341/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..88aaee94c36db26b80bcb5f08c690d0804c63cf3 --- /dev/null +++ b/tasks/henrygd__beszel-2341/instruction.md @@ -0,0 +1,45 @@ +# Issue + +**Title:** fix(agent): report container-local CPU usage via cgroup cpu accounting + +## Description + +## 📃 Description + +. + +**Problem:** inside an unprivileged Proxmox LXC container the agent reports the utilization of the *physical host cores* in the container's cpuset, not the CPU the container's own processes consume. An idle container pinned to a host core that a busy neighbor saturates shows ~100% CPU while doing nothing. + +**Root cause:** `getCpuMetrics()` collects CPU via `cpu.Times(false)` (gopsutil), which reads `/proc/stat` unconditionally. Inside LXC, lxcfs serves `/proc/stat` with raw counters of the host cores in the container's cpuset; in plain Docker/k8s the host's `/proc` is exposed outright. Either way the numbers describe host cores, not the container. + +**Fix:** when the agent runs inside a container, derive CPU% from the cgroup's own accounting instead — `cpu.stat` `usage_usec`/`user_usec`/`system_usec` on cgroup v2, `cpuacct.usage`/`cpuacct.stat` on v1 — computed as `(usage_now − usage_prev) / (elapsed × usable cores)`, where usable cores is the smallest of the process affinity mask, the cgroup cpuset, and the CPU quota (`cpu.max` / `cpu.cfs_quota_us`). This matches how cAdvisor and node-exporter's cgroup collector account for container CPU. + +Detection is marker-based (`container` env, `/.dockerenv`, `/run/.containerenv`, `/run/systemd/container`, `container=` in `/proc/1/environ` for non-systemd LXC guests, or an `lxcfs` mount over `/proc`) and gated: plain hosts are untouched, and a container without readable cgroup CPU accounting still falls back to the previous `/proc/stat` path. + +Cgroup-path resolution: inside a private cgroup namespace (LXC, default Docker) the `/sys/fs/cgroup` mount root already *is* the container's root cgroup, so its `cpu.stat` covers every process in the container — including siblings of the agent's own service cgroup. With `--cgroupns=host`-style setups the process's `0::` path is a real host-side path containing a runtime marker (`docker-*`, `kubepods`, `lxc`, `crio`, `libpod`, `containerd`, `podman`) and is resolved under the mount instead. + +**Verification:** + +- `cd agent && go build ./...` — clean +- `gofmt -l` on changed files — clean (`agent/emmc_stub.go`, `agent/gpu.go` carry pre-existing upstream formatting drift, untouched) +- `cd agent && go vet ./...` — clean +- `go test -tags 'testing no_ui' ./agent/...` — all green; `go test ./agent/...` — green +- `GOOS=darwin`/`freebsd` agent builds — clean (Windows build fails pre-existing on missing `agent/lhm/bin` assets, identical on `main`) +- New tests in `agent/cpu_linux_test.go` cover: detection markers, v2 sample parsing, container-root-vs-service-cgroup resolution, `--cgroupns=host`-style path join, v1 `cpuacct` fallback, quota/cpuset normalization, zero/backwards/elapsed<=0 deltas, and the `getCpuMetrics` wiring both directions. Sabotage-checked: `TestGetCpuMetricsPrefersCgroup` fails when the dispatch branch is removed. +- Live LXC sanity not run (no Proxmox host available); the fixture tests mirror the issue's repro numerically. + +**Known limitation:** per-core `CpuCoresUsage` still comes from `/proc/stat` (there is no per-core cgroup counter), so per-core bars inside LXC still reflect host core load when cpusets overlap; the total CPU% — the reported bug — is correct. + +Designed to compose with #2285 (the deferred CPU half of the same container-stats fix); identifier names are kept distinct so both can merge without collision. + +## 🪵 Changelog + +### 🔧 Fixed + +- Agent running inside a container (Proxmox LXC, Docker, Podman, k8s) now reports the container's own CPU usage from cgroup accounting instead of the host cores' counters exposed via `/proc/stat` (#2332) + +AI-assisted. I wrote and verified this change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c394a6b5b16f`. 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/henrygd__beszel-2341/solution/patch.diff b/tasks/henrygd__beszel-2341/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c5ec814aa7ff87ef4de440d481408c6ef8c66070 --- /dev/null +++ b/tasks/henrygd__beszel-2341/solution/patch.diff @@ -0,0 +1,795 @@ +diff --git a/agent/cpu.go b/agent/cpu.go +index 8ac0c2e9..ce7fb39f 100644 +--- a/agent/cpu.go ++++ b/agent/cpu.go +@@ -30,11 +30,20 @@ type CpuMetrics struct { + Iowait float64 + Steal float64 + Idle float64 ++ // fromCgroup is set when Total comes from cgroup accounting (LXC) rather ++ // than /proc/stat, so per-core /proc/stat usage would not match it. ++ fromCgroup bool + } + + // getCpuMetrics calculates detailed CPU usage metrics using cached previous measurements. + // It returns percentages for total, user, system, iowait, and steal time. + func getCpuMetrics(cacheTimeMs uint16) (CpuMetrics, error) { ++ // Inside LXC, lxcfs serves /proc/stat with the host cores' counters, not ++ // the guest's own usage. Prefer the cgroup's CPU accounting there. (#2332) ++ if metrics, ok := containerCpuMetrics(cacheTimeMs); ok { ++ metrics.fromCgroup = true ++ return metrics, nil ++ } + times, err := cpu.Times(false) + if err != nil || len(times) == 0 { + return CpuMetrics{}, err +diff --git a/agent/cpu_linux.go b/agent/cpu_linux.go +new file mode 100644 +index 00000000..a50d5059 +--- /dev/null ++++ b/agent/cpu_linux.go +@@ -0,0 +1,372 @@ ++//go:build linux ++ ++package agent ++ ++import ( ++ "os" ++ "path/filepath" ++ "runtime" ++ "strconv" ++ "strings" ++ "sync" ++ "time" ++ ++ "github.com/henrygd/beszel/agent/utils" ++) ++ ++// LXC-aware CPU accounting (issue #2332). ++// ++// Inside an LXC guest, lxcfs serves /proc/stat with the raw counters of the ++// host cores in the guest's cpuset, not the guest's own usage. An idle guest ++// sharing a host core with a busy neighbor then reports near-100% CPU while ++// doing nothing. The cgroup's own accounting (cpu.stat / cpuacct.usage) ++// reflects only the guest's processes, so inside LXC we derive CPU% from that ++// instead. ++// ++// Other runtimes (Docker, Podman, k8s) are deliberately left alone: the agent ++// is normally deployed there to monitor the host, and the host's /proc/stat is ++// exactly what it should report. ++ ++// File paths and hooks are variables so tests can point them at fixtures. ++var ( ++ cpuCgroupRoot = "/sys/fs/cgroup" // default cgroup v2 mount point ++ cpuCgroupMountinfo = "/proc/self/mountinfo" ++ cpuProcSelfCgroup = "/proc/self/cgroup" ++ cpuSystemdContPath = "/run/systemd/container" ++ cpuNumCPU = runtime.NumCPU ++ cpuNow = time.Now ++) ++ ++// cpuUserHZ is the USER_HZ jiffies-per-second rate cpuacct.stat reports in. ++const cpuUserHZ = 100 ++ ++// inLxc reports whether the agent itself runs inside an LXC guest. ++// The result is cached because it cannot change during the process lifetime. ++var inLxc = sync.OnceValue(detectLxc) ++ ++// detectLxc looks for LXC guest markers that are readable without root ++// (the agent usually runs as an unprivileged user, so /proc/1/environ is not). ++func detectLxc() bool { ++ // lxcfs mounted over /proc/stat is the direct cause of the host-core ++ // counters. Only match that mount point: an LXC host also has lxcfs ++ // mounted, but at /var/lib/lxcfs. ++ if data, err := os.ReadFile(cpuCgroupMountinfo); err == nil && procStatFromLxcfs(data) { ++ return true ++ } ++ // set by liblxc for the container init and inherited on non-systemd guests ++ if os.Getenv("container") == "lxc" { ++ return true ++ } ++ // written by systemd on systemd-based guests ++ if data, err := os.ReadFile(cpuSystemdContPath); err == nil && ++ strings.TrimSpace(string(data)) == "lxc" { ++ return true ++ } ++ return false ++} ++ ++// procStatFromLxcfs reports whether mountinfo shows lxcfs mounted on /proc/stat. ++func procStatFromLxcfs(mountinfo []byte) bool { ++ for line := range strings.SplitSeq(string(mountinfo), "\n") { ++ left, right, found := strings.Cut(line, " - ") ++ if !found { ++ continue ++ } ++ fields, post := strings.Fields(left), strings.Fields(right) ++ if len(fields) >= 5 && len(post) > 0 && fields[4] == "/proc/stat" && post[0] == "fuse.lxcfs" { ++ return true ++ } ++ } ++ return false ++} ++ ++// cgroupCpuSample is one read of the container's cumulative CPU accounting. ++type cgroupCpuSample struct { ++ usageUsec uint64 ++ userUsec uint64 ++ systemUsec uint64 ++ cores float64 // usable CPU cores: affinity ∩ cpuset ∩ quota ++ at time.Time ++} ++ ++var lastCgroupCpuSamples = make(map[uint16]cgroupCpuSample) ++ ++// init seeds the LXC CPU baseline so the first reported value is a real ++// delta since startup rather than zero. ++func init() { ++ if !inLxc() { ++ return ++ } ++ if s, ok := readContainerCpuSample(); ok { ++ s.at = cpuNow() ++ lastCgroupCpuSamples[60000] = s ++ } ++} ++ ++// containerCpuMetrics derives CPU metrics from the guest's own cgroup ++// accounting when running inside LXC. It returns ok=false everywhere else and ++// whenever cgroup accounting is unreadable, so callers keep the /proc/stat ++// path. ++func containerCpuMetrics(cacheTimeMs uint16) (CpuMetrics, bool) { ++ if !inLxc() { ++ return CpuMetrics{}, false ++ } ++ cur, ok := readContainerCpuSample() ++ if !ok { ++ return CpuMetrics{}, false ++ } ++ cur.at = cpuNow() ++ ++ prev, ok := lastCgroupCpuSamples[cacheTimeMs] ++ if !ok { ++ prev = lastCgroupCpuSamples[60000] ++ } ++ lastCgroupCpuSamples[cacheTimeMs] = cur ++ ++ // No baseline yet, a backwards counter (cgroup recreated), or a ++ // non-positive clock delta: report zero this tick instead of guessing. ++ elapsedUsec := cur.at.Sub(prev.at).Microseconds() ++ if prev.at.IsZero() || elapsedUsec <= 0 || cur.usageUsec < prev.usageUsec { ++ return CpuMetrics{}, true ++ } ++ ++ cores := cur.cores ++ if cores <= 0 { ++ cores = 1 ++ } ++ window := float64(elapsedUsec) * cores ++ ++ metrics := CpuMetrics{ ++ Total: clampPercent(float64(cur.usageUsec-prev.usageUsec) / window * 100), ++ User: clampPercent(float64(cur.userUsec-prev.userUsec) / window * 100), ++ System: clampPercent(float64(cur.systemUsec-prev.systemUsec) / window * 100), ++ } ++ // cgroup accounting has no iowait/steal; everything not busy is idle. ++ metrics.Idle = clampPercent(100 - metrics.Total) ++ return metrics, true ++} ++ ++// readContainerCpuSample reads the container's cumulative CPU usage, preferring ++// the cgroup v2 unified hierarchy and falling back to the v1 cpuacct ++// controller. ++func readContainerCpuSample() (cgroupCpuSample, bool) { ++ if s, ok := readCgroupV2CpuSample(); ok { ++ return s, true ++ } ++ return readCgroupV1CpuSample() ++} ++ ++// readCgroupV2CpuSample reads usage from the unified hierarchy's cpu.stat. ++// ++// The mount root is always the cgroup to read: an LXC guest has a private ++// cgroup namespace, so /sys/fs/cgroup already is the guest's root cgroup, and ++// its cpu.stat accounts for every process in the guest. The agent's own path ++// in /proc/self/cgroup (its service cgroup, or the ".lxc" leaf when started ++// from an attached shell) only covers a subset and must not be descended into. ++func readCgroupV2CpuSample() (cgroupCpuSample, bool) { ++ if !inCgroupV2() { ++ return cgroupCpuSample{}, false // no v2 membership; try v1 ++ } ++ dir := cpuCgroupRoot ++ if mount := cgroupMountPoint("cgroup2", ""); mount != "" { ++ dir = mount ++ } ++ stat := filepath.Join(dir, "cpu.stat") ++ usage, ok := cgroupStatValue(stat, "usage_usec") ++ if !ok { ++ return cgroupCpuSample{}, false ++ } ++ s := cgroupCpuSample{usageUsec: usage, cores: cpuCgroupCores(dir)} ++ s.userUsec, _ = cgroupStatValue(stat, "user_usec") ++ s.systemUsec, _ = cgroupStatValue(stat, "system_usec") ++ return s, true ++} ++ ++// readCgroupV1CpuSample reads usage from the legacy cpuacct controller. ++// As with v2, the hierarchy mount root is the guest's own cgroup and its ++// accounting includes every child cgroup, so it is read directly rather than ++// the agent's own sub-cgroup. ++func readCgroupV1CpuSample() (cgroupCpuSample, bool) { ++ dir := cgroupMountPoint("cgroup", "cpuacct") ++ if dir == "" { ++ return cgroupCpuSample{}, false ++ } ++ usageNs, ok := utils.ReadUintFile(filepath.Join(dir, "cpuacct.usage")) ++ if !ok { ++ return cgroupCpuSample{}, false ++ } ++ s := cgroupCpuSample{usageUsec: usageNs / 1000, cores: cpuCgroupCores(dir)} ++ // cpuacct.stat reports user/system in USER_HZ jiffies. ++ if v, ok := cgroupStatValue(filepath.Join(dir, "cpuacct.stat"), "user"); ok { ++ s.userUsec = v * 1e6 / cpuUserHZ ++ } ++ if v, ok := cgroupStatValue(filepath.Join(dir, "cpuacct.stat"), "system"); ok { ++ s.systemUsec = v * 1e6 / cpuUserHZ ++ } ++ return s, true ++} ++ ++// inCgroupV2 reports whether /proc/self/cgroup lists the v2 unified hierarchy ++// (a "0::" entry). ++func inCgroupV2() bool { ++ data, err := os.ReadFile(cpuProcSelfCgroup) ++ if err != nil { ++ return false ++ } ++ for line := range strings.SplitSeq(string(data), "\n") { ++ if strings.HasPrefix(line, "0::") { ++ return true ++ } ++ } ++ return false ++} ++ ++// cgroupMountPoint returns the mount point of a cgroup hierarchy from ++// /proc/self/mountinfo: the cgroup2 mount for v2, or the cgroup mount whose ++// super options list the wanted v1 controller. ++func cgroupMountPoint(fstype, v1ctrl string) string { ++ data, err := os.ReadFile(cpuCgroupMountinfo) ++ if err != nil { ++ return "" ++ } ++ for _, line := range strings.Split(string(data), "\n") { ++ left, right, found := strings.Cut(line, " - ") ++ if !found { ++ continue ++ } ++ post := strings.Fields(right) ++ if len(post) == 0 || post[0] != fstype { ++ continue ++ } ++ if v1ctrl != "" && !mountOptHas(post, v1ctrl) { ++ continue ++ } ++ fields := strings.Fields(left) ++ if len(fields) >= 5 { ++ return unescapeMountPoint(fields[4]) ++ } ++ } ++ return "" ++} ++ ++// mountOptHas reports whether the comma-separated super options (field 3 after ++// the " - " separator) contain opt. ++func mountOptHas(post []string, opt string) bool { ++ if len(post) < 3 { ++ return false ++ } ++ for _, o := range strings.Split(post[2], ",") { ++ if o == opt { ++ return true ++ } ++ } ++ return false ++} ++ ++// unescapeMountPoint decodes octal escapes (e.g. \040 for space) used in ++// mountinfo paths. ++func unescapeMountPoint(s string) string { ++ return strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`).Replace(s) ++} ++ ++// cpuCgroupCores returns how many CPU cores the cgroup at dir may use: the ++// smallest of the process affinity mask, the cgroup cpuset, and the CPU quota. ++func cpuCgroupCores(dir string) float64 { ++ cores := float64(cpuNumCPU()) ++ if n := cpusetCount(dir); n > 0 && n < cores { ++ cores = n ++ } ++ if q, ok := cpuQuotaCores(dir); ok && q < cores { ++ cores = q ++ } ++ if cores <= 0 { ++ cores = 1 ++ } ++ return cores ++} ++ ++// cpusetCount returns the number of CPUs in the cgroup's cpuset, e.g. "0-3" or ++// "2,5-7". An empty or missing file means unconstrained. ++func cpusetCount(dir string) float64 { ++ for _, name := range []string{"cpuset.cpus.effective", "cpuset.cpus"} { ++ raw, err := os.ReadFile(filepath.Join(dir, name)) ++ if err != nil { ++ continue ++ } ++ if n := countCpuList(strings.TrimSpace(string(raw))); n > 0 { ++ return float64(n) ++ } ++ } ++ return 0 ++} ++ ++// countCpuList counts the CPUs in a Linux CPU list like "0-3,5,8-9". ++func countCpuList(list string) int { ++ total := 0 ++ for part := range strings.SplitSeq(list, ",") { ++ lo, hi, ranged := strings.Cut(part, "-") ++ a, err := strconv.Atoi(lo) ++ if err != nil { ++ continue ++ } ++ b := a ++ if ranged { ++ if v, err := strconv.Atoi(hi); err == nil { ++ b = v ++ } ++ } ++ if b >= a { ++ total += b - a + 1 ++ } ++ } ++ return total ++} ++ ++// cpuQuotaCores returns the cgroup's CPU quota in cores. v2 uses cpu.max ++// (" "), v1 uses cpu.cfs_quota_us / cpu.cfs_period_us. ++func cpuQuotaCores(dir string) (float64, bool) { ++ if raw, err := os.ReadFile(filepath.Join(dir, "cpu.max")); err == nil { ++ fields := strings.Fields(string(raw)) ++ if len(fields) == 2 && fields[0] != "max" { ++ if quota, err := strconv.ParseFloat(fields[0], 64); err == nil && quota > 0 { ++ if period, err := strconv.ParseFloat(fields[1], 64); err == nil && period > 0 { ++ return quota / period, true ++ } ++ } ++ } ++ } ++ if quota, ok := readCgroupInt(filepath.Join(dir, "cpu.cfs_quota_us")); ok && quota > 0 { ++ if period, ok := readCgroupInt(filepath.Join(dir, "cpu.cfs_period_us")); ok && period > 0 { ++ return float64(quota) / float64(period), true ++ } ++ } ++ return 0, false ++} ++ ++// cgroupStatValue returns the value of key in a cgroup "key value" stat file. ++func cgroupStatValue(path, key string) (uint64, bool) { ++ data, err := os.ReadFile(path) ++ if err != nil { ++ return 0, false ++ } ++ for line := range strings.SplitSeq(string(data), "\n") { ++ name, value, found := strings.Cut(line, " ") ++ if !found || name != key { ++ continue ++ } ++ v, err := strconv.ParseUint(strings.TrimSpace(value), 10, 64) ++ return v, err == nil ++ } ++ return 0, false ++} ++ ++// readCgroupInt reads a file containing a single signed integer ++// (cpu.cfs_quota_us is -1 when no quota is set). ++func readCgroupInt(path string) (int64, bool) { ++ data, err := os.ReadFile(path) ++ if err != nil { ++ return 0, false ++ } ++ v, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64) ++ return v, err == nil ++} +diff --git a/agent/cpu_linux_test.go b/agent/cpu_linux_test.go +new file mode 100644 +index 00000000..337ad76b +--- /dev/null ++++ b/agent/cpu_linux_test.go +@@ -0,0 +1,350 @@ ++//go:build testing && linux ++ ++package agent ++ ++import ( ++ "os" ++ "path/filepath" ++ "sync" ++ "testing" ++ "time" ++ ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/require" ++) ++ ++// swapCpuContainerSeams points every container-detection and cgroup path at ++// empty fixtures under a temp dir, then restores them on cleanup. ++func swapCpuContainerSeams(t *testing.T) { ++ t.Helper() ++ backup := struct { ++ root, mountinfo, selfCgroup, systemdCont string ++ numCPU func() int ++ now func() time.Time ++ }{ ++ cpuCgroupRoot, cpuCgroupMountinfo, cpuProcSelfCgroup, cpuSystemdContPath, cpuNumCPU, cpuNow, ++ } ++ origInLxc := inLxc ++ samples := lastCgroupCpuSamples ++ env, hadEnv := os.LookupEnv("container") ++ t.Cleanup(func() { ++ cpuCgroupRoot, cpuCgroupMountinfo, cpuProcSelfCgroup, cpuSystemdContPath = backup.root, backup.mountinfo, backup.selfCgroup, backup.systemdCont ++ cpuNumCPU, cpuNow = backup.numCPU, backup.now ++ inLxc = origInLxc ++ lastCgroupCpuSamples = samples ++ if hadEnv { ++ os.Setenv("container", env) ++ } ++ }) ++ ++ inLxc = sync.OnceValue(detectLxc) ++ lastCgroupCpuSamples = make(map[uint16]cgroupCpuSample) ++ os.Unsetenv("container") ++ ++ tmp := t.TempDir() ++ cpuCgroupRoot = filepath.Join(tmp, "cgroup") ++ cpuCgroupMountinfo = filepath.Join(tmp, "mountinfo") ++ cpuProcSelfCgroup = filepath.Join(tmp, "self-cgroup") ++ cpuSystemdContPath = filepath.Join(tmp, "systemd-container") ++} ++ ++func writeCpuFixture(t *testing.T, path, contents string) { ++ t.Helper() ++ require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) ++ require.NoError(t, os.WriteFile(path, []byte(contents), 0o644)) ++} ++ ++// markLxc makes detection see a systemd-based LXC guest. ++func markLxc(t *testing.T) { ++ t.Helper() ++ writeCpuFixture(t, cpuSystemdContPath, "lxc\n") ++} ++ ++// fakeNow installs a controllable clock and returns a function to advance it. ++func fakeNow(t *testing.T) func(time.Duration) { ++ t.Helper() ++ cur := time.Unix(1_700_000_000, 0) ++ cpuNow = func() time.Time { return cur } ++ return func(d time.Duration) { cur = cur.Add(d) } ++} ++ ++func TestDetectLxc(t *testing.T) { ++ tests := []struct { ++ name string ++ setup func(t *testing.T) ++ want bool ++ }{ ++ {"plain host", func(t *testing.T) {}, false}, ++ {"container env lxc", func(t *testing.T) { t.Setenv("container", "lxc") }, true}, ++ {"container env podman", func(t *testing.T) { t.Setenv("container", "podman") }, false}, ++ {"systemd container lxc", func(t *testing.T) { writeCpuFixture(t, cpuSystemdContPath, "lxc\n") }, true}, ++ {"systemd container nspawn", func(t *testing.T) { writeCpuFixture(t, cpuSystemdContPath, "systemd-nspawn\n") }, false}, ++ {"lxcfs serving /proc/stat", func(t *testing.T) { ++ writeCpuFixture(t, cpuCgroupMountinfo, ++ "31 25 0:28 / /proc/stat rw,nosuid,nodev,relatime - fuse.lxcfs lxcfs rw,user_id=0,group_id=0\n") ++ }, true}, ++ // an LXC host (e.g. Proxmox) mounts lxcfs too, but not over its own /proc ++ {"lxcfs mounted on host", func(t *testing.T) { ++ writeCpuFixture(t, cpuCgroupMountinfo, ++ "45 25 0:40 / /var/lib/lxcfs rw,nosuid,nodev,relatime - fuse.lxcfs lxcfs rw,user_id=0,group_id=0\n") ++ }, false}, ++ {"cgroup-only mountinfo", func(t *testing.T) { ++ writeCpuFixture(t, cpuCgroupMountinfo, ++ "36 25 0:32 / /sys/fs/cgroup rw - cgroup2 cgroup2 rw,nsdelegate\n") ++ }, false}, ++ } ++ for _, tt := range tests { ++ t.Run(tt.name, func(t *testing.T) { ++ swapCpuContainerSeams(t) ++ tt.setup(t) ++ assert.Equal(t, tt.want, detectLxc()) ++ }) ++ } ++} ++ ++func TestReadCgroupV2CpuSample(t *testing.T) { ++ swapCpuContainerSeams(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ require.NoError(t, os.MkdirAll(cpuCgroupRoot, 0o755)) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), ++ "usage_usec 3000000\nuser_usec 2000000\nsystem_usec 1000000\nnr_throttled 7\n") ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpuset.cpus.effective"), "2,5-7\n") ++ cpuNumCPU = func() int { return 8 } ++ ++ s, ok := readCgroupV2CpuSample() ++ require.True(t, ok) ++ assert.EqualValues(t, 3000000, s.usageUsec) ++ assert.EqualValues(t, 2000000, s.userUsec) ++ assert.EqualValues(t, 1000000, s.systemUsec) ++ assert.InDelta(t, 4, s.cores, 0.001) // cpuset 2,5-7 = 4 cores ++} ++ ++// The agent may sit in a sub-cgroup of the guest (a systemd service, or the ++// ".lxc" leaf when started from an attached shell); the mount root still ++// accounts for the whole guest and must win. ++func TestReadCgroupV2PrefersContainerRoot(t *testing.T) { ++ for _, rel := range []string{"system.slice/beszel-agent.service", ".lxc"} { ++ t.Run(rel, func(t *testing.T) { ++ swapCpuContainerSeams(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/"+rel+"\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 9000\n") ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, rel, "cpu.stat"), "usage_usec 5\n") ++ ++ s, ok := readCgroupV2CpuSample() ++ require.True(t, ok) ++ assert.EqualValues(t, 9000, s.usageUsec) ++ }) ++ } ++} ++ ++// Same for v1: the cpuacct mount root covers the agent's sibling services. ++func TestReadCgroupV1PrefersContainerRoot(t *testing.T) { ++ swapCpuContainerSeams(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "3:cpu,cpuacct:/system.slice/beszel-agent.service\n") ++ v1 := filepath.Join(t.TempDir(), "cpu,cpuacct") ++ writeCpuFixture(t, cpuCgroupMountinfo, ++ "30 25 0:26 / "+v1+" rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,cpu,cpuacct\n") ++ writeCpuFixture(t, filepath.Join(v1, "cpuacct.usage"), "9000000\n") ++ writeCpuFixture(t, filepath.Join(v1, "system.slice/beszel-agent.service/cpuacct.usage"), "5000\n") ++ ++ s, ok := readContainerCpuSample() ++ require.True(t, ok) ++ assert.EqualValues(t, 9000, s.usageUsec) ++} ++ ++func TestReadCgroupV1CpuSample(t *testing.T) { ++ swapCpuContainerSeams(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "3:cpuacct:/\n2:memory:/\n") ++ v1 := filepath.Join(t.TempDir(), "cpuacct") ++ writeCpuFixture(t, cpuCgroupMountinfo, ++ "30 25 0:26 / "+v1+" rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,cpuacct\n") ++ writeCpuFixture(t, filepath.Join(v1, "cpuacct.usage"), "2000000000\n") ++ writeCpuFixture(t, filepath.Join(v1, "cpuacct.stat"), "user 100\nsystem 50\n") ++ cpuNumCPU = func() int { return 4 } ++ ++ s, ok := readContainerCpuSample() // no 0:: line -> falls through to v1 ++ require.True(t, ok) ++ assert.EqualValues(t, 2000000, s.usageUsec) // ns -> usec ++ assert.EqualValues(t, 1000000, s.userUsec) // 100 jiffies * 1e6/100 ++ assert.EqualValues(t, 500000, s.systemUsec) // 50 jiffies ++ assert.InDelta(t, 4, s.cores, 0.001) ++} ++ ++func TestContainerCpuMetricsMath(t *testing.T) { ++ swapCpuContainerSeams(t) ++ markLxc(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ require.NoError(t, os.MkdirAll(cpuCgroupRoot, 0o755)) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpuset.cpus.effective"), "0-3\n") ++ cpuNumCPU = func() int { return 8 } ++ advance := fakeNow(t) ++ ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), ++ "usage_usec 1000000\nuser_usec 600000\nsystem_usec 400000\n") ++ m, ok := containerCpuMetrics(60000) ++ require.True(t, ok) ++ assert.Zero(t, m.Total) // first call only seeds the baseline ++ ++ // 1s elapsed, container burned 2 core-seconds on 4 usable cores ++ advance(time.Second) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), ++ "usage_usec 3000000\nuser_usec 1600000\nsystem_usec 900000\n") ++ m, ok = containerCpuMetrics(60000) ++ require.True(t, ok) ++ assert.InDelta(t, 50, m.Total, 0.01) ++ assert.InDelta(t, 25, m.User, 0.01) ++ assert.InDelta(t, 12.5, m.System, 0.01) ++ assert.Zero(t, m.Iowait) ++ assert.Zero(t, m.Steal) ++ assert.InDelta(t, 50, m.Idle, 0.01) ++} ++ ++func TestContainerCpuMetricsHonorsQuota(t *testing.T) { ++ swapCpuContainerSeams(t) ++ markLxc(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ require.NoError(t, os.MkdirAll(cpuCgroupRoot, 0o755)) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.max"), "200000 100000\n") // 2 cores ++ cpuNumCPU = func() int { return 8 } ++ advance := fakeNow(t) ++ ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 1000000\n") ++ containerCpuMetrics(60000) ++ advance(time.Second) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 2000000\n") ++ m, ok := containerCpuMetrics(60000) ++ require.True(t, ok) ++ assert.InDelta(t, 50, m.Total, 0.01) // 1 core-second against a 2-core quota ++} ++ ++func TestContainerCpuMetricsZeroAndBackwardDelta(t *testing.T) { ++ swapCpuContainerSeams(t) ++ markLxc(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ require.NoError(t, os.MkdirAll(cpuCgroupRoot, 0o755)) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 5000000\n") ++ cpuNumCPU = func() int { return 4 } ++ advance := fakeNow(t) ++ ++ // seed the baseline, then do not advance the clock: elapsed <= 0 ++ containerCpuMetrics(60000) ++ m, ok := containerCpuMetrics(60000) ++ require.True(t, ok) ++ assert.Zero(t, m.Total) ++ ++ // counter goes backwards (cgroup recreated): report zero and re-baseline ++ advance(time.Second) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 100000\n") ++ m, ok = containerCpuMetrics(60000) ++ require.True(t, ok) ++ assert.Zero(t, m.Total) ++ ++ // next tick measures from the new baseline, not the stale one ++ advance(time.Second) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 1100000\n") ++ m, ok = containerCpuMetrics(60000) ++ require.True(t, ok) ++ assert.InDelta(t, 25, m.Total, 0.01) // 1e6 usec / (1s * 4 cores) ++} ++ ++func TestContainerCpuMetricsFallbacks(t *testing.T) { ++ t.Run("not in lxc", func(t *testing.T) { ++ swapCpuContainerSeams(t) ++ _, ok := containerCpuMetrics(60000) ++ assert.False(t, ok) ++ }) ++ // Docker agents monitor the host, so cgroup accounting must not kick in ++ // even when it is readable and no LXC marker is present. ++ t.Run("docker container", func(t *testing.T) { ++ swapCpuContainerSeams(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 5000000\n") ++ _, ok := containerCpuMetrics(60000) ++ assert.False(t, ok) ++ }) ++ t.Run("in lxc without cgroup accounting", func(t *testing.T) { ++ swapCpuContainerSeams(t) ++ markLxc(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ // cpuCgroupRoot has no cpu.stat ++ _, ok := containerCpuMetrics(60000) ++ assert.False(t, ok) ++ }) ++} ++ ++// The host path must keep reporting through gopsutil untouched. ++func TestGetCpuMetricsHostFallback(t *testing.T) { ++ swapCpuContainerSeams(t) ++ m, err := getCpuMetrics(60000) ++ require.NoError(t, err) ++ assert.False(t, m.fromCgroup) ++ assert.GreaterOrEqual(t, m.Total, 0.0) ++ assert.LessOrEqual(t, m.Total, 100.0) ++} ++ ++// Inside LXC getCpuMetrics must report the cgroup-derived value, not ++// the host core counters from /proc/stat. ++func TestGetCpuMetricsPrefersCgroup(t *testing.T) { ++ swapCpuContainerSeams(t) ++ markLxc(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ require.NoError(t, os.MkdirAll(cpuCgroupRoot, 0o755)) ++ cpuNumCPU = func() int { return 4 } ++ advance := fakeNow(t) ++ ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 0\n") ++ m, err := getCpuMetrics(60000) ++ require.NoError(t, err) ++ assert.Zero(t, m.Total) ++ ++ advance(time.Second) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 2000000\n") ++ m, err = getCpuMetrics(60000) ++ require.NoError(t, err) ++ assert.InDelta(t, 50, m.Total, 0.01) ++ assert.True(t, m.fromCgroup) // per-core usage is skipped for this source ++} ++ ++func TestCountCpuList(t *testing.T) { ++ assert.Equal(t, 4, countCpuList("0-3")) ++ assert.Equal(t, 4, countCpuList("2,5-7")) ++ assert.Equal(t, 1, countCpuList("2")) ++ assert.Equal(t, 0, countCpuList("")) ++ assert.Equal(t, 0, countCpuList("max")) ++ assert.Equal(t, 6, countCpuList("0-3,8-9")) ++} ++ ++func TestCpuQuotaCores(t *testing.T) { ++ dir := t.TempDir() ++ _, ok := cpuQuotaCores(dir) ++ assert.False(t, ok) // no quota files ++ ++ writeCpuFixture(t, filepath.Join(dir, "cpu.max"), "max 100000\n") ++ _, ok = cpuQuotaCores(dir) ++ assert.False(t, ok) // unlimited ++ ++ writeCpuFixture(t, filepath.Join(dir, "cpu.max"), "150000 100000\n") ++ q, ok := cpuQuotaCores(dir) ++ require.True(t, ok) ++ assert.InDelta(t, 1.5, q, 0.001) ++ ++ // v1 files ++ v1 := t.TempDir() ++ writeCpuFixture(t, filepath.Join(v1, "cpu.cfs_quota_us"), "-1\n") ++ writeCpuFixture(t, filepath.Join(v1, "cpu.cfs_period_us"), "100000\n") ++ _, ok = cpuQuotaCores(v1) ++ assert.False(t, ok) ++ ++ writeCpuFixture(t, filepath.Join(v1, "cpu.cfs_quota_us"), "50000\n") ++ q, ok = cpuQuotaCores(v1) ++ require.True(t, ok) ++ assert.InDelta(t, 0.5, q, 0.001) ++} +diff --git a/agent/cpu_unsupported.go b/agent/cpu_unsupported.go +new file mode 100644 +index 00000000..886941f8 +--- /dev/null ++++ b/agent/cpu_unsupported.go +@@ -0,0 +1,9 @@ ++//go:build !linux ++ ++package agent ++ ++// containerCpuMetrics is Linux-only (cgroup accounting). Other platforms keep ++// the gopsutil /proc path. ++func containerCpuMetrics(uint16) (CpuMetrics, bool) { ++ return CpuMetrics{}, false ++} +diff --git a/agent/system.go b/agent/system.go +index 3373e1aa..f567585f 100644 +--- a/agent/system.go ++++ b/agent/system.go +@@ -170,9 +170,13 @@ func (a *Agent) getSystemStats(cacheTimeMs uint16) system.Stats { + slog.Error("Error getting cpu metrics", "err", err) + } + +- // per-core cpu usage +- if perCoreUsage, err := getPerCoreCpuUsage(cacheTimeMs); err == nil { +- systemStats.CpuCoresUsage = perCoreUsage ++ // per-core cpu usage. Skipped when the total comes from cgroup accounting: ++ // per-core /proc/stat counters there describe shared host cores, not the ++ // guest, and would contradict the total. ++ if !cpuMetrics.fromCgroup { ++ if perCoreUsage, err := getPerCoreCpuUsage(cacheTimeMs); err == nil { ++ systemStats.CpuCoresUsage = perCoreUsage ++ } + } + + // load average diff --git a/tasks/henrygd__beszel-2341/solution/solve.sh b/tasks/henrygd__beszel-2341/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2341/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/henrygd__beszel-2341/task.toml b/tasks/henrygd__beszel-2341/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..be0f0d8f681df872e4acb683b68746aad6853daa --- /dev/null +++ b/tasks/henrygd__beszel-2341/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2341" +description = "fix(agent): report container-local CPU usage via cgroup cpu accounting" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "c394a6b5b16f029bacd8d093cc6893c2d1bcc13d" +reference = "https://github.com/henrygd/beszel/pull/2341" +source_access = "auto" +built_at = "2026-11-16T16:09:53.436592+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3a5a1ad5ce858140f0effcdba9d549537f7b675a701a89834842686303dc2e6b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-01T23:33:43Z" +diff_format = "unified" +context_files = [ + "agent/cpu.go", + "agent/cpu_linux.go", + "agent/cpu_linux_test.go", + "agent/cpu_unsupported.go", + "agent/system.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 750 +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:00.815634+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a03f32176612bc57a3caa8bd5cc07dce5aaedc50ee802558fd93caeabaf26336" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2341/tests/capture.py b/tasks/henrygd__beszel-2341/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2341/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/henrygd__beszel-2341/tests/instruction.md b/tasks/henrygd__beszel-2341/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..88aaee94c36db26b80bcb5f08c690d0804c63cf3 --- /dev/null +++ b/tasks/henrygd__beszel-2341/tests/instruction.md @@ -0,0 +1,45 @@ +# Issue + +**Title:** fix(agent): report container-local CPU usage via cgroup cpu accounting + +## Description + +## 📃 Description + +. + +**Problem:** inside an unprivileged Proxmox LXC container the agent reports the utilization of the *physical host cores* in the container's cpuset, not the CPU the container's own processes consume. An idle container pinned to a host core that a busy neighbor saturates shows ~100% CPU while doing nothing. + +**Root cause:** `getCpuMetrics()` collects CPU via `cpu.Times(false)` (gopsutil), which reads `/proc/stat` unconditionally. Inside LXC, lxcfs serves `/proc/stat` with raw counters of the host cores in the container's cpuset; in plain Docker/k8s the host's `/proc` is exposed outright. Either way the numbers describe host cores, not the container. + +**Fix:** when the agent runs inside a container, derive CPU% from the cgroup's own accounting instead — `cpu.stat` `usage_usec`/`user_usec`/`system_usec` on cgroup v2, `cpuacct.usage`/`cpuacct.stat` on v1 — computed as `(usage_now − usage_prev) / (elapsed × usable cores)`, where usable cores is the smallest of the process affinity mask, the cgroup cpuset, and the CPU quota (`cpu.max` / `cpu.cfs_quota_us`). This matches how cAdvisor and node-exporter's cgroup collector account for container CPU. + +Detection is marker-based (`container` env, `/.dockerenv`, `/run/.containerenv`, `/run/systemd/container`, `container=` in `/proc/1/environ` for non-systemd LXC guests, or an `lxcfs` mount over `/proc`) and gated: plain hosts are untouched, and a container without readable cgroup CPU accounting still falls back to the previous `/proc/stat` path. + +Cgroup-path resolution: inside a private cgroup namespace (LXC, default Docker) the `/sys/fs/cgroup` mount root already *is* the container's root cgroup, so its `cpu.stat` covers every process in the container — including siblings of the agent's own service cgroup. With `--cgroupns=host`-style setups the process's `0::` path is a real host-side path containing a runtime marker (`docker-*`, `kubepods`, `lxc`, `crio`, `libpod`, `containerd`, `podman`) and is resolved under the mount instead. + +**Verification:** + +- `cd agent && go build ./...` — clean +- `gofmt -l` on changed files — clean (`agent/emmc_stub.go`, `agent/gpu.go` carry pre-existing upstream formatting drift, untouched) +- `cd agent && go vet ./...` — clean +- `go test -tags 'testing no_ui' ./agent/...` — all green; `go test ./agent/...` — green +- `GOOS=darwin`/`freebsd` agent builds — clean (Windows build fails pre-existing on missing `agent/lhm/bin` assets, identical on `main`) +- New tests in `agent/cpu_linux_test.go` cover: detection markers, v2 sample parsing, container-root-vs-service-cgroup resolution, `--cgroupns=host`-style path join, v1 `cpuacct` fallback, quota/cpuset normalization, zero/backwards/elapsed<=0 deltas, and the `getCpuMetrics` wiring both directions. Sabotage-checked: `TestGetCpuMetricsPrefersCgroup` fails when the dispatch branch is removed. +- Live LXC sanity not run (no Proxmox host available); the fixture tests mirror the issue's repro numerically. + +**Known limitation:** per-core `CpuCoresUsage` still comes from `/proc/stat` (there is no per-core cgroup counter), so per-core bars inside LXC still reflect host core load when cpusets overlap; the total CPU% — the reported bug — is correct. + +Designed to compose with #2285 (the deferred CPU half of the same container-stats fix); identifier names are kept distinct so both can merge without collision. + +## 🪵 Changelog + +### 🔧 Fixed + +- Agent running inside a container (Proxmox LXC, Docker, Podman, k8s) now reports the container's own CPU usage from cgroup accounting instead of the host cores' counters exposed via `/proc/stat` (#2332) + +AI-assisted. I wrote and verified this change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c394a6b5b16f`. 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/henrygd__beszel-2341/tests/oracle.patch b/tasks/henrygd__beszel-2341/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c5ec814aa7ff87ef4de440d481408c6ef8c66070 --- /dev/null +++ b/tasks/henrygd__beszel-2341/tests/oracle.patch @@ -0,0 +1,795 @@ +diff --git a/agent/cpu.go b/agent/cpu.go +index 8ac0c2e9..ce7fb39f 100644 +--- a/agent/cpu.go ++++ b/agent/cpu.go +@@ -30,11 +30,20 @@ type CpuMetrics struct { + Iowait float64 + Steal float64 + Idle float64 ++ // fromCgroup is set when Total comes from cgroup accounting (LXC) rather ++ // than /proc/stat, so per-core /proc/stat usage would not match it. ++ fromCgroup bool + } + + // getCpuMetrics calculates detailed CPU usage metrics using cached previous measurements. + // It returns percentages for total, user, system, iowait, and steal time. + func getCpuMetrics(cacheTimeMs uint16) (CpuMetrics, error) { ++ // Inside LXC, lxcfs serves /proc/stat with the host cores' counters, not ++ // the guest's own usage. Prefer the cgroup's CPU accounting there. (#2332) ++ if metrics, ok := containerCpuMetrics(cacheTimeMs); ok { ++ metrics.fromCgroup = true ++ return metrics, nil ++ } + times, err := cpu.Times(false) + if err != nil || len(times) == 0 { + return CpuMetrics{}, err +diff --git a/agent/cpu_linux.go b/agent/cpu_linux.go +new file mode 100644 +index 00000000..a50d5059 +--- /dev/null ++++ b/agent/cpu_linux.go +@@ -0,0 +1,372 @@ ++//go:build linux ++ ++package agent ++ ++import ( ++ "os" ++ "path/filepath" ++ "runtime" ++ "strconv" ++ "strings" ++ "sync" ++ "time" ++ ++ "github.com/henrygd/beszel/agent/utils" ++) ++ ++// LXC-aware CPU accounting (issue #2332). ++// ++// Inside an LXC guest, lxcfs serves /proc/stat with the raw counters of the ++// host cores in the guest's cpuset, not the guest's own usage. An idle guest ++// sharing a host core with a busy neighbor then reports near-100% CPU while ++// doing nothing. The cgroup's own accounting (cpu.stat / cpuacct.usage) ++// reflects only the guest's processes, so inside LXC we derive CPU% from that ++// instead. ++// ++// Other runtimes (Docker, Podman, k8s) are deliberately left alone: the agent ++// is normally deployed there to monitor the host, and the host's /proc/stat is ++// exactly what it should report. ++ ++// File paths and hooks are variables so tests can point them at fixtures. ++var ( ++ cpuCgroupRoot = "/sys/fs/cgroup" // default cgroup v2 mount point ++ cpuCgroupMountinfo = "/proc/self/mountinfo" ++ cpuProcSelfCgroup = "/proc/self/cgroup" ++ cpuSystemdContPath = "/run/systemd/container" ++ cpuNumCPU = runtime.NumCPU ++ cpuNow = time.Now ++) ++ ++// cpuUserHZ is the USER_HZ jiffies-per-second rate cpuacct.stat reports in. ++const cpuUserHZ = 100 ++ ++// inLxc reports whether the agent itself runs inside an LXC guest. ++// The result is cached because it cannot change during the process lifetime. ++var inLxc = sync.OnceValue(detectLxc) ++ ++// detectLxc looks for LXC guest markers that are readable without root ++// (the agent usually runs as an unprivileged user, so /proc/1/environ is not). ++func detectLxc() bool { ++ // lxcfs mounted over /proc/stat is the direct cause of the host-core ++ // counters. Only match that mount point: an LXC host also has lxcfs ++ // mounted, but at /var/lib/lxcfs. ++ if data, err := os.ReadFile(cpuCgroupMountinfo); err == nil && procStatFromLxcfs(data) { ++ return true ++ } ++ // set by liblxc for the container init and inherited on non-systemd guests ++ if os.Getenv("container") == "lxc" { ++ return true ++ } ++ // written by systemd on systemd-based guests ++ if data, err := os.ReadFile(cpuSystemdContPath); err == nil && ++ strings.TrimSpace(string(data)) == "lxc" { ++ return true ++ } ++ return false ++} ++ ++// procStatFromLxcfs reports whether mountinfo shows lxcfs mounted on /proc/stat. ++func procStatFromLxcfs(mountinfo []byte) bool { ++ for line := range strings.SplitSeq(string(mountinfo), "\n") { ++ left, right, found := strings.Cut(line, " - ") ++ if !found { ++ continue ++ } ++ fields, post := strings.Fields(left), strings.Fields(right) ++ if len(fields) >= 5 && len(post) > 0 && fields[4] == "/proc/stat" && post[0] == "fuse.lxcfs" { ++ return true ++ } ++ } ++ return false ++} ++ ++// cgroupCpuSample is one read of the container's cumulative CPU accounting. ++type cgroupCpuSample struct { ++ usageUsec uint64 ++ userUsec uint64 ++ systemUsec uint64 ++ cores float64 // usable CPU cores: affinity ∩ cpuset ∩ quota ++ at time.Time ++} ++ ++var lastCgroupCpuSamples = make(map[uint16]cgroupCpuSample) ++ ++// init seeds the LXC CPU baseline so the first reported value is a real ++// delta since startup rather than zero. ++func init() { ++ if !inLxc() { ++ return ++ } ++ if s, ok := readContainerCpuSample(); ok { ++ s.at = cpuNow() ++ lastCgroupCpuSamples[60000] = s ++ } ++} ++ ++// containerCpuMetrics derives CPU metrics from the guest's own cgroup ++// accounting when running inside LXC. It returns ok=false everywhere else and ++// whenever cgroup accounting is unreadable, so callers keep the /proc/stat ++// path. ++func containerCpuMetrics(cacheTimeMs uint16) (CpuMetrics, bool) { ++ if !inLxc() { ++ return CpuMetrics{}, false ++ } ++ cur, ok := readContainerCpuSample() ++ if !ok { ++ return CpuMetrics{}, false ++ } ++ cur.at = cpuNow() ++ ++ prev, ok := lastCgroupCpuSamples[cacheTimeMs] ++ if !ok { ++ prev = lastCgroupCpuSamples[60000] ++ } ++ lastCgroupCpuSamples[cacheTimeMs] = cur ++ ++ // No baseline yet, a backwards counter (cgroup recreated), or a ++ // non-positive clock delta: report zero this tick instead of guessing. ++ elapsedUsec := cur.at.Sub(prev.at).Microseconds() ++ if prev.at.IsZero() || elapsedUsec <= 0 || cur.usageUsec < prev.usageUsec { ++ return CpuMetrics{}, true ++ } ++ ++ cores := cur.cores ++ if cores <= 0 { ++ cores = 1 ++ } ++ window := float64(elapsedUsec) * cores ++ ++ metrics := CpuMetrics{ ++ Total: clampPercent(float64(cur.usageUsec-prev.usageUsec) / window * 100), ++ User: clampPercent(float64(cur.userUsec-prev.userUsec) / window * 100), ++ System: clampPercent(float64(cur.systemUsec-prev.systemUsec) / window * 100), ++ } ++ // cgroup accounting has no iowait/steal; everything not busy is idle. ++ metrics.Idle = clampPercent(100 - metrics.Total) ++ return metrics, true ++} ++ ++// readContainerCpuSample reads the container's cumulative CPU usage, preferring ++// the cgroup v2 unified hierarchy and falling back to the v1 cpuacct ++// controller. ++func readContainerCpuSample() (cgroupCpuSample, bool) { ++ if s, ok := readCgroupV2CpuSample(); ok { ++ return s, true ++ } ++ return readCgroupV1CpuSample() ++} ++ ++// readCgroupV2CpuSample reads usage from the unified hierarchy's cpu.stat. ++// ++// The mount root is always the cgroup to read: an LXC guest has a private ++// cgroup namespace, so /sys/fs/cgroup already is the guest's root cgroup, and ++// its cpu.stat accounts for every process in the guest. The agent's own path ++// in /proc/self/cgroup (its service cgroup, or the ".lxc" leaf when started ++// from an attached shell) only covers a subset and must not be descended into. ++func readCgroupV2CpuSample() (cgroupCpuSample, bool) { ++ if !inCgroupV2() { ++ return cgroupCpuSample{}, false // no v2 membership; try v1 ++ } ++ dir := cpuCgroupRoot ++ if mount := cgroupMountPoint("cgroup2", ""); mount != "" { ++ dir = mount ++ } ++ stat := filepath.Join(dir, "cpu.stat") ++ usage, ok := cgroupStatValue(stat, "usage_usec") ++ if !ok { ++ return cgroupCpuSample{}, false ++ } ++ s := cgroupCpuSample{usageUsec: usage, cores: cpuCgroupCores(dir)} ++ s.userUsec, _ = cgroupStatValue(stat, "user_usec") ++ s.systemUsec, _ = cgroupStatValue(stat, "system_usec") ++ return s, true ++} ++ ++// readCgroupV1CpuSample reads usage from the legacy cpuacct controller. ++// As with v2, the hierarchy mount root is the guest's own cgroup and its ++// accounting includes every child cgroup, so it is read directly rather than ++// the agent's own sub-cgroup. ++func readCgroupV1CpuSample() (cgroupCpuSample, bool) { ++ dir := cgroupMountPoint("cgroup", "cpuacct") ++ if dir == "" { ++ return cgroupCpuSample{}, false ++ } ++ usageNs, ok := utils.ReadUintFile(filepath.Join(dir, "cpuacct.usage")) ++ if !ok { ++ return cgroupCpuSample{}, false ++ } ++ s := cgroupCpuSample{usageUsec: usageNs / 1000, cores: cpuCgroupCores(dir)} ++ // cpuacct.stat reports user/system in USER_HZ jiffies. ++ if v, ok := cgroupStatValue(filepath.Join(dir, "cpuacct.stat"), "user"); ok { ++ s.userUsec = v * 1e6 / cpuUserHZ ++ } ++ if v, ok := cgroupStatValue(filepath.Join(dir, "cpuacct.stat"), "system"); ok { ++ s.systemUsec = v * 1e6 / cpuUserHZ ++ } ++ return s, true ++} ++ ++// inCgroupV2 reports whether /proc/self/cgroup lists the v2 unified hierarchy ++// (a "0::" entry). ++func inCgroupV2() bool { ++ data, err := os.ReadFile(cpuProcSelfCgroup) ++ if err != nil { ++ return false ++ } ++ for line := range strings.SplitSeq(string(data), "\n") { ++ if strings.HasPrefix(line, "0::") { ++ return true ++ } ++ } ++ return false ++} ++ ++// cgroupMountPoint returns the mount point of a cgroup hierarchy from ++// /proc/self/mountinfo: the cgroup2 mount for v2, or the cgroup mount whose ++// super options list the wanted v1 controller. ++func cgroupMountPoint(fstype, v1ctrl string) string { ++ data, err := os.ReadFile(cpuCgroupMountinfo) ++ if err != nil { ++ return "" ++ } ++ for _, line := range strings.Split(string(data), "\n") { ++ left, right, found := strings.Cut(line, " - ") ++ if !found { ++ continue ++ } ++ post := strings.Fields(right) ++ if len(post) == 0 || post[0] != fstype { ++ continue ++ } ++ if v1ctrl != "" && !mountOptHas(post, v1ctrl) { ++ continue ++ } ++ fields := strings.Fields(left) ++ if len(fields) >= 5 { ++ return unescapeMountPoint(fields[4]) ++ } ++ } ++ return "" ++} ++ ++// mountOptHas reports whether the comma-separated super options (field 3 after ++// the " - " separator) contain opt. ++func mountOptHas(post []string, opt string) bool { ++ if len(post) < 3 { ++ return false ++ } ++ for _, o := range strings.Split(post[2], ",") { ++ if o == opt { ++ return true ++ } ++ } ++ return false ++} ++ ++// unescapeMountPoint decodes octal escapes (e.g. \040 for space) used in ++// mountinfo paths. ++func unescapeMountPoint(s string) string { ++ return strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`).Replace(s) ++} ++ ++// cpuCgroupCores returns how many CPU cores the cgroup at dir may use: the ++// smallest of the process affinity mask, the cgroup cpuset, and the CPU quota. ++func cpuCgroupCores(dir string) float64 { ++ cores := float64(cpuNumCPU()) ++ if n := cpusetCount(dir); n > 0 && n < cores { ++ cores = n ++ } ++ if q, ok := cpuQuotaCores(dir); ok && q < cores { ++ cores = q ++ } ++ if cores <= 0 { ++ cores = 1 ++ } ++ return cores ++} ++ ++// cpusetCount returns the number of CPUs in the cgroup's cpuset, e.g. "0-3" or ++// "2,5-7". An empty or missing file means unconstrained. ++func cpusetCount(dir string) float64 { ++ for _, name := range []string{"cpuset.cpus.effective", "cpuset.cpus"} { ++ raw, err := os.ReadFile(filepath.Join(dir, name)) ++ if err != nil { ++ continue ++ } ++ if n := countCpuList(strings.TrimSpace(string(raw))); n > 0 { ++ return float64(n) ++ } ++ } ++ return 0 ++} ++ ++// countCpuList counts the CPUs in a Linux CPU list like "0-3,5,8-9". ++func countCpuList(list string) int { ++ total := 0 ++ for part := range strings.SplitSeq(list, ",") { ++ lo, hi, ranged := strings.Cut(part, "-") ++ a, err := strconv.Atoi(lo) ++ if err != nil { ++ continue ++ } ++ b := a ++ if ranged { ++ if v, err := strconv.Atoi(hi); err == nil { ++ b = v ++ } ++ } ++ if b >= a { ++ total += b - a + 1 ++ } ++ } ++ return total ++} ++ ++// cpuQuotaCores returns the cgroup's CPU quota in cores. v2 uses cpu.max ++// (" "), v1 uses cpu.cfs_quota_us / cpu.cfs_period_us. ++func cpuQuotaCores(dir string) (float64, bool) { ++ if raw, err := os.ReadFile(filepath.Join(dir, "cpu.max")); err == nil { ++ fields := strings.Fields(string(raw)) ++ if len(fields) == 2 && fields[0] != "max" { ++ if quota, err := strconv.ParseFloat(fields[0], 64); err == nil && quota > 0 { ++ if period, err := strconv.ParseFloat(fields[1], 64); err == nil && period > 0 { ++ return quota / period, true ++ } ++ } ++ } ++ } ++ if quota, ok := readCgroupInt(filepath.Join(dir, "cpu.cfs_quota_us")); ok && quota > 0 { ++ if period, ok := readCgroupInt(filepath.Join(dir, "cpu.cfs_period_us")); ok && period > 0 { ++ return float64(quota) / float64(period), true ++ } ++ } ++ return 0, false ++} ++ ++// cgroupStatValue returns the value of key in a cgroup "key value" stat file. ++func cgroupStatValue(path, key string) (uint64, bool) { ++ data, err := os.ReadFile(path) ++ if err != nil { ++ return 0, false ++ } ++ for line := range strings.SplitSeq(string(data), "\n") { ++ name, value, found := strings.Cut(line, " ") ++ if !found || name != key { ++ continue ++ } ++ v, err := strconv.ParseUint(strings.TrimSpace(value), 10, 64) ++ return v, err == nil ++ } ++ return 0, false ++} ++ ++// readCgroupInt reads a file containing a single signed integer ++// (cpu.cfs_quota_us is -1 when no quota is set). ++func readCgroupInt(path string) (int64, bool) { ++ data, err := os.ReadFile(path) ++ if err != nil { ++ return 0, false ++ } ++ v, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64) ++ return v, err == nil ++} +diff --git a/agent/cpu_linux_test.go b/agent/cpu_linux_test.go +new file mode 100644 +index 00000000..337ad76b +--- /dev/null ++++ b/agent/cpu_linux_test.go +@@ -0,0 +1,350 @@ ++//go:build testing && linux ++ ++package agent ++ ++import ( ++ "os" ++ "path/filepath" ++ "sync" ++ "testing" ++ "time" ++ ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/require" ++) ++ ++// swapCpuContainerSeams points every container-detection and cgroup path at ++// empty fixtures under a temp dir, then restores them on cleanup. ++func swapCpuContainerSeams(t *testing.T) { ++ t.Helper() ++ backup := struct { ++ root, mountinfo, selfCgroup, systemdCont string ++ numCPU func() int ++ now func() time.Time ++ }{ ++ cpuCgroupRoot, cpuCgroupMountinfo, cpuProcSelfCgroup, cpuSystemdContPath, cpuNumCPU, cpuNow, ++ } ++ origInLxc := inLxc ++ samples := lastCgroupCpuSamples ++ env, hadEnv := os.LookupEnv("container") ++ t.Cleanup(func() { ++ cpuCgroupRoot, cpuCgroupMountinfo, cpuProcSelfCgroup, cpuSystemdContPath = backup.root, backup.mountinfo, backup.selfCgroup, backup.systemdCont ++ cpuNumCPU, cpuNow = backup.numCPU, backup.now ++ inLxc = origInLxc ++ lastCgroupCpuSamples = samples ++ if hadEnv { ++ os.Setenv("container", env) ++ } ++ }) ++ ++ inLxc = sync.OnceValue(detectLxc) ++ lastCgroupCpuSamples = make(map[uint16]cgroupCpuSample) ++ os.Unsetenv("container") ++ ++ tmp := t.TempDir() ++ cpuCgroupRoot = filepath.Join(tmp, "cgroup") ++ cpuCgroupMountinfo = filepath.Join(tmp, "mountinfo") ++ cpuProcSelfCgroup = filepath.Join(tmp, "self-cgroup") ++ cpuSystemdContPath = filepath.Join(tmp, "systemd-container") ++} ++ ++func writeCpuFixture(t *testing.T, path, contents string) { ++ t.Helper() ++ require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) ++ require.NoError(t, os.WriteFile(path, []byte(contents), 0o644)) ++} ++ ++// markLxc makes detection see a systemd-based LXC guest. ++func markLxc(t *testing.T) { ++ t.Helper() ++ writeCpuFixture(t, cpuSystemdContPath, "lxc\n") ++} ++ ++// fakeNow installs a controllable clock and returns a function to advance it. ++func fakeNow(t *testing.T) func(time.Duration) { ++ t.Helper() ++ cur := time.Unix(1_700_000_000, 0) ++ cpuNow = func() time.Time { return cur } ++ return func(d time.Duration) { cur = cur.Add(d) } ++} ++ ++func TestDetectLxc(t *testing.T) { ++ tests := []struct { ++ name string ++ setup func(t *testing.T) ++ want bool ++ }{ ++ {"plain host", func(t *testing.T) {}, false}, ++ {"container env lxc", func(t *testing.T) { t.Setenv("container", "lxc") }, true}, ++ {"container env podman", func(t *testing.T) { t.Setenv("container", "podman") }, false}, ++ {"systemd container lxc", func(t *testing.T) { writeCpuFixture(t, cpuSystemdContPath, "lxc\n") }, true}, ++ {"systemd container nspawn", func(t *testing.T) { writeCpuFixture(t, cpuSystemdContPath, "systemd-nspawn\n") }, false}, ++ {"lxcfs serving /proc/stat", func(t *testing.T) { ++ writeCpuFixture(t, cpuCgroupMountinfo, ++ "31 25 0:28 / /proc/stat rw,nosuid,nodev,relatime - fuse.lxcfs lxcfs rw,user_id=0,group_id=0\n") ++ }, true}, ++ // an LXC host (e.g. Proxmox) mounts lxcfs too, but not over its own /proc ++ {"lxcfs mounted on host", func(t *testing.T) { ++ writeCpuFixture(t, cpuCgroupMountinfo, ++ "45 25 0:40 / /var/lib/lxcfs rw,nosuid,nodev,relatime - fuse.lxcfs lxcfs rw,user_id=0,group_id=0\n") ++ }, false}, ++ {"cgroup-only mountinfo", func(t *testing.T) { ++ writeCpuFixture(t, cpuCgroupMountinfo, ++ "36 25 0:32 / /sys/fs/cgroup rw - cgroup2 cgroup2 rw,nsdelegate\n") ++ }, false}, ++ } ++ for _, tt := range tests { ++ t.Run(tt.name, func(t *testing.T) { ++ swapCpuContainerSeams(t) ++ tt.setup(t) ++ assert.Equal(t, tt.want, detectLxc()) ++ }) ++ } ++} ++ ++func TestReadCgroupV2CpuSample(t *testing.T) { ++ swapCpuContainerSeams(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ require.NoError(t, os.MkdirAll(cpuCgroupRoot, 0o755)) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), ++ "usage_usec 3000000\nuser_usec 2000000\nsystem_usec 1000000\nnr_throttled 7\n") ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpuset.cpus.effective"), "2,5-7\n") ++ cpuNumCPU = func() int { return 8 } ++ ++ s, ok := readCgroupV2CpuSample() ++ require.True(t, ok) ++ assert.EqualValues(t, 3000000, s.usageUsec) ++ assert.EqualValues(t, 2000000, s.userUsec) ++ assert.EqualValues(t, 1000000, s.systemUsec) ++ assert.InDelta(t, 4, s.cores, 0.001) // cpuset 2,5-7 = 4 cores ++} ++ ++// The agent may sit in a sub-cgroup of the guest (a systemd service, or the ++// ".lxc" leaf when started from an attached shell); the mount root still ++// accounts for the whole guest and must win. ++func TestReadCgroupV2PrefersContainerRoot(t *testing.T) { ++ for _, rel := range []string{"system.slice/beszel-agent.service", ".lxc"} { ++ t.Run(rel, func(t *testing.T) { ++ swapCpuContainerSeams(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/"+rel+"\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 9000\n") ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, rel, "cpu.stat"), "usage_usec 5\n") ++ ++ s, ok := readCgroupV2CpuSample() ++ require.True(t, ok) ++ assert.EqualValues(t, 9000, s.usageUsec) ++ }) ++ } ++} ++ ++// Same for v1: the cpuacct mount root covers the agent's sibling services. ++func TestReadCgroupV1PrefersContainerRoot(t *testing.T) { ++ swapCpuContainerSeams(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "3:cpu,cpuacct:/system.slice/beszel-agent.service\n") ++ v1 := filepath.Join(t.TempDir(), "cpu,cpuacct") ++ writeCpuFixture(t, cpuCgroupMountinfo, ++ "30 25 0:26 / "+v1+" rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,cpu,cpuacct\n") ++ writeCpuFixture(t, filepath.Join(v1, "cpuacct.usage"), "9000000\n") ++ writeCpuFixture(t, filepath.Join(v1, "system.slice/beszel-agent.service/cpuacct.usage"), "5000\n") ++ ++ s, ok := readContainerCpuSample() ++ require.True(t, ok) ++ assert.EqualValues(t, 9000, s.usageUsec) ++} ++ ++func TestReadCgroupV1CpuSample(t *testing.T) { ++ swapCpuContainerSeams(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "3:cpuacct:/\n2:memory:/\n") ++ v1 := filepath.Join(t.TempDir(), "cpuacct") ++ writeCpuFixture(t, cpuCgroupMountinfo, ++ "30 25 0:26 / "+v1+" rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,cpuacct\n") ++ writeCpuFixture(t, filepath.Join(v1, "cpuacct.usage"), "2000000000\n") ++ writeCpuFixture(t, filepath.Join(v1, "cpuacct.stat"), "user 100\nsystem 50\n") ++ cpuNumCPU = func() int { return 4 } ++ ++ s, ok := readContainerCpuSample() // no 0:: line -> falls through to v1 ++ require.True(t, ok) ++ assert.EqualValues(t, 2000000, s.usageUsec) // ns -> usec ++ assert.EqualValues(t, 1000000, s.userUsec) // 100 jiffies * 1e6/100 ++ assert.EqualValues(t, 500000, s.systemUsec) // 50 jiffies ++ assert.InDelta(t, 4, s.cores, 0.001) ++} ++ ++func TestContainerCpuMetricsMath(t *testing.T) { ++ swapCpuContainerSeams(t) ++ markLxc(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ require.NoError(t, os.MkdirAll(cpuCgroupRoot, 0o755)) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpuset.cpus.effective"), "0-3\n") ++ cpuNumCPU = func() int { return 8 } ++ advance := fakeNow(t) ++ ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), ++ "usage_usec 1000000\nuser_usec 600000\nsystem_usec 400000\n") ++ m, ok := containerCpuMetrics(60000) ++ require.True(t, ok) ++ assert.Zero(t, m.Total) // first call only seeds the baseline ++ ++ // 1s elapsed, container burned 2 core-seconds on 4 usable cores ++ advance(time.Second) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), ++ "usage_usec 3000000\nuser_usec 1600000\nsystem_usec 900000\n") ++ m, ok = containerCpuMetrics(60000) ++ require.True(t, ok) ++ assert.InDelta(t, 50, m.Total, 0.01) ++ assert.InDelta(t, 25, m.User, 0.01) ++ assert.InDelta(t, 12.5, m.System, 0.01) ++ assert.Zero(t, m.Iowait) ++ assert.Zero(t, m.Steal) ++ assert.InDelta(t, 50, m.Idle, 0.01) ++} ++ ++func TestContainerCpuMetricsHonorsQuota(t *testing.T) { ++ swapCpuContainerSeams(t) ++ markLxc(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ require.NoError(t, os.MkdirAll(cpuCgroupRoot, 0o755)) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.max"), "200000 100000\n") // 2 cores ++ cpuNumCPU = func() int { return 8 } ++ advance := fakeNow(t) ++ ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 1000000\n") ++ containerCpuMetrics(60000) ++ advance(time.Second) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 2000000\n") ++ m, ok := containerCpuMetrics(60000) ++ require.True(t, ok) ++ assert.InDelta(t, 50, m.Total, 0.01) // 1 core-second against a 2-core quota ++} ++ ++func TestContainerCpuMetricsZeroAndBackwardDelta(t *testing.T) { ++ swapCpuContainerSeams(t) ++ markLxc(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ require.NoError(t, os.MkdirAll(cpuCgroupRoot, 0o755)) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 5000000\n") ++ cpuNumCPU = func() int { return 4 } ++ advance := fakeNow(t) ++ ++ // seed the baseline, then do not advance the clock: elapsed <= 0 ++ containerCpuMetrics(60000) ++ m, ok := containerCpuMetrics(60000) ++ require.True(t, ok) ++ assert.Zero(t, m.Total) ++ ++ // counter goes backwards (cgroup recreated): report zero and re-baseline ++ advance(time.Second) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 100000\n") ++ m, ok = containerCpuMetrics(60000) ++ require.True(t, ok) ++ assert.Zero(t, m.Total) ++ ++ // next tick measures from the new baseline, not the stale one ++ advance(time.Second) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 1100000\n") ++ m, ok = containerCpuMetrics(60000) ++ require.True(t, ok) ++ assert.InDelta(t, 25, m.Total, 0.01) // 1e6 usec / (1s * 4 cores) ++} ++ ++func TestContainerCpuMetricsFallbacks(t *testing.T) { ++ t.Run("not in lxc", func(t *testing.T) { ++ swapCpuContainerSeams(t) ++ _, ok := containerCpuMetrics(60000) ++ assert.False(t, ok) ++ }) ++ // Docker agents monitor the host, so cgroup accounting must not kick in ++ // even when it is readable and no LXC marker is present. ++ t.Run("docker container", func(t *testing.T) { ++ swapCpuContainerSeams(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 5000000\n") ++ _, ok := containerCpuMetrics(60000) ++ assert.False(t, ok) ++ }) ++ t.Run("in lxc without cgroup accounting", func(t *testing.T) { ++ swapCpuContainerSeams(t) ++ markLxc(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ // cpuCgroupRoot has no cpu.stat ++ _, ok := containerCpuMetrics(60000) ++ assert.False(t, ok) ++ }) ++} ++ ++// The host path must keep reporting through gopsutil untouched. ++func TestGetCpuMetricsHostFallback(t *testing.T) { ++ swapCpuContainerSeams(t) ++ m, err := getCpuMetrics(60000) ++ require.NoError(t, err) ++ assert.False(t, m.fromCgroup) ++ assert.GreaterOrEqual(t, m.Total, 0.0) ++ assert.LessOrEqual(t, m.Total, 100.0) ++} ++ ++// Inside LXC getCpuMetrics must report the cgroup-derived value, not ++// the host core counters from /proc/stat. ++func TestGetCpuMetricsPrefersCgroup(t *testing.T) { ++ swapCpuContainerSeams(t) ++ markLxc(t) ++ writeCpuFixture(t, cpuProcSelfCgroup, "0::/\n") ++ writeCpuFixture(t, cpuCgroupMountinfo, "") ++ require.NoError(t, os.MkdirAll(cpuCgroupRoot, 0o755)) ++ cpuNumCPU = func() int { return 4 } ++ advance := fakeNow(t) ++ ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 0\n") ++ m, err := getCpuMetrics(60000) ++ require.NoError(t, err) ++ assert.Zero(t, m.Total) ++ ++ advance(time.Second) ++ writeCpuFixture(t, filepath.Join(cpuCgroupRoot, "cpu.stat"), "usage_usec 2000000\n") ++ m, err = getCpuMetrics(60000) ++ require.NoError(t, err) ++ assert.InDelta(t, 50, m.Total, 0.01) ++ assert.True(t, m.fromCgroup) // per-core usage is skipped for this source ++} ++ ++func TestCountCpuList(t *testing.T) { ++ assert.Equal(t, 4, countCpuList("0-3")) ++ assert.Equal(t, 4, countCpuList("2,5-7")) ++ assert.Equal(t, 1, countCpuList("2")) ++ assert.Equal(t, 0, countCpuList("")) ++ assert.Equal(t, 0, countCpuList("max")) ++ assert.Equal(t, 6, countCpuList("0-3,8-9")) ++} ++ ++func TestCpuQuotaCores(t *testing.T) { ++ dir := t.TempDir() ++ _, ok := cpuQuotaCores(dir) ++ assert.False(t, ok) // no quota files ++ ++ writeCpuFixture(t, filepath.Join(dir, "cpu.max"), "max 100000\n") ++ _, ok = cpuQuotaCores(dir) ++ assert.False(t, ok) // unlimited ++ ++ writeCpuFixture(t, filepath.Join(dir, "cpu.max"), "150000 100000\n") ++ q, ok := cpuQuotaCores(dir) ++ require.True(t, ok) ++ assert.InDelta(t, 1.5, q, 0.001) ++ ++ // v1 files ++ v1 := t.TempDir() ++ writeCpuFixture(t, filepath.Join(v1, "cpu.cfs_quota_us"), "-1\n") ++ writeCpuFixture(t, filepath.Join(v1, "cpu.cfs_period_us"), "100000\n") ++ _, ok = cpuQuotaCores(v1) ++ assert.False(t, ok) ++ ++ writeCpuFixture(t, filepath.Join(v1, "cpu.cfs_quota_us"), "50000\n") ++ q, ok = cpuQuotaCores(v1) ++ require.True(t, ok) ++ assert.InDelta(t, 0.5, q, 0.001) ++} +diff --git a/agent/cpu_unsupported.go b/agent/cpu_unsupported.go +new file mode 100644 +index 00000000..886941f8 +--- /dev/null ++++ b/agent/cpu_unsupported.go +@@ -0,0 +1,9 @@ ++//go:build !linux ++ ++package agent ++ ++// containerCpuMetrics is Linux-only (cgroup accounting). Other platforms keep ++// the gopsutil /proc path. ++func containerCpuMetrics(uint16) (CpuMetrics, bool) { ++ return CpuMetrics{}, false ++} +diff --git a/agent/system.go b/agent/system.go +index 3373e1aa..f567585f 100644 +--- a/agent/system.go ++++ b/agent/system.go +@@ -170,9 +170,13 @@ func (a *Agent) getSystemStats(cacheTimeMs uint16) system.Stats { + slog.Error("Error getting cpu metrics", "err", err) + } + +- // per-core cpu usage +- if perCoreUsage, err := getPerCoreCpuUsage(cacheTimeMs); err == nil { +- systemStats.CpuCoresUsage = perCoreUsage ++ // per-core cpu usage. Skipped when the total comes from cgroup accounting: ++ // per-core /proc/stat counters there describe shared host cores, not the ++ // guest, and would contradict the total. ++ if !cpuMetrics.fromCgroup { ++ if perCoreUsage, err := getPerCoreCpuUsage(cacheTimeMs); err == nil { ++ systemStats.CpuCoresUsage = perCoreUsage ++ } + } + + // load average diff --git a/tasks/henrygd__beszel-2341/tests/test.sh b/tasks/henrygd__beszel-2341/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bc8e2875a169fb2e6e9d3d08d0e1409889ead374 --- /dev/null +++ b/tasks/henrygd__beszel-2341/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 c394a6b5b16f029bacd8d093cc6893c2d1bcc13d > "$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/henrygd__beszel-2341/tests/verifier.py b/tasks/henrygd__beszel-2341/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2341/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/henrygd__beszel-2355/environment/Dockerfile b/tasks/henrygd__beszel-2355/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..08ee1d6314f6250b126233fbcc846342f7b8cc50 --- /dev/null +++ b/tasks/henrygd__beszel-2355/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a0dc19eacf6902d2f6934a3efd7ea7277198c40b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a0dc19eacf6902d2f6934a3efd7ea7277198c40b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a0dc19eacf6902d2f6934a3efd7ea7277198c40b \ + && 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/henrygd__beszel-2355/instruction.md b/tasks/henrygd__beszel-2355/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5c2cf4873777fd84a2719c2a8a5e1a19f4c5a41d --- /dev/null +++ b/tasks/henrygd__beszel-2355/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** chore(helm): update app version to 0.20.0 + +## Description + +Updates the Helm charts for [Beszel 0.20.0](https://github.com/henrygd/beszel/releases/tag/v0.20.0) and bumps their chart patch versions. Merging this pull request publishes the updated charts to GHCR. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a0dc19eacf69`. 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/henrygd__beszel-2355/solution/patch.diff b/tasks/henrygd__beszel-2355/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..eba40d7a8a944f378b4b38de0e25fe0e8c379a83 --- /dev/null +++ b/tasks/henrygd__beszel-2355/solution/patch.diff @@ -0,0 +1,94 @@ +diff --git a/supplemental/helm/beszel-agent/Chart.yaml b/supplemental/helm/beszel-agent/Chart.yaml +index 1d891cd3..9c404dd4 100644 +--- a/supplemental/helm/beszel-agent/Chart.yaml ++++ b/supplemental/helm/beszel-agent/Chart.yaml +@@ -2,9 +2,9 @@ apiVersion: v1 + description: Installs beszel-agent in kubernetes + home: https://github.com/henrygd/beszel/tree/main/supplemental/helm/beszel-agent + name: beszel-agent +-appVersion: "0.19.0" ++appVersion: "0.20.0" + # Bump this version when publishing chart changes. +-version: 0.1.6 ++version: 0.1.7 + sources: + - https://github.com/henrygd/beszel/tree/main/supplemental/helm/beszel-agent + - https://www.beszel.dev/ +diff --git a/supplemental/helm/beszel-agent/README.md b/supplemental/helm/beszel-agent/README.md +index a1ba9da6..dd9cd244 100644 +--- a/supplemental/helm/beszel-agent/README.md ++++ b/supplemental/helm/beszel-agent/README.md +@@ -80,7 +80,7 @@ Essential parameters to configure: + | `secret.sshKey` | `ssh-key` | Key name in the secret for the SSH public key | + | `secret.tokenKey` | `token` | Key name in the secret for the authentication token | + | `image.repository` | `henrygd/beszel-agent` | Container image | +-| `image.tag` | Chart AppVersion (0.19.0) | Image version | ++| `image.tag` | Chart AppVersion (0.20.0) | Image version | + | `hostNetwork` | `false` | Use host network for network monitoring | + | `tolerations` | Allows all taints | Tolerations for running on tainted nodes | + +@@ -385,7 +385,7 @@ helm upgrade beszel-agent ./beszel-agent \ + + # Change image version + helm upgrade beszel-agent ./beszel-agent \ +- --set image.tag="0.19.0" ++ --set image.tag="0.20.0" + ``` + + ### Restart All Agents +@@ -522,7 +522,7 @@ kubectl get secret beszel-agent -o jsonpath='{.data.ssh-key}' | base64 -d + ## Chart Information + + - **Chart Version**: 0.1.0 +-- **App Version**: 0.19.0 ++- **App Version**: 0.20.0 + - **Kubernetes Version**: 1.19+ + - **Maintainer**: cloudwithdan (nikoloskid@pm.me) + +diff --git a/supplemental/helm/beszel-hub/Chart.yaml b/supplemental/helm/beszel-hub/Chart.yaml +index bdb89121..6883cb7f 100644 +--- a/supplemental/helm/beszel-hub/Chart.yaml ++++ b/supplemental/helm/beszel-hub/Chart.yaml +@@ -2,9 +2,9 @@ apiVersion: v1 + description: Installs beszel-hub in kubernetes + home: https://github.com/henrygd/beszel/tree/main/supplemental/helm/beszel-hub + name: beszel-hub +-appVersion: "0.19.0" ++appVersion: "0.20.0" + # Bump this version when publishing chart changes. +-version: 0.1.6 ++version: 0.1.7 + sources: + - https://github.com/henrygd/beszel/tree/main/supplemental/helm/beszel-hub + - https://www.beszel.dev/ +diff --git a/supplemental/helm/beszel-hub/README.md b/supplemental/helm/beszel-hub/README.md +index ee254bbc..ecc68279 100644 +--- a/supplemental/helm/beszel-hub/README.md ++++ b/supplemental/helm/beszel-hub/README.md +@@ -47,7 +47,7 @@ Key configuration options in `values.yaml`: + |-----------|---------|-------------| + | `replicaCount` | `1` | Number of Beszel Hub replicas | + | `image.repository` | `henrygd/beszel` | Container image repository | +-| `image.tag` | Chart AppVersion (0.19.0) | Container image tag | ++| `image.tag` | Chart AppVersion (0.20.0) | Container image tag | + | `image.pullPolicy` | `IfNotPresent` | Image pull policy | + | `service.port` | `8090` | Service port | + | `persistentVolumeClaim.enabled` | `true` | Enable persistent volume | +@@ -169,7 +169,7 @@ tolerations: + ```yaml + replicaCount: 3 + image: +- tag: "0.19.0" ++ tag: "0.20.0" + service: + type: LoadBalancer + ingress: +@@ -330,7 +330,7 @@ By default, Beszel Hub uses a PersistentVolumeClaim for data storage. Ensure you + ## Chart Information + + - **Chart Version**: 0.1.0 +-- **App Version**: 0.19.0 ++- **App Version**: 0.20.0 + - **Kubernetes Version**: 1.19+ + - **Maintainer**: cloudwithdan (nikoloskid@pm.me) + diff --git a/tasks/henrygd__beszel-2355/solution/solve.sh b/tasks/henrygd__beszel-2355/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2355/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/henrygd__beszel-2355/task.toml b/tasks/henrygd__beszel-2355/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fd899e42f9d810e4c4828191e4542bf8d79a5368 --- /dev/null +++ b/tasks/henrygd__beszel-2355/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2355" +description = "chore(helm): update app version to 0.20.0" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "a0dc19eacf6902d2f6934a3efd7ea7277198c40b" +reference = "https://github.com/henrygd/beszel/pull/2355" +source_access = "auto" +built_at = "2026-11-16T16:09:53.495374+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a79fbc16284d4fda9702ad94a6fb79819be692a9446ec6f55cf930be3a93aea4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-19T15:39:14Z" +diff_format = "unified" +context_files = [ + "supplemental/helm/beszel-agent/Chart.yaml", + "supplemental/helm/beszel-agent/README.md", + "supplemental/helm/beszel-hub/Chart.yaml", + "supplemental/helm/beszel-hub/README.md", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 20 +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:00.816125+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4097232dbdd78b841413b4096a0387fb9d2fdff5e80f3843a3ba535089d3515e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2355/tests/capture.py b/tasks/henrygd__beszel-2355/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2355/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/henrygd__beszel-2355/tests/instruction.md b/tasks/henrygd__beszel-2355/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5c2cf4873777fd84a2719c2a8a5e1a19f4c5a41d --- /dev/null +++ b/tasks/henrygd__beszel-2355/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** chore(helm): update app version to 0.20.0 + +## Description + +Updates the Helm charts for [Beszel 0.20.0](https://github.com/henrygd/beszel/releases/tag/v0.20.0) and bumps their chart patch versions. Merging this pull request publishes the updated charts to GHCR. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a0dc19eacf69`. 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/henrygd__beszel-2355/tests/oracle.patch b/tasks/henrygd__beszel-2355/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..eba40d7a8a944f378b4b38de0e25fe0e8c379a83 --- /dev/null +++ b/tasks/henrygd__beszel-2355/tests/oracle.patch @@ -0,0 +1,94 @@ +diff --git a/supplemental/helm/beszel-agent/Chart.yaml b/supplemental/helm/beszel-agent/Chart.yaml +index 1d891cd3..9c404dd4 100644 +--- a/supplemental/helm/beszel-agent/Chart.yaml ++++ b/supplemental/helm/beszel-agent/Chart.yaml +@@ -2,9 +2,9 @@ apiVersion: v1 + description: Installs beszel-agent in kubernetes + home: https://github.com/henrygd/beszel/tree/main/supplemental/helm/beszel-agent + name: beszel-agent +-appVersion: "0.19.0" ++appVersion: "0.20.0" + # Bump this version when publishing chart changes. +-version: 0.1.6 ++version: 0.1.7 + sources: + - https://github.com/henrygd/beszel/tree/main/supplemental/helm/beszel-agent + - https://www.beszel.dev/ +diff --git a/supplemental/helm/beszel-agent/README.md b/supplemental/helm/beszel-agent/README.md +index a1ba9da6..dd9cd244 100644 +--- a/supplemental/helm/beszel-agent/README.md ++++ b/supplemental/helm/beszel-agent/README.md +@@ -80,7 +80,7 @@ Essential parameters to configure: + | `secret.sshKey` | `ssh-key` | Key name in the secret for the SSH public key | + | `secret.tokenKey` | `token` | Key name in the secret for the authentication token | + | `image.repository` | `henrygd/beszel-agent` | Container image | +-| `image.tag` | Chart AppVersion (0.19.0) | Image version | ++| `image.tag` | Chart AppVersion (0.20.0) | Image version | + | `hostNetwork` | `false` | Use host network for network monitoring | + | `tolerations` | Allows all taints | Tolerations for running on tainted nodes | + +@@ -385,7 +385,7 @@ helm upgrade beszel-agent ./beszel-agent \ + + # Change image version + helm upgrade beszel-agent ./beszel-agent \ +- --set image.tag="0.19.0" ++ --set image.tag="0.20.0" + ``` + + ### Restart All Agents +@@ -522,7 +522,7 @@ kubectl get secret beszel-agent -o jsonpath='{.data.ssh-key}' | base64 -d + ## Chart Information + + - **Chart Version**: 0.1.0 +-- **App Version**: 0.19.0 ++- **App Version**: 0.20.0 + - **Kubernetes Version**: 1.19+ + - **Maintainer**: cloudwithdan (nikoloskid@pm.me) + +diff --git a/supplemental/helm/beszel-hub/Chart.yaml b/supplemental/helm/beszel-hub/Chart.yaml +index bdb89121..6883cb7f 100644 +--- a/supplemental/helm/beszel-hub/Chart.yaml ++++ b/supplemental/helm/beszel-hub/Chart.yaml +@@ -2,9 +2,9 @@ apiVersion: v1 + description: Installs beszel-hub in kubernetes + home: https://github.com/henrygd/beszel/tree/main/supplemental/helm/beszel-hub + name: beszel-hub +-appVersion: "0.19.0" ++appVersion: "0.20.0" + # Bump this version when publishing chart changes. +-version: 0.1.6 ++version: 0.1.7 + sources: + - https://github.com/henrygd/beszel/tree/main/supplemental/helm/beszel-hub + - https://www.beszel.dev/ +diff --git a/supplemental/helm/beszel-hub/README.md b/supplemental/helm/beszel-hub/README.md +index ee254bbc..ecc68279 100644 +--- a/supplemental/helm/beszel-hub/README.md ++++ b/supplemental/helm/beszel-hub/README.md +@@ -47,7 +47,7 @@ Key configuration options in `values.yaml`: + |-----------|---------|-------------| + | `replicaCount` | `1` | Number of Beszel Hub replicas | + | `image.repository` | `henrygd/beszel` | Container image repository | +-| `image.tag` | Chart AppVersion (0.19.0) | Container image tag | ++| `image.tag` | Chart AppVersion (0.20.0) | Container image tag | + | `image.pullPolicy` | `IfNotPresent` | Image pull policy | + | `service.port` | `8090` | Service port | + | `persistentVolumeClaim.enabled` | `true` | Enable persistent volume | +@@ -169,7 +169,7 @@ tolerations: + ```yaml + replicaCount: 3 + image: +- tag: "0.19.0" ++ tag: "0.20.0" + service: + type: LoadBalancer + ingress: +@@ -330,7 +330,7 @@ By default, Beszel Hub uses a PersistentVolumeClaim for data storage. Ensure you + ## Chart Information + + - **Chart Version**: 0.1.0 +-- **App Version**: 0.19.0 ++- **App Version**: 0.20.0 + - **Kubernetes Version**: 1.19+ + - **Maintainer**: cloudwithdan (nikoloskid@pm.me) + diff --git a/tasks/henrygd__beszel-2355/tests/test.sh b/tasks/henrygd__beszel-2355/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9b8883926ae71ddb2786fbe696830f69999ef3e1 --- /dev/null +++ b/tasks/henrygd__beszel-2355/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 a0dc19eacf6902d2f6934a3efd7ea7277198c40b > "$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/henrygd__beszel-2355/tests/verifier.py b/tasks/henrygd__beszel-2355/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2355/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/henrygd__beszel-2362/environment/Dockerfile b/tasks/henrygd__beszel-2362/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7ce6b7a475f7b2ec17784a809b38e427269e5beb --- /dev/null +++ b/tasks/henrygd__beszel-2362/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 97e6f64bdcb926b8d0436f358942c098a46b6237 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 97e6f64bdcb926b8d0436f358942c098a46b6237 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 97e6f64bdcb926b8d0436f358942c098a46b6237 \ + && 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/henrygd__beszel-2362/instruction.md b/tasks/henrygd__beszel-2362/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..99a9b27a3b752c05da2471710fb00a63a8033612 --- /dev/null +++ b/tasks/henrygd__beszel-2362/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(i18n): extract bulk monitor format hint + +## Description + +## 📃 Description + +Adds translation keys for the new section. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97e6f64bdcb9`. 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/henrygd__beszel-2362/solution/patch.diff b/tasks/henrygd__beszel-2362/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..fd4e8f70d4e2f5e12d2069388ed6e356d368ea3f --- /dev/null +++ b/tasks/henrygd__beszel-2362/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +index 733935dc..66c642be 100644 +--- a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx ++++ b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +@@ -485,7 +485,9 @@ export function AddMonitorDialog({ systemId, monitors }: { systemId?: string; mo + + Bulk Add {{ foo: t`Network Monitors` }} + +- target[,protocol[,port[,interval]]] ++ ++ target[,protocol[,port[,interval]]] ++ + +
+
+@@ -521,7 +523,9 @@ export function AddMonitorDialog({ systemId, monitors }: { systemId?: string; mo + placeholder={["1.1.1.1", "example.com,tcp", "https://example.com,http,,60"].join("\n")} + required + /> +-

target[,protocol[,port[,interval]]]

++

++ target[,protocol[,port[,interval]]] ++

+
+
+ diff --git a/tasks/henrygd__beszel-2362/solution/solve.sh b/tasks/henrygd__beszel-2362/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2362/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/henrygd__beszel-2362/task.toml b/tasks/henrygd__beszel-2362/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..67d4951698cc5e56dd1cebcf26b7283eb75b1422 --- /dev/null +++ b/tasks/henrygd__beszel-2362/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2362" +description = "fix(i18n): extract bulk monitor format hint" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "97e6f64bdcb926b8d0436f358942c098a46b6237" +reference = "https://github.com/henrygd/beszel/pull/2362" +source_access = "auto" +built_at = "2026-11-16T16:09:53.455613+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ffc178cf4ac7da40d20222fd0e7abaaa87ed7e30bb28cedf011cc7a6fc68fd17" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-23T19:19:31Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/network-monitors-table/monitor-dialog.tsx", +] +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:00.816584+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c120c0841b5ce95955c66d19b5e8cb10b25d30a5acecfa4c4cf58d3b2ece226c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2362/tests/capture.py b/tasks/henrygd__beszel-2362/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2362/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/henrygd__beszel-2362/tests/instruction.md b/tasks/henrygd__beszel-2362/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..99a9b27a3b752c05da2471710fb00a63a8033612 --- /dev/null +++ b/tasks/henrygd__beszel-2362/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(i18n): extract bulk monitor format hint + +## Description + +## 📃 Description + +Adds translation keys for the new section. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97e6f64bdcb9`. 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/henrygd__beszel-2362/tests/oracle.patch b/tasks/henrygd__beszel-2362/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..fd4e8f70d4e2f5e12d2069388ed6e356d368ea3f --- /dev/null +++ b/tasks/henrygd__beszel-2362/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +index 733935dc..66c642be 100644 +--- a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx ++++ b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +@@ -485,7 +485,9 @@ export function AddMonitorDialog({ systemId, monitors }: { systemId?: string; mo + + Bulk Add {{ foo: t`Network Monitors` }} + +- target[,protocol[,port[,interval]]] ++ ++ target[,protocol[,port[,interval]]] ++ + + +
+@@ -521,7 +523,9 @@ export function AddMonitorDialog({ systemId, monitors }: { systemId?: string; mo + placeholder={["1.1.1.1", "example.com,tcp", "https://example.com,http,,60"].join("\n")} + required + /> +-

target[,protocol[,port[,interval]]]

++

++ target[,protocol[,port[,interval]]] ++

+
+
+ diff --git a/tasks/henrygd__beszel-2362/tests/test.sh b/tasks/henrygd__beszel-2362/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..954895ea1046ffba2bd0419540e57c3bc06db6fc --- /dev/null +++ b/tasks/henrygd__beszel-2362/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 97e6f64bdcb926b8d0436f358942c098a46b6237 > "$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/henrygd__beszel-2362/tests/verifier.py b/tasks/henrygd__beszel-2362/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2362/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/henrygd__beszel-2363/environment/Dockerfile b/tasks/henrygd__beszel-2363/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0d744869dbacf374b59005829c685ce1ddcda0a6 --- /dev/null +++ b/tasks/henrygd__beszel-2363/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 15994474f6c061a6a1db525f19b72ec0ba0e42a0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 15994474f6c061a6a1db525f19b72ec0ba0e42a0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 15994474f6c061a6a1db525f19b72ec0ba0e42a0 \ + && 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/henrygd__beszel-2363/instruction.md b/tasks/henrygd__beszel-2363/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..79aaf56ae842aa50cb8d0d20c49fbbd3f111f741 --- /dev/null +++ b/tasks/henrygd__beszel-2363/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** feat(ui): render country flag emoji + +## Description + +## 📃 Description + +Adds support for Twemoji. Particularly useful on Windows systems. +Used font: https://github.com/mozilla/twemoji-colr + +## 📷 Screenshots + +
+ before +2 +
+ +
+ after +1 +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `15994474f6c0`. 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/henrygd__beszel-2363/solution/patch.diff b/tasks/henrygd__beszel-2363/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c1ec083e57e7680bd94d59374d73474f8196b4f9 --- /dev/null +++ b/tasks/henrygd__beszel-2363/solution/patch.diff @@ -0,0 +1,45 @@ +diff --git a/internal/site/src/assets/TwemojiCountryFlags.woff2 b/internal/site/src/assets/TwemojiCountryFlags.woff2 +new file mode 100644 +index 00000000..b9d6ea84 +Binary files /dev/null and b/internal/site/src/assets/TwemojiCountryFlags.woff2 differ +diff --git a/internal/site/src/index.css b/internal/site/src/index.css +index 974d2b6f..d33bd106 100644 +--- a/internal/site/src/index.css ++++ b/internal/site/src/index.css +@@ -64,7 +64,7 @@ + } + + @theme inline { +- --font-sans: Inter, InterVariable, sans-serif; ++ --font-sans: TwemojiCountryFlags, Inter, InterVariable, sans-serif; + + --breakpoint-xs: 26.6rem; + --breakpoint-450: 28rem; +@@ -118,11 +118,25 @@ + } + + @layer utilities { +- + /* Fonts */ ++ ++ /* Twemoji Country Flags font from country-flag-emoji-polyfill, ++ * derived from Twemoji Mozilla. Twemoji graphics are licensed CC BY 4.0: ++ * https://creativecommons.org/licenses/by/4.0/ ++ */ ++ @font-face { ++ font-family: TwemojiCountryFlags; ++ font-style: normal; ++ font-weight: 400; ++ font-display: swap; ++ src: url("./assets/TwemojiCountryFlags.woff2") format("woff2"); ++ /* Regional indicator symbols make up ISO 3166-1 flag emoji. */ ++ unicode-range: U+1F1E6-1F1FF; ++ } ++ + @supports (font-variation-settings: normal) { + :root { +- font-family: Inter, InterVariable, sans-serif; ++ font-family: TwemojiCountryFlags, Inter, InterVariable, sans-serif; + } + } + diff --git a/tasks/henrygd__beszel-2363/solution/solve.sh b/tasks/henrygd__beszel-2363/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2363/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/henrygd__beszel-2363/task.toml b/tasks/henrygd__beszel-2363/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7482a6f52cbac5138ee78f77d3851e10c0b38aed --- /dev/null +++ b/tasks/henrygd__beszel-2363/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2363" +description = "feat(ui): render country flag emoji" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "15994474f6c061a6a1db525f19b72ec0ba0e42a0" +reference = "https://github.com/henrygd/beszel/pull/2363" +source_access = "auto" +built_at = "2026-11-16T16:09:53.456993+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ae1d96af3f80e52396af92a0f9e2d3a2de0093db4f99e43906eae8b5a3860f04" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-26T14:41:23Z" +diff_format = "unified" +context_files = [ + "internal/site/src/assets/TwemojiCountryFlags.woff2", + "internal/site/src/index.css", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 20 +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:00.817043+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d1b3841e4b590d6aaf3b40e8cc2deb1786efacd8d3ac338d22d17421b346d86d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2363/tests/capture.py b/tasks/henrygd__beszel-2363/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2363/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/henrygd__beszel-2363/tests/instruction.md b/tasks/henrygd__beszel-2363/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..79aaf56ae842aa50cb8d0d20c49fbbd3f111f741 --- /dev/null +++ b/tasks/henrygd__beszel-2363/tests/instruction.md @@ -0,0 +1,26 @@ +# Issue + +**Title:** feat(ui): render country flag emoji + +## Description + +## 📃 Description + +Adds support for Twemoji. Particularly useful on Windows systems. +Used font: https://github.com/mozilla/twemoji-colr + +## 📷 Screenshots + +
+ before +2 +
+ +
+ after +1 +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `15994474f6c0`. 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/henrygd__beszel-2363/tests/oracle.patch b/tasks/henrygd__beszel-2363/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c1ec083e57e7680bd94d59374d73474f8196b4f9 --- /dev/null +++ b/tasks/henrygd__beszel-2363/tests/oracle.patch @@ -0,0 +1,45 @@ +diff --git a/internal/site/src/assets/TwemojiCountryFlags.woff2 b/internal/site/src/assets/TwemojiCountryFlags.woff2 +new file mode 100644 +index 00000000..b9d6ea84 +Binary files /dev/null and b/internal/site/src/assets/TwemojiCountryFlags.woff2 differ +diff --git a/internal/site/src/index.css b/internal/site/src/index.css +index 974d2b6f..d33bd106 100644 +--- a/internal/site/src/index.css ++++ b/internal/site/src/index.css +@@ -64,7 +64,7 @@ + } + + @theme inline { +- --font-sans: Inter, InterVariable, sans-serif; ++ --font-sans: TwemojiCountryFlags, Inter, InterVariable, sans-serif; + + --breakpoint-xs: 26.6rem; + --breakpoint-450: 28rem; +@@ -118,11 +118,25 @@ + } + + @layer utilities { +- + /* Fonts */ ++ ++ /* Twemoji Country Flags font from country-flag-emoji-polyfill, ++ * derived from Twemoji Mozilla. Twemoji graphics are licensed CC BY 4.0: ++ * https://creativecommons.org/licenses/by/4.0/ ++ */ ++ @font-face { ++ font-family: TwemojiCountryFlags; ++ font-style: normal; ++ font-weight: 400; ++ font-display: swap; ++ src: url("./assets/TwemojiCountryFlags.woff2") format("woff2"); ++ /* Regional indicator symbols make up ISO 3166-1 flag emoji. */ ++ unicode-range: U+1F1E6-1F1FF; ++ } ++ + @supports (font-variation-settings: normal) { + :root { +- font-family: Inter, InterVariable, sans-serif; ++ font-family: TwemojiCountryFlags, Inter, InterVariable, sans-serif; + } + } + diff --git a/tasks/henrygd__beszel-2363/tests/test.sh b/tasks/henrygd__beszel-2363/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d33b85f990fde77a388dcfc39409ac80cd7bf26c --- /dev/null +++ b/tasks/henrygd__beszel-2363/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 15994474f6c061a6a1db525f19b72ec0ba0e42a0 > "$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/henrygd__beszel-2363/tests/verifier.py b/tasks/henrygd__beszel-2363/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2363/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/henrygd__beszel-2375/environment/Dockerfile b/tasks/henrygd__beszel-2375/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff28208c4b42ecf1eb7fbc7ab8830adaadec3aea --- /dev/null +++ b/tasks/henrygd__beszel-2375/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2c69197d2d1cc94b325a8e9098eaba43d16063e6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2c69197d2d1cc94b325a8e9098eaba43d16063e6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2c69197d2d1cc94b325a8e9098eaba43d16063e6 \ + && 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/henrygd__beszel-2375/instruction.md b/tasks/henrygd__beszel-2375/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8400e47c53dd44a38ea30ca9a1879ef1cd424aef --- /dev/null +++ b/tasks/henrygd__beszel-2375/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** fix: preserve status alerts through pending recovery + +## Description + +## 📃 Description + +Handles the `pending → up` transition when a system reconnects after its connection settings are edited. Active status alerts are preserved during `pending` and resolved once the system is confirmed online. + +## 🧵 Changelog + +### 🔧 Fixed + +- Status alerts remaining active after a system transitions from pending to online. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2c69197d2d1c`. 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/henrygd__beszel-2375/solution/patch.diff b/tasks/henrygd__beszel-2375/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3d9304318c8dea93a41f4b82cd14ee0e100f925b --- /dev/null +++ b/tasks/henrygd__beszel-2375/solution/patch.diff @@ -0,0 +1,126 @@ +diff --git a/internal/hub/systems/system_manager.go b/internal/hub/systems/system_manager.go +index d1ff9633..e5a85ba3 100644 +--- a/internal/hub/systems/system_manager.go ++++ b/internal/hub/systems/system_manager.go +@@ -217,11 +217,15 @@ func (sm *SystemManager) onRecordAfterUpdateSuccess(e *core.RecordEvent) error { + // Pause monitoring but keep system in manager for potential resume + system.closeSSHConnection() + } +- _ = deactivateAlerts(e.App, e.Record.Id) ++ _ = deactivateAlerts(e.App, e.Record.Id, false) + sm.hub.CancelPendingStatusAlerts(e.Record.Id) + sm.hub.CancelPendingContainerAlerts(e.Record.Id) + return e.Next() + case pending: ++ // Keep an active status alert until connectivity is confirmed. This lets ++ // pending -> up resolve it and send the recovery notification after a ++ // system address or other connection setting is changed. ++ _ = deactivateAlerts(e.App, e.Record.Id, true) + // Resume monitoring, preferring existing WebSocket connection + if ok && system.WsConn != nil { + go system.update() +@@ -231,7 +235,6 @@ func (sm *SystemManager) onRecordAfterUpdateSuccess(e *core.RecordEvent) error { + if err := sm.AddRecord(e.Record, nil); err != nil { + e.App.Logger().Error("Error adding record", "err", err) + } +- _ = deactivateAlerts(e.App, e.Record.Id) + return e.Next() + case down: + // Docker state is unknown while the system is unreachable. Do not let a +@@ -254,8 +257,9 @@ func (sm *SystemManager) onRecordAfterUpdateSuccess(e *core.RecordEvent) error { + } + } + +- // Trigger status change alerts for up/down transitions +- if (newStatus == down && prevStatus == up) || (newStatus == up && prevStatus == down) { ++ // A connection-setting update moves a down system through pending before it ++ // comes up, so recover active status alerts on any non-up -> up transition. ++ if (newStatus == down && prevStatus == up) || (newStatus == up && prevStatus != up) { + if err := sm.hub.HandleStatusAlerts(newStatus, e.Record); err != nil { + e.App.Logger().Error("Error handling status alerts", "err", err) + } +@@ -413,10 +417,11 @@ func (sm *SystemManager) createSSHClientConfig() error { + return nil + } + +-// deactivateAlerts finds all triggered alerts for a system and sets them to inactive. +-// This is called when a system is paused or goes offline to prevent continued alerts. ++// deactivateAlerts finds triggered alerts for a system and sets them to inactive. ++// Status alerts can be preserved while connection changes are pending so that a ++// confirmed recovery still produces an "up" notification. + // Monitor incidents remain open: a missing observation does not establish recovery. +-func deactivateAlerts(app core.App, systemID string) error { ++func deactivateAlerts(app core.App, systemID string, preserveStatusAlert bool) error { + // Note: Direct SQL updates don't trigger SSE, so we use the PocketBase API + // _, err := app.DB().NewQuery(fmt.Sprintf("UPDATE alerts SET triggered = false WHERE system = '%s'", systemID)).Execute() + +@@ -426,6 +431,9 @@ func deactivateAlerts(app core.App, systemID string) error { + } + + for _, alert := range alerts { ++ if preserveStatusAlert && alert.GetString("name") == "Status" { ++ continue ++ } + alert.Set("triggered", false) + if err := app.SaveNoValidate(alert); err != nil { + return err +diff --git a/internal/hub/systems/systems_test.go b/internal/hub/systems/systems_test.go +index cf4997f8..6c92c87f 100644 +--- a/internal/hub/systems/systems_test.go ++++ b/internal/hub/systems/systems_test.go +@@ -133,6 +133,55 @@ func TestSystemManagerNew(t *testing.T) { + }) + } + ++func TestStatusAlertRecoveryAfterPendingTransition(t *testing.T) { ++ hub, user := tests.GetHubWithUser(t) ++ defer hub.Cleanup() ++ ++ userSettings, err := hub.FindFirstRecordByFilter("user_settings", "user={:user}", map[string]any{"user": user.Id}) ++ require.NoError(t, err) ++ userSettings.Set("settings", map[string]any{ ++ "emails": []string{"test@example.com"}, ++ "webhooks": []string{}, ++ }) ++ require.NoError(t, hub.Save(userSettings)) ++ ++ record, err := tests.CreateRecord(hub, "systems", map[string]any{ ++ "name": "changed-address", ++ "host": "192.0.2.1", ++ "port": "33914", ++ "users": []string{user.Id}, ++ }) ++ require.NoError(t, err) ++ record.Set("status", "down") ++ require.NoError(t, hub.Save(record)) ++ ++ alert, err := tests.CreateRecord(hub, "alerts", map[string]any{ ++ "name": "Status", ++ "system": record.Id, ++ "user": user.Id, ++ "min": 1, ++ "triggered": true, ++ }) ++ require.NoError(t, err) ++ initialEmailCount := hub.TestMailer.TotalSend() ++ ++ // The edit dialog temporarily moves the system through pending. The active ++ // status alert must remain active until the new connection is confirmed. ++ record.Set("host", "192.0.2.2") ++ record.Set("status", "pending") ++ require.NoError(t, hub.Save(record)) ++ alert, err = hub.FindRecordById("alerts", alert.Id) ++ require.NoError(t, err) ++ assert.True(t, alert.GetBool("triggered"), "pending connection update should preserve the active status alert") ++ ++ record.Set("status", "up") ++ require.NoError(t, hub.Save(record)) ++ alert, err = hub.FindRecordById("alerts", alert.Id) ++ require.NoError(t, err) ++ assert.False(t, alert.GetBool("triggered"), "pending -> up should resolve the active status alert") ++ assert.Equal(t, initialEmailCount+1, hub.TestMailer.TotalSend(), "recovery should send an up notification") ++} ++ + func testOld(t *testing.T, hub *tests.TestHub) { + user, err := tests.CreateUser(hub, "test@testy.com", "testtesttest") + require.NoError(t, err) diff --git a/tasks/henrygd__beszel-2375/solution/solve.sh b/tasks/henrygd__beszel-2375/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2375/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/henrygd__beszel-2375/task.toml b/tasks/henrygd__beszel-2375/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e46f38f9b77d4214be2d625ec617aa0ee8263414 --- /dev/null +++ b/tasks/henrygd__beszel-2375/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2375" +description = "fix: preserve status alerts through pending recovery" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "2c69197d2d1cc94b325a8e9098eaba43d16063e6" +reference = "https://github.com/henrygd/beszel/pull/2375" +source_access = "auto" +built_at = "2026-11-16T16:09:53.458474+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c1a359548357f6ad56f91470eeee8a50e57d47d86e608dbb5517d87642bc2134" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-22T23:14:55Z" +diff_format = "unified" +context_files = [ + "internal/hub/systems/system_manager.go", + "internal/hub/systems/systems_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 71 +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:00.817508+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ea463db41f78ac6bf3052450a4787de0cd325545429aca8f83cc1680dda96f25" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2375/tests/capture.py b/tasks/henrygd__beszel-2375/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2375/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/henrygd__beszel-2375/tests/instruction.md b/tasks/henrygd__beszel-2375/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8400e47c53dd44a38ea30ca9a1879ef1cd424aef --- /dev/null +++ b/tasks/henrygd__beszel-2375/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** fix: preserve status alerts through pending recovery + +## Description + +## 📃 Description + +Handles the `pending → up` transition when a system reconnects after its connection settings are edited. Active status alerts are preserved during `pending` and resolved once the system is confirmed online. + +## 🧵 Changelog + +### 🔧 Fixed + +- Status alerts remaining active after a system transitions from pending to online. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2c69197d2d1c`. 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/henrygd__beszel-2375/tests/oracle.patch b/tasks/henrygd__beszel-2375/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3d9304318c8dea93a41f4b82cd14ee0e100f925b --- /dev/null +++ b/tasks/henrygd__beszel-2375/tests/oracle.patch @@ -0,0 +1,126 @@ +diff --git a/internal/hub/systems/system_manager.go b/internal/hub/systems/system_manager.go +index d1ff9633..e5a85ba3 100644 +--- a/internal/hub/systems/system_manager.go ++++ b/internal/hub/systems/system_manager.go +@@ -217,11 +217,15 @@ func (sm *SystemManager) onRecordAfterUpdateSuccess(e *core.RecordEvent) error { + // Pause monitoring but keep system in manager for potential resume + system.closeSSHConnection() + } +- _ = deactivateAlerts(e.App, e.Record.Id) ++ _ = deactivateAlerts(e.App, e.Record.Id, false) + sm.hub.CancelPendingStatusAlerts(e.Record.Id) + sm.hub.CancelPendingContainerAlerts(e.Record.Id) + return e.Next() + case pending: ++ // Keep an active status alert until connectivity is confirmed. This lets ++ // pending -> up resolve it and send the recovery notification after a ++ // system address or other connection setting is changed. ++ _ = deactivateAlerts(e.App, e.Record.Id, true) + // Resume monitoring, preferring existing WebSocket connection + if ok && system.WsConn != nil { + go system.update() +@@ -231,7 +235,6 @@ func (sm *SystemManager) onRecordAfterUpdateSuccess(e *core.RecordEvent) error { + if err := sm.AddRecord(e.Record, nil); err != nil { + e.App.Logger().Error("Error adding record", "err", err) + } +- _ = deactivateAlerts(e.App, e.Record.Id) + return e.Next() + case down: + // Docker state is unknown while the system is unreachable. Do not let a +@@ -254,8 +257,9 @@ func (sm *SystemManager) onRecordAfterUpdateSuccess(e *core.RecordEvent) error { + } + } + +- // Trigger status change alerts for up/down transitions +- if (newStatus == down && prevStatus == up) || (newStatus == up && prevStatus == down) { ++ // A connection-setting update moves a down system through pending before it ++ // comes up, so recover active status alerts on any non-up -> up transition. ++ if (newStatus == down && prevStatus == up) || (newStatus == up && prevStatus != up) { + if err := sm.hub.HandleStatusAlerts(newStatus, e.Record); err != nil { + e.App.Logger().Error("Error handling status alerts", "err", err) + } +@@ -413,10 +417,11 @@ func (sm *SystemManager) createSSHClientConfig() error { + return nil + } + +-// deactivateAlerts finds all triggered alerts for a system and sets them to inactive. +-// This is called when a system is paused or goes offline to prevent continued alerts. ++// deactivateAlerts finds triggered alerts for a system and sets them to inactive. ++// Status alerts can be preserved while connection changes are pending so that a ++// confirmed recovery still produces an "up" notification. + // Monitor incidents remain open: a missing observation does not establish recovery. +-func deactivateAlerts(app core.App, systemID string) error { ++func deactivateAlerts(app core.App, systemID string, preserveStatusAlert bool) error { + // Note: Direct SQL updates don't trigger SSE, so we use the PocketBase API + // _, err := app.DB().NewQuery(fmt.Sprintf("UPDATE alerts SET triggered = false WHERE system = '%s'", systemID)).Execute() + +@@ -426,6 +431,9 @@ func deactivateAlerts(app core.App, systemID string) error { + } + + for _, alert := range alerts { ++ if preserveStatusAlert && alert.GetString("name") == "Status" { ++ continue ++ } + alert.Set("triggered", false) + if err := app.SaveNoValidate(alert); err != nil { + return err +diff --git a/internal/hub/systems/systems_test.go b/internal/hub/systems/systems_test.go +index cf4997f8..6c92c87f 100644 +--- a/internal/hub/systems/systems_test.go ++++ b/internal/hub/systems/systems_test.go +@@ -133,6 +133,55 @@ func TestSystemManagerNew(t *testing.T) { + }) + } + ++func TestStatusAlertRecoveryAfterPendingTransition(t *testing.T) { ++ hub, user := tests.GetHubWithUser(t) ++ defer hub.Cleanup() ++ ++ userSettings, err := hub.FindFirstRecordByFilter("user_settings", "user={:user}", map[string]any{"user": user.Id}) ++ require.NoError(t, err) ++ userSettings.Set("settings", map[string]any{ ++ "emails": []string{"test@example.com"}, ++ "webhooks": []string{}, ++ }) ++ require.NoError(t, hub.Save(userSettings)) ++ ++ record, err := tests.CreateRecord(hub, "systems", map[string]any{ ++ "name": "changed-address", ++ "host": "192.0.2.1", ++ "port": "33914", ++ "users": []string{user.Id}, ++ }) ++ require.NoError(t, err) ++ record.Set("status", "down") ++ require.NoError(t, hub.Save(record)) ++ ++ alert, err := tests.CreateRecord(hub, "alerts", map[string]any{ ++ "name": "Status", ++ "system": record.Id, ++ "user": user.Id, ++ "min": 1, ++ "triggered": true, ++ }) ++ require.NoError(t, err) ++ initialEmailCount := hub.TestMailer.TotalSend() ++ ++ // The edit dialog temporarily moves the system through pending. The active ++ // status alert must remain active until the new connection is confirmed. ++ record.Set("host", "192.0.2.2") ++ record.Set("status", "pending") ++ require.NoError(t, hub.Save(record)) ++ alert, err = hub.FindRecordById("alerts", alert.Id) ++ require.NoError(t, err) ++ assert.True(t, alert.GetBool("triggered"), "pending connection update should preserve the active status alert") ++ ++ record.Set("status", "up") ++ require.NoError(t, hub.Save(record)) ++ alert, err = hub.FindRecordById("alerts", alert.Id) ++ require.NoError(t, err) ++ assert.False(t, alert.GetBool("triggered"), "pending -> up should resolve the active status alert") ++ assert.Equal(t, initialEmailCount+1, hub.TestMailer.TotalSend(), "recovery should send an up notification") ++} ++ + func testOld(t *testing.T, hub *tests.TestHub) { + user, err := tests.CreateUser(hub, "test@testy.com", "testtesttest") + require.NoError(t, err) diff --git a/tasks/henrygd__beszel-2375/tests/test.sh b/tasks/henrygd__beszel-2375/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..654a489ffd8ca0d52c35a886ab1a725e84e78aed --- /dev/null +++ b/tasks/henrygd__beszel-2375/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 2c69197d2d1cc94b325a8e9098eaba43d16063e6 > "$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/henrygd__beszel-2375/tests/verifier.py b/tasks/henrygd__beszel-2375/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2375/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/henrygd__beszel-2377/environment/Dockerfile b/tasks/henrygd__beszel-2377/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..291af96bcf30f87f4f4a852eba6665893c15ba42 --- /dev/null +++ b/tasks/henrygd__beszel-2377/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a5f216f425997de165fabc64562f4974697b04ef 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a5f216f425997de165fabc64562f4974697b04ef \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a5f216f425997de165fabc64562f4974697b04ef \ + && 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/henrygd__beszel-2377/instruction.md b/tasks/henrygd__beszel-2377/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7b17c190a058a90f651f6a14a074afcb38055fac --- /dev/null +++ b/tasks/henrygd__beszel-2377/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** feat(ui): change loss to a red line + +## Description + +## 📃 Description + +The packet loss chart now renders using a fixed red (`--destructive`) line color instead of the default per-monitor color cycling, making loss more visually distinct as a warning signal regardless of monitor count. + +## 🪵 Changelog + +### ✏️ Changed + +- Added an optional `color` override prop to `MonitorChart` to force a fixed line color instead of per-monitor color assignment +- `LossChart` now uses `var(--destructive)` for its line color + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a5f216f42599`. 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/henrygd__beszel-2377/solution/patch.diff b/tasks/henrygd__beszel-2377/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5e74d9bca6fc83c484d412228cd3496ee94a44da --- /dev/null +++ b/tasks/henrygd__beszel-2377/solution/patch.diff @@ -0,0 +1,44 @@ +diff --git a/internal/site/src/components/routes/system/charts/monitors-charts.tsx b/internal/site/src/components/routes/system/charts/monitors-charts.tsx +index a900b53a..0602611c 100644 +--- a/internal/site/src/components/routes/system/charts/monitors-charts.tsx ++++ b/internal/site/src/components/routes/system/charts/monitors-charts.tsx +@@ -27,6 +27,8 @@ type MonitorChartBaseProps = MonitorChartProps & { + tickFormatter: (value: number) => string + contentFormatter: ({ value }: { value: number | string }) => string | number + domain?: [number | "auto", number | "auto"] ++ /** Overrides the per-monitor line colors (e.g. a fixed color for single-monitor charts). */ ++ color?: string + } + + function MonitorChart({ +@@ -41,6 +43,7 @@ function MonitorChart({ + tickFormatter, + contentFormatter, + domain, ++ color, + showFilter = monitors.length > 1, + }: MonitorChartBaseProps) { + const storedFilter = useStore($monitorFilter) +@@ -67,11 +70,12 @@ function MonitorChart({ + label, + dataKey: (record: NetworkMonitorStatsRecord) => record.stats?.[p.id]?.[metric] ?? null, + dot, +- color: count <= 5 ? i + 1 : `hsl(${(i * 360) / count}, var(--chart-saturation), var(--chart-lightness))`, ++ color: ++ color ?? (count <= 5 ? i + 1 : `hsl(${(i * 360) / count}, var(--chart-saturation), var(--chart-lightness))`), + }) + } + return { dataPoints: points, visibleKeys: visibleIDs } +- }, [monitors, filter, metric, chartData.chartTime]) ++ }, [monitors, filter, metric, chartData.chartTime, color]) + + const filteredMonitorStats = useMemo(() => { + if (!visibleKeys.length) return monitorStats +@@ -200,6 +204,7 @@ export function LossChart({ monitorStats, grid, monitors, chartData, empty, titl + title={title} + description={t`Packet loss (%)`} + domain={[0, 100]} ++ color="var(--destructive)" + tickFormatter={(value) => `${toFixedFloat(value, value >= 10 ? 0 : 1)}%`} + contentFormatter={({ value }) => { + if (typeof value !== "number") { diff --git a/tasks/henrygd__beszel-2377/solution/solve.sh b/tasks/henrygd__beszel-2377/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2377/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/henrygd__beszel-2377/task.toml b/tasks/henrygd__beszel-2377/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8fcb2fe2e399297545137eb79bc62608fec97d6a --- /dev/null +++ b/tasks/henrygd__beszel-2377/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2377" +description = "feat(ui): change loss to a red line" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "a5f216f425997de165fabc64562f4974697b04ef" +reference = "https://github.com/henrygd/beszel/pull/2377" +source_access = "auto" +built_at = "2026-11-16T16:09:53.493811+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d9c9a13479e8839a06cdb284414b5cc3e4d4218ef534d2aab8b5824a0d4b9927" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-21T18:49:12Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/routes/system/charts/monitors-charts.tsx", +] +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:00.817949+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a7eedb1c28a835492f2c10151dd523f8fe10b7ce82a2958e362384a0c3e7b7fd" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2377/tests/capture.py b/tasks/henrygd__beszel-2377/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2377/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/henrygd__beszel-2377/tests/instruction.md b/tasks/henrygd__beszel-2377/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7b17c190a058a90f651f6a14a074afcb38055fac --- /dev/null +++ b/tasks/henrygd__beszel-2377/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** feat(ui): change loss to a red line + +## Description + +## 📃 Description + +The packet loss chart now renders using a fixed red (`--destructive`) line color instead of the default per-monitor color cycling, making loss more visually distinct as a warning signal regardless of monitor count. + +## 🪵 Changelog + +### ✏️ Changed + +- Added an optional `color` override prop to `MonitorChart` to force a fixed line color instead of per-monitor color assignment +- `LossChart` now uses `var(--destructive)` for its line color + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a5f216f42599`. 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/henrygd__beszel-2377/tests/oracle.patch b/tasks/henrygd__beszel-2377/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5e74d9bca6fc83c484d412228cd3496ee94a44da --- /dev/null +++ b/tasks/henrygd__beszel-2377/tests/oracle.patch @@ -0,0 +1,44 @@ +diff --git a/internal/site/src/components/routes/system/charts/monitors-charts.tsx b/internal/site/src/components/routes/system/charts/monitors-charts.tsx +index a900b53a..0602611c 100644 +--- a/internal/site/src/components/routes/system/charts/monitors-charts.tsx ++++ b/internal/site/src/components/routes/system/charts/monitors-charts.tsx +@@ -27,6 +27,8 @@ type MonitorChartBaseProps = MonitorChartProps & { + tickFormatter: (value: number) => string + contentFormatter: ({ value }: { value: number | string }) => string | number + domain?: [number | "auto", number | "auto"] ++ /** Overrides the per-monitor line colors (e.g. a fixed color for single-monitor charts). */ ++ color?: string + } + + function MonitorChart({ +@@ -41,6 +43,7 @@ function MonitorChart({ + tickFormatter, + contentFormatter, + domain, ++ color, + showFilter = monitors.length > 1, + }: MonitorChartBaseProps) { + const storedFilter = useStore($monitorFilter) +@@ -67,11 +70,12 @@ function MonitorChart({ + label, + dataKey: (record: NetworkMonitorStatsRecord) => record.stats?.[p.id]?.[metric] ?? null, + dot, +- color: count <= 5 ? i + 1 : `hsl(${(i * 360) / count}, var(--chart-saturation), var(--chart-lightness))`, ++ color: ++ color ?? (count <= 5 ? i + 1 : `hsl(${(i * 360) / count}, var(--chart-saturation), var(--chart-lightness))`), + }) + } + return { dataPoints: points, visibleKeys: visibleIDs } +- }, [monitors, filter, metric, chartData.chartTime]) ++ }, [monitors, filter, metric, chartData.chartTime, color]) + + const filteredMonitorStats = useMemo(() => { + if (!visibleKeys.length) return monitorStats +@@ -200,6 +204,7 @@ export function LossChart({ monitorStats, grid, monitors, chartData, empty, titl + title={title} + description={t`Packet loss (%)`} + domain={[0, 100]} ++ color="var(--destructive)" + tickFormatter={(value) => `${toFixedFloat(value, value >= 10 ? 0 : 1)}%`} + contentFormatter={({ value }) => { + if (typeof value !== "number") { diff --git a/tasks/henrygd__beszel-2377/tests/test.sh b/tasks/henrygd__beszel-2377/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d17d74eb8af69734c6499b230da8aa13fc6df880 --- /dev/null +++ b/tasks/henrygd__beszel-2377/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 a5f216f425997de165fabc64562f4974697b04ef > "$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/henrygd__beszel-2377/tests/verifier.py b/tasks/henrygd__beszel-2377/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2377/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/henrygd__beszel-2387/environment/Dockerfile b/tasks/henrygd__beszel-2387/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8e383417b41f9906bb8e02557252d517408bd394 --- /dev/null +++ b/tasks/henrygd__beszel-2387/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3f20ecae503117ff052061136b080b8f8cce2df9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3f20ecae503117ff052061136b080b8f8cce2df9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3f20ecae503117ff052061136b080b8f8cce2df9 \ + && 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/henrygd__beszel-2387/instruction.md b/tasks/henrygd__beszel-2387/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f63dbcf24d2152ef99d2bfddf67e27e9b67fb24c --- /dev/null +++ b/tasks/henrygd__beszel-2387/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** Fix: Convert intel gpu top from text to JSON + +## Description + +## 📃 Description + +Intel GPUs use intel_gpu_top, but we're processing text output. JSON is available so we should use that. + +In my installation, Compute is reported as VideoEnhance. This bug is likely because text output is not consistent or reliable. + +Changing to JSON makes this more resilient, and fixes the bug. + +## 📖 Documentation + +No changes proposed. +The documentation does quote the intel_gpu_top command which has been removed, but I suggest that remain in place since it's human readable (unlike JSON). + +## 📷 Screenshots + +No UX changes required. The back-end change fixes it automatically. + +Screenshots below based on an LLM workload on the GPU (triggering 'compute') + +Context showing source of truth: +image + +Beszel before: +image + +Beszel after: +image + +## Testing +I do not have an intel dedicated GPU (only my iGPU and some nvidia cards). This change has been tested by my iGPU only. It would be great if someone with a dedicated GPU could also test to confirm the other attributes continue to work (e.g. my iGPU doesn't report power consumption). + +## AI Disclosure +I am not familiar with the Go language so I had agents assist with this PR + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3f20ecae5031`. 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/henrygd__beszel-2387/solution/patch.diff b/tasks/henrygd__beszel-2387/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9f0ceaa596391f1e8e8da8e5418a5919f7321550 --- /dev/null +++ b/tasks/henrygd__beszel-2387/solution/patch.diff @@ -0,0 +1,762 @@ +diff --git a/agent/gpu_intel.go b/agent/gpu_intel.go +index fd73ed84..b0813ffa 100644 +--- a/agent/gpu_intel.go ++++ b/agent/gpu_intel.go +@@ -2,7 +2,9 @@ package agent + + import ( + "bufio" ++ "encoding/json" + "io" ++ "log/slog" + "os/exec" + "strconv" + "strings" +@@ -49,10 +51,10 @@ func (gm *GPUManager) updateIntelFromStats(sample *intelGpuStats) bool { + return true + } + +-// collectIntelStats executes intel_gpu_top in text mode (-l) and parses the output ++// collectIntelStats executes intel_gpu_top in JSON mode (-J) and parses the output. + func (gm *GPUManager) collectIntelStats() (err error) { + // Build command arguments, optionally selecting a device via -d +- args := []string{"-s", intelGpuStatsInterval, "-l"} ++ args := []string{"-s", intelGpuStatsInterval, "-J"} + if dev, ok := utils.GetEnv("INTEL_GPU_DEVICE"); ok && dev != "" { + args = append(args, "-d", dev) + } +@@ -80,48 +82,64 @@ func (gm *GPUManager) collectIntelStats() (err error) { + } + }() + +- scanner := bufio.NewScanner(stdout) +- var header1 string +- var engineNames []string +- var friendlyNames []string +- var preEngineCols int +- var powerIndex int +- var hadDataRow bool +- // skip first data row because it sometimes has erroneous data +- var skippedFirstDataRow bool +- +- for scanner.Scan() { +- line := strings.TrimSpace(scanner.Text()) +- if line == "" { +- continue +- } ++ if err := gm.parseIntelJSONStream(stdout); err != nil { ++ return err ++ } ++ // The closing "]" is printed as the process exits, so read to EOF to let ++ // it finish instead of killing it. ++ _, _ = io.Copy(io.Discard, stdout) ++ return nil ++} + +- // first header line +- if strings.HasPrefix(line, "Freq") { +- header1 = line +- continue ++// parseIntelJSONStream decodes samples from intel_gpu_top -J output and ++// aggregates them. Since v1.28 the samples are wrapped in an array ("[", then ++// comma separated objects, and "]" only when the process exits). Older ++// versions print the same comma separated objects without the opening "[", so ++// it is added here to let both formats decode as an array. ++func (gm *GPUManager) parseIntelJSONStream(r io.Reader) error { ++ er := &eofReader{r: r} ++ br := bufio.NewReader(er) ++ first, err := peekNonSpace(br) ++ if err != nil { ++ if err == io.EOF { ++ return errNoValidData + } ++ return err ++ } ++ var src io.Reader = br ++ if first != '[' { ++ src = io.MultiReader(strings.NewReader("["), br) ++ } + +- // second header line +- if strings.HasPrefix(line, "req") { +- engineNames, friendlyNames, powerIndex, preEngineCols = gm.parseIntelHeaders(header1, line) +- continue ++ dec := json.NewDecoder(src) ++ if _, err := dec.Token(); err != nil { // opening "[" ++ return err ++ } ++ var hadDataRow bool ++ // skip first data row because it sometimes has erroneous data ++ var skippedFirstDataRow bool ++ // Decode reads one object and skips the commas between them. The array is ++ // usually never closed, so output ending mid-array or mid-sample (the ++ // process was killed) is the normal end of the stream rather than an error. ++ for dec.More() { ++ var sample intelGpuJSONSample ++ if err := dec.Decode(&sample); err != nil { ++ if er.eof { ++ break ++ } ++ return err + } +- +- // Data row + if !skippedFirstDataRow { + skippedFirstDataRow = true + continue + } +- sample, err := gm.parseIntelData(line, engineNames, friendlyNames, powerIndex, preEngineCols) +- if err != nil { +- return err ++ stats := parseIntelJSONSample(sample) ++ if !validIntelPower(stats.PowerGPU) || !validIntelPower(stats.PowerPkg) { ++ slog.Debug("Skipping intel_gpu_top sample with invalid power", "gpu", stats.PowerGPU, "pkg", stats.PowerPkg) ++ continue + } + hadDataRow = true +- gm.updateIntelFromStats(&sample) +- } +- if scanErr := scanner.Err(); scanErr != nil { +- return scanErr ++ gm.updateIntelFromStats(&stats) + } + if !hadDataRow { + return errNoValidData +@@ -129,80 +147,82 @@ func (gm *GPUManager) collectIntelStats() (err error) { + return nil + } + +-func (gm *GPUManager) parseIntelHeaders(header1 string, header2 string) (engineNames []string, friendlyNames []string, powerIndex int, preEngineCols int) { +- // Build indexes +- h1 := strings.Fields(header1) +- h2 := strings.Fields(header2) +- powerIndex = -1 // Initialize to -1, will be set to actual index if found +- // Collect engine names from header1 +- for _, col := range h1 { +- key := strings.TrimRightFunc(col, func(r rune) bool { +- return (r >= '0' && r <= '9') || r == '/' +- }) +- var friendly string +- switch key { +- case "RCS": +- friendly = "Render/3D" +- case "BCS": +- friendly = "Blitter" +- case "VCS": +- friendly = "Video" +- case "VECS": +- friendly = "VideoEnhance" +- case "CCS": +- friendly = "Compute" +- default: +- continue ++// eofReader records whether the underlying reader has returned io.EOF. The ++// json decoder reports a stream ending mid-value as a syntax error, so this ++// is how a truncated final sample is told apart from invalid output. ++type eofReader struct { ++ r io.Reader ++ eof bool ++} ++ ++func (e *eofReader) Read(p []byte) (int, error) { ++ n, err := e.r.Read(p) ++ if err == io.EOF { ++ e.eof = true ++ } ++ return n, err ++} ++ ++// peekNonSpace discards leading JSON whitespace and returns the next byte without consuming it. ++func peekNonSpace(br *bufio.Reader) (byte, error) { ++ for { ++ b, err := br.Peek(1) ++ if err != nil { ++ return 0, err + } +- engineNames = append(engineNames, key) +- friendlyNames = append(friendlyNames, friendly) +- } +- // find power gpu index among pre-engine columns +- if n := len(engineNames); n > 0 { +- preEngineCols = max(len(h2)-3*n, 0) +- limit := min(len(h2), preEngineCols) +- for i := range limit { +- if strings.EqualFold(h2[i], "gpu") { +- powerIndex = i +- break +- } ++ switch b[0] { ++ case ' ', '\t', '\n', '\r': ++ _, _ = br.ReadByte() ++ default: ++ return b[0], nil + } + } +- return engineNames, friendlyNames, powerIndex, preEngineCols + } + +-func (gm *GPUManager) parseIntelData(line string, engineNames []string, friendlyNames []string, powerIndex int, preEngineCols int) (sample intelGpuStats, err error) { +- fields := strings.Fields(line) +- if len(fields) == 0 { +- return sample, errNoValidData +- } +- // Make sure row has enough columns for engines +- if need := preEngineCols + 3*len(engineNames); len(fields) < need { +- return sample, errNoValidData ++// intelGpuJSONSample is a single sample from intel_gpu_top -J output. Only the ++// needed fields are mapped. ++type intelGpuJSONSample struct { ++ Power *struct { ++ GPU float64 `json:"GPU"` ++ Package float64 `json:"Package"` ++ } `json:"power"` ++ Engines map[string]struct { ++ Busy float64 `json:"busy"` ++ } `json:"engines"` ++} ++ ++// validIntelPower reports whether a power reading from intel_gpu_top is plausible. ++func validIntelPower(watts float64) bool { ++ // 5000 is well above any real GPU or package draw. intel_gpu_top ++ // computes power from unsigned energy counter deltas, so a counter that reads ++ // lower than the previous sample produces an enormous value for that period. ++ return watts >= 0 && watts <= 5000 ++} ++ ++// parseIntelJSONSample converts one intel_gpu_top JSON sample into intelGpuStats. ++func parseIntelJSONSample(sample intelGpuJSONSample) (stats intelGpuStats) { ++ if sample.Power != nil { ++ stats.PowerGPU = sample.Power.GPU ++ stats.PowerPkg = sample.Power.Package + } +- if powerIndex >= 0 && powerIndex < len(fields) { +- if v, perr := strconv.ParseFloat(fields[powerIndex], 64); perr == nil { +- sample.PowerGPU = v +- } +- if v, perr := strconv.ParseFloat(fields[powerIndex+1], 64); perr == nil { +- sample.PowerPkg = v ++ if len(sample.Engines) > 0 { ++ stats.Engines = make(map[string]float64, len(sample.Engines)) ++ for key, engine := range sample.Engines { ++ stats.Engines[intelEngineClass(key)] += engine.Busy + } + } +- if len(engineNames) > 0 { +- sample.Engines = make(map[string]float64, len(engineNames)) +- for k := range engineNames { +- base := preEngineCols + 3*k +- if base < len(fields) { +- busy := 0.0 +- if v, e := strconv.ParseFloat(fields[base], 64); e == nil { +- busy = v +- } +- cur := sample.Engines[friendlyNames[k]] +- sample.Engines[friendlyNames[k]] = cur + busy +- } else { +- sample.Engines[friendlyNames[k]] = 0 +- } ++ return stats ++} ++ ++// intelEngineClass returns the engine class name for an engine key. Keys are ++// class names ("Render/3D", "Video") in class view, which JSON output uses by ++// default since v1.28, and instance names ("Render/3D/0", "Video/1") in ++// physical view, which older versions use. ++func intelEngineClass(key string) string { ++ if i := strings.LastIndexByte(key, '/'); i >= 0 { ++ if _, err := strconv.ParseUint(key[i+1:], 10, 32); err == nil { ++ return key[:i] + } + } +- return sample, nil ++ return key + } +diff --git a/agent/gpu_test.go b/agent/gpu_test.go +index 889f6c26..82a83a73 100644 +--- a/agent/gpu_test.go ++++ b/agent/gpu_test.go +@@ -3,9 +3,11 @@ + package agent + + import ( ++ "encoding/json" + "fmt" + "os" + "path/filepath" ++ "slices" + "strings" + "testing" + "time" +@@ -1431,12 +1433,10 @@ func TestNewGPUManagerPriorityMixedCollectors(t *testing.T) { + t.Setenv("BESZEL_AGENT_GPU_COLLECTOR", "intel_gpu_top,rocm-smi") + + intelPath := filepath.Join(dir, "intel_gpu_top") +- intelScript := `#!/bin/sh +-echo "Freq MHz IRQ RC6 Power W IMC MiB/s RCS VCS" +-echo " req act /s % gpu pkg rd wr % se wa % se wa" +-echo "226 223 338 58 2.00 2.69 1820 965 0.00 0 0 0.00 0 0" +-echo "189 187 412 67 1.80 2.45 1950 823 8.50 2 1 15.00 1 0" +-` ++ intelScript := "#!/bin/sh\necho '" + intelJSONStream(true, ++ intelJSONSample(2, 2.69, map[string]float64{"Render/3D": 0, "Video": 0}), ++ intelJSONSample(1.8, 2.45, map[string]float64{"Render/3D": 8.5, "Video": 15}), ++ ) + "'\n" + require.NoError(t, os.WriteFile(intelPath, []byte(intelScript), 0755)) + + rocmPath := filepath.Join(dir, "rocm-smi") +@@ -1752,19 +1752,61 @@ func TestIntelUpdateFromStats(t *testing.T) { + assert.Equal(t, float64(2), gpu.Count) + } + ++// intelJSONSample returns one sample object formatted like intel_gpu_top -J output ++func intelJSONSample(powerGPU, powerPkg float64, engines map[string]float64) string { ++ var sb strings.Builder ++ sb.WriteString("{\n\t\"period\": {\n\t\t\"duration\": 3300.123456,\n\t\t\"unit\": \"ms\"\n\t},\n") ++ sb.WriteString("\t\"frequency\": {\n\t\t\"requested\": 373.000000,\n\t\t\"actual\": 373.000000,\n\t\t\"unit\": \"MHz\"\n\t},\n") ++ fmt.Fprintf(&sb, "\t\"power\": {\n\t\t\"GPU\": %f,\n\t\t\"Package\": %f,\n\t\t\"unit\": \"W\"\n\t},\n", powerGPU, powerPkg) ++ sb.WriteString("\t\"engines\": {") ++ names := make([]string, 0, len(engines)) ++ for name := range engines { ++ names = append(names, name) ++ } ++ slices.Sort(names) ++ for i, name := range names { ++ if i > 0 { ++ sb.WriteString(",") ++ } ++ fmt.Fprintf(&sb, "\n\t\t%q: {\n\t\t\t\"busy\": %f,\n\t\t\t\"sema\": 0.000000,\n\t\t\t\"wait\": 0.000000,\n\t\t\t\"unit\": \"%%\"\n\t\t}", name, engines[name]) ++ } ++ sb.WriteString("\n\t}\n}") ++ return sb.String() ++} ++ ++// intelJSONStream joins samples as intel_gpu_top -J prints them. Since v1.28 ++// the output starts with "[" (withArray); older versions omit it. ++func intelJSONStream(withArray bool, samples ...string) string { ++ var sb strings.Builder ++ if withArray { ++ sb.WriteString("[\n") ++ } ++ for i, s := range samples { ++ if i > 0 { ++ sb.WriteString(",\n") ++ } ++ sb.WriteString(s) ++ } ++ return sb.String() ++} ++ + func TestIntelCollectorStreaming(t *testing.T) { + dir := t.TempDir() + t.Setenv("PATH", dir) + +- // Create a fake intel_gpu_top that prints -l format with four samples (first will be skipped) and exits ++ engines := func(render, blitter, video float64) map[string]float64 { ++ return map[string]float64{"Render/3D": render, "Blitter": blitter, "Video": video} ++ } ++ output := intelJSONStream(true, ++ intelJSONSample(1.5, 4.13, engines(12.34, 0, 5)), ++ intelJSONSample(2.0, 2.69, engines(0, 0, 0)), ++ intelJSONSample(1.8, 2.45, engines(8.5, 15, 22)), ++ intelJSONSample(2.2, 3.12, engines(5.75, 9.5, 12)), ++ ) + "\n]" ++ ++ // Create a fake intel_gpu_top that prints -J output with four samples (first will be skipped) and exits + scriptPath := filepath.Join(dir, "intel_gpu_top") +- script := `#!/bin/sh +-echo "Freq MHz IRQ RC6 Power W IMC MiB/s RCS BCS VCS" +-echo " req act /s % gpu pkg rd wr % se wa % se wa % se wa" +-echo "373 373 224 45 1.50 4.13 2554 714 12.34 0 0 0.00 0 0 5.00 0 0" +-echo "226 223 338 58 2.00 2.69 1820 965 0.00 0 0 0.00 0 0 0.00 0 0" +-echo "189 187 412 67 1.80 2.45 1950 823 8.50 2 1 15.00 1 0 22.00 0 1" +-echo "298 295 278 51 2.20 3.12 1675 942 5.75 1 2 9.50 3 1 12.00 1 0"` ++ script := "#!/bin/sh\necho '" + output + "'\n" + if err := os.WriteFile(scriptPath, []byte(script), 0755); err != nil { + t.Fatal(err) + } +@@ -1781,229 +1823,168 @@ echo "298 295 278 51 2.20 3.12 1675 942 5.75 1 2 9.50 + gpu := gm.GpuDataMap["i0"] + require.NotNil(t, gpu) + // Power should be sum of samples 2-4 (first is skipped): 2.0 + 1.8 + 2.2 = 6.0 +- assert.EqualValues(t, 6.0, gpu.Power) ++ assert.InDelta(t, 6.0, gpu.Power, 0.001) + assert.InDelta(t, 8.26, gpu.PowerPkg, 0.01) // Allow small floating point differences + // Engines aggregated from samples 2-4 +- assert.EqualValues(t, 14.25, gpu.Engines["Render/3D"]) // 0.00 + 8.50 + 5.75 +- assert.EqualValues(t, 34.0, gpu.Engines["Video"]) // 0.00 + 22.00 + 12.00 +- assert.EqualValues(t, 24.5, gpu.Engines["Blitter"]) // 0.00 + 15.00 + 9.50 ++ assert.InDelta(t, 14.25, gpu.Engines["Render/3D"], 0.001) // 0.00 + 8.50 + 5.75 ++ assert.InDelta(t, 34.0, gpu.Engines["Video"], 0.001) // 0.00 + 22.00 + 12.00 ++ assert.InDelta(t, 24.5, gpu.Engines["Blitter"], 0.001) // 0.00 + 15.00 + 9.50 + // Count should be 3 samples (first is skipped) + assert.Equal(t, float64(3), gpu.Count) + } + +-func TestParseIntelHeaders(t *testing.T) { ++func TestParseIntelJSONStream(t *testing.T) { ++ first := intelJSONSample(9, 9, map[string]float64{"Render/3D": 99, "Compute": 99}) ++ classView := []string{ ++ intelJSONSample(2, 3, map[string]float64{"Render/3D": 10, "Blitter": 1, "Video": 5, "VideoEnhance": 0, "Compute": 40}), ++ intelJSONSample(1, 2, map[string]float64{"Render/3D": 20, "Blitter": 0, "Video": 5, "VideoEnhance": 3, "Compute": 60}), ++ } ++ classViewWant := map[string]float64{"Render/3D": 30, "Blitter": 1, "Video": 10, "VideoEnhance": 3, "Compute": 100} ++ + tests := []struct { +- name string +- header1 string +- header2 string +- wantEngineNames []string +- wantFriendlyNames []string +- wantPowerIndex int +- wantPreEngineCols int ++ name string ++ input string ++ wantErr error ++ wantAnyErr bool ++ wantCount float64 ++ wantPower float64 ++ wantPkg float64 ++ wantEngines map[string]float64 + }{ + { +- name: "basic headers with RCS BCS VCS", +- header1: "Freq MHz IRQ RC6 Power W IMC MiB/s RCS BCS VCS", +- header2: " req act /s % gpu pkg rd wr % se wa % se wa % se wa", +- wantEngineNames: []string{"RCS", "BCS", "VCS"}, +- wantFriendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- wantPowerIndex: 4, // "gpu" is at index 4 +- wantPreEngineCols: 8, // 17 total cols - 3*3 = 8 ++ name: "array still open while process runs", ++ input: intelJSONStream(true, first, classView[0], classView[1]), ++ wantCount: 2, ++ wantPower: 3, ++ wantPkg: 5, ++ wantEngines: classViewWant, ++ }, ++ { ++ name: "closed array", ++ input: intelJSONStream(true, first, classView[0], classView[1]) + "\n]\n", ++ wantCount: 2, ++ wantPower: 3, ++ wantPkg: 5, ++ wantEngines: classViewWant, ++ }, ++ { ++ name: "truncated final sample", ++ input: intelJSONStream(true, first, classView[0], classView[1], `{"period": {"duration": 33`), ++ wantCount: 2, ++ wantPower: 3, ++ wantPkg: 5, ++ wantEngines: classViewWant, + }, + { +- name: "basic headers with RCS BCS VCS using index in name", +- header1: "Freq MHz IRQ RC6 Power W IMC MiB/s RCS/0 BCS/1 VCS/2", +- header2: " req act /s % gpu pkg rd wr % se wa % se wa % se wa", +- wantEngineNames: []string{"RCS", "BCS", "VCS"}, +- wantFriendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- wantPowerIndex: 4, // "gpu" is at index 4 +- wantPreEngineCols: 8, // 17 total cols - 3*3 = 8 ++ // intel_gpu_top < 1.28 omits the opening "[" and uses physical engine names ++ name: "legacy output without array and with engine instances", ++ input: intelJSONStream(false, ++ intelJSONSample(9, 9, map[string]float64{"Render/3D/0": 99}), ++ intelJSONSample(1.5, 2.5, map[string]float64{"Render/3D/0": 12, "Blitter/0": 1, "Video/0": 4, "Video/1": 6, "VideoEnhance/0": 2}), ++ ), ++ wantCount: 1, ++ wantPower: 1.5, ++ wantPkg: 2.5, ++ wantEngines: map[string]float64{"Render/3D": 12, "Blitter": 1, "Video": 10, "VideoEnhance": 2}, + }, + { +- name: "headers with only RCS", +- header1: "Freq MHz IRQ RC6 Power W IMC MiB/s RCS", +- header2: " req act /s % gpu pkg rd wr % se wa", +- wantEngineNames: []string{"RCS"}, +- wantFriendlyNames: []string{"Render/3D"}, +- wantPowerIndex: 4, +- wantPreEngineCols: 8, // 11 total - 3*1 = 8 ++ // energy counter read lower than the previous sample in intel_gpu_top ++ name: "sample with invalid power is skipped", ++ input: intelJSONStream(true, first, classView[0], ++ intelJSONSample(86_000_000, 3, map[string]float64{"Render/3D": 50}), ++ intelJSONSample(2, 90_000_000, map[string]float64{"Render/3D": 50}), ++ classView[1], ++ ), ++ wantCount: 2, ++ wantPower: 3, ++ wantPkg: 5, ++ wantEngines: classViewWant, + }, + { +- name: "headers with VECS and CCS", +- header1: "Freq MHz IRQ RC6 Power W IMC MiB/s VECS CCS", +- header2: " req act /s % gpu pkg rd wr % se wa % se wa", +- wantEngineNames: []string{"VECS", "CCS"}, +- wantFriendlyNames: []string{"VideoEnhance", "Compute"}, +- wantPowerIndex: 4, +- wantPreEngineCols: 8, // 14 total - 3*2 = 8 ++ name: "only samples with invalid power", ++ input: intelJSONStream(true, first, intelJSONSample(86_000_000, 3, map[string]float64{"Render/3D": 50})), ++ wantErr: errNoValidData, + }, + { +- name: "no engines", +- header1: "Freq MHz IRQ RC6 Power W IMC MiB/s", +- header2: " req act /s % gpu pkg rd wr", +- wantEngineNames: nil, // no engines found, slices remain nil +- wantFriendlyNames: nil, +- wantPowerIndex: -1, // no engines, so no search +- wantPreEngineCols: 0, ++ name: "empty output", ++ input: "", ++ wantErr: errNoValidData, + }, + { +- name: "power index not found", +- header1: "Freq MHz IRQ RC6 Power W IMC MiB/s RCS", +- header2: " req act /s % pkg cpu rd wr % se wa", // no "gpu" +- wantEngineNames: []string{"RCS"}, +- wantFriendlyNames: []string{"Render/3D"}, +- wantPowerIndex: -1, // "gpu" not found +- wantPreEngineCols: 8, // 11 total - 3*1 = 8 ++ name: "only first sample, which is skipped", ++ input: intelJSONStream(true, first), ++ wantErr: errNoValidData, + }, + { +- name: "empty headers", +- header1: "", +- header2: "", +- wantEngineNames: nil, // empty input, slices remain nil +- wantFriendlyNames: nil, +- wantPowerIndex: -1, +- wantPreEngineCols: 0, ++ name: "invalid output", ++ input: "intel_gpu_top: command failed", ++ wantAnyErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { +- gm := &GPUManager{} +- engineNames, friendlyNames, powerIndex, preEngineCols := gm.parseIntelHeaders(tt.header1, tt.header2) +- +- assert.Equal(t, tt.wantEngineNames, engineNames) +- assert.Equal(t, tt.wantFriendlyNames, friendlyNames) +- assert.Equal(t, tt.wantPowerIndex, powerIndex) +- assert.Equal(t, tt.wantPreEngineCols, preEngineCols) ++ gm := &GPUManager{GpuDataMap: make(map[string]*system.GPUData)} ++ err := gm.parseIntelJSONStream(strings.NewReader(tt.input)) ++ if tt.wantAnyErr { ++ assert.Error(t, err) ++ return ++ } ++ if tt.wantErr != nil { ++ assert.ErrorIs(t, err, tt.wantErr) ++ assert.Empty(t, gm.GpuDataMap) ++ return ++ } ++ require.NoError(t, err) ++ ++ gpu := gm.GpuDataMap["i0"] ++ require.NotNil(t, gpu) ++ assert.Equal(t, tt.wantCount, gpu.Count) ++ assert.InDelta(t, tt.wantPower, gpu.Power, 0.001) ++ assert.InDelta(t, tt.wantPkg, gpu.PowerPkg, 0.001) ++ assert.Len(t, gpu.Engines, len(tt.wantEngines)) ++ for name, want := range tt.wantEngines { ++ assert.InDelta(t, want, gpu.Engines[name], 0.001, name) ++ } + }) + } + } + +-func TestParseIntelData(t *testing.T) { +- tests := []struct { +- name string +- line string +- engineNames []string +- friendlyNames []string +- powerIndex int +- preEngineCols int +- wantPowerGPU float64 +- wantEngines map[string]float64 +- wantErr error +- }{ +- { +- name: "basic data with power and engines", +- line: "373 373 224 45 1.50 4.13 2554 714 12.34 0 0 0.00 0 0 5.00 0 0", +- engineNames: []string{"RCS", "BCS", "VCS"}, +- friendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 1.50, +- wantEngines: map[string]float64{ +- "Render/3D": 12.34, +- "Blitter": 0.00, +- "Video": 5.00, +- }, +- }, +- { +- name: "data with zero power", +- line: "226 223 338 58 0.00 2.69 1820 965 0.00 0 0 0.00 0 0 0.00 0 0", +- engineNames: []string{"RCS", "BCS", "VCS"}, +- friendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 0.00, +- wantEngines: map[string]float64{ +- "Render/3D": 0.00, +- "Blitter": 0.00, +- "Video": 0.00, +- }, +- }, +- { +- name: "data with no power index", +- line: "373 373 224 45 1.50 4.13 2554 714 12.34 0 0 0.00 0 0 5.00 0 0", +- engineNames: []string{"RCS", "BCS", "VCS"}, +- friendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- powerIndex: -1, +- preEngineCols: 8, +- wantPowerGPU: 0.0, // no power parsed +- wantEngines: map[string]float64{ +- "Render/3D": 12.34, +- "Blitter": 0.00, +- "Video": 5.00, +- }, +- }, +- { +- name: "data with insufficient columns", +- line: "373 373 224 45 1.50", // too few columns +- engineNames: []string{"RCS", "BCS", "VCS"}, +- friendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 0.0, +- wantEngines: nil, // empty sample returned +- wantErr: errNoValidData, +- }, +- { +- name: "empty line", +- line: "", +- engineNames: []string{"RCS"}, +- friendlyNames: []string{"Render/3D"}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 0.0, +- wantEngines: nil, +- wantErr: errNoValidData, +- }, +- { +- name: "data with invalid power value", +- line: "373 373 224 45 N/A 4.13 2554 714 12.34 0 0 0.00 0 0 5.00 0 0", +- engineNames: []string{"RCS", "BCS", "VCS"}, +- friendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 0.0, // N/A can't be parsed +- wantEngines: map[string]float64{ +- "Render/3D": 12.34, +- "Blitter": 0.00, +- "Video": 5.00, +- }, +- }, +- { +- name: "data with invalid engine value", +- line: "373 373 224 45 1.50 4.13 2554 714 N/A 0 0 0.00 0 0 5.00 0 0", +- engineNames: []string{"RCS", "BCS", "VCS"}, +- friendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 1.50, +- wantEngines: map[string]float64{ +- "Render/3D": 0.0, // N/A becomes 0 +- "Blitter": 0.00, +- "Video": 5.00, +- }, +- }, +- { +- name: "data with no engines", +- line: "373 373 224 45 1.50 4.13 2554 714", +- engineNames: []string{}, +- friendlyNames: []string{}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 1.50, +- wantEngines: nil, +- }, +- } ++func TestParseIntelJSONSample(t *testing.T) { ++ t.Run("without power", func(t *testing.T) { ++ var sample intelGpuJSONSample ++ require.NoError(t, json.Unmarshal([]byte(`{"engines": {"Render/3D": {"busy": 7.5, "unit": "%"}}}`), &sample)) ++ stats := parseIntelJSONSample(sample) ++ assert.Zero(t, stats.PowerGPU) ++ assert.Zero(t, stats.PowerPkg) ++ assert.Equal(t, map[string]float64{"Render/3D": 7.5}, stats.Engines) ++ }) + +- for _, tt := range tests { +- t.Run(tt.name, func(t *testing.T) { +- gm := &GPUManager{} +- sample, err := gm.parseIntelData(tt.line, tt.engineNames, tt.friendlyNames, tt.powerIndex, tt.preEngineCols) +- assert.Equal(t, tt.wantErr, err) ++ t.Run("without engines", func(t *testing.T) { ++ var sample intelGpuJSONSample ++ require.NoError(t, json.Unmarshal([]byte(`{"power": {"GPU": 1.25, "Package": 4.5, "unit": "W"}}`), &sample)) ++ stats := parseIntelJSONSample(sample) ++ assert.Equal(t, 1.25, stats.PowerGPU) ++ assert.Equal(t, 4.5, stats.PowerPkg) ++ assert.Nil(t, stats.Engines) ++ }) ++} + +- assert.Equal(t, tt.wantPowerGPU, sample.PowerGPU) +- assert.Equal(t, tt.wantEngines, sample.Engines) +- }) ++func TestIntelEngineClass(t *testing.T) { ++ tests := map[string]string{ ++ "Render/3D": "Render/3D", ++ "Render/3D/0": "Render/3D", ++ "Blitter": "Blitter", ++ "Blitter/0": "Blitter", ++ "Video/1": "Video", ++ "VideoEnhance/0": "VideoEnhance", ++ "Compute/3": "Compute", ++ "[unknown]": "[unknown]", ++ "[unknown]/0": "[unknown]", ++ "Video/": "Video/", ++ } ++ for key, want := range tests { ++ assert.Equal(t, want, intelEngineClass(key), key) + } + } + +@@ -2016,13 +1997,11 @@ func TestIntelCollectorDeviceEnv(t *testing.T) { + + // Create a fake intel_gpu_top that records its arguments and prints minimal valid output + scriptPath := filepath.Join(dir, "intel_gpu_top") +- script := fmt.Sprintf(`#!/bin/sh +-echo "$@" > %s +-echo "Freq MHz IRQ RC6 Power W IMC MiB/s RCS VCS" +-echo " req act /s %% gpu pkg rd wr %% se wa %% se wa" +-echo "226 223 338 58 2.00 2.69 1820 965 0.00 0 0 0.00 0 0" +-echo "189 187 412 67 1.80 2.45 1950 823 8.50 2 1 15.00 1 0" +-`, argsFile) ++ output := intelJSONStream(true, ++ intelJSONSample(2, 2.69, map[string]float64{"Render/3D": 0, "Video": 0}), ++ intelJSONSample(1.8, 2.45, map[string]float64{"Render/3D": 8.5, "Video": 15}), ++ ) ++ script := fmt.Sprintf("#!/bin/sh\necho \"$@\" > %s\necho '%s'\n", argsFile, output) + if err := os.WriteFile(scriptPath, []byte(script), 0755); err != nil { + t.Fatal(err) + } +@@ -2043,5 +2022,5 @@ echo "189 187 412 67 1.80 2.45 1950 823 8.50 2 1 15.00 + argsStr := strings.TrimSpace(string(data)) + require.Contains(t, argsStr, "-d sriov") + require.Contains(t, argsStr, "-s ") +- require.Contains(t, argsStr, "-l") ++ require.Contains(t, argsStr, "-J") + } diff --git a/tasks/henrygd__beszel-2387/solution/solve.sh b/tasks/henrygd__beszel-2387/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2387/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/henrygd__beszel-2387/task.toml b/tasks/henrygd__beszel-2387/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..89d9566c27ab0e004e96c2c0038bb43125cad254 --- /dev/null +++ b/tasks/henrygd__beszel-2387/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2387" +description = "Fix: Convert intel gpu top from text to JSON" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "3f20ecae503117ff052061136b080b8f8cce2df9" +reference = "https://github.com/henrygd/beszel/pull/2387" +source_access = "auto" +built_at = "2026-11-16T16:09:53.434102+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c987d16e0fbf96cc4bdcbf3c004b845588f121ef6b116fbe1cdf54223a5bc766" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-27T14:17:28Z" +diff_format = "unified" +context_files = [ + "agent/gpu_intel.go", + "agent/gpu_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 625 +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:00.818406+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2043552fc86dc5ec8fe3542e184bfc3d6776b7549d2bc4bd8adb3121bced2341" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2387/tests/capture.py b/tasks/henrygd__beszel-2387/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2387/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/henrygd__beszel-2387/tests/instruction.md b/tasks/henrygd__beszel-2387/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f63dbcf24d2152ef99d2bfddf67e27e9b67fb24c --- /dev/null +++ b/tasks/henrygd__beszel-2387/tests/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** Fix: Convert intel gpu top from text to JSON + +## Description + +## 📃 Description + +Intel GPUs use intel_gpu_top, but we're processing text output. JSON is available so we should use that. + +In my installation, Compute is reported as VideoEnhance. This bug is likely because text output is not consistent or reliable. + +Changing to JSON makes this more resilient, and fixes the bug. + +## 📖 Documentation + +No changes proposed. +The documentation does quote the intel_gpu_top command which has been removed, but I suggest that remain in place since it's human readable (unlike JSON). + +## 📷 Screenshots + +No UX changes required. The back-end change fixes it automatically. + +Screenshots below based on an LLM workload on the GPU (triggering 'compute') + +Context showing source of truth: +image + +Beszel before: +image + +Beszel after: +image + +## Testing +I do not have an intel dedicated GPU (only my iGPU and some nvidia cards). This change has been tested by my iGPU only. It would be great if someone with a dedicated GPU could also test to confirm the other attributes continue to work (e.g. my iGPU doesn't report power consumption). + +## AI Disclosure +I am not familiar with the Go language so I had agents assist with this PR + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3f20ecae5031`. 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/henrygd__beszel-2387/tests/oracle.patch b/tasks/henrygd__beszel-2387/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9f0ceaa596391f1e8e8da8e5418a5919f7321550 --- /dev/null +++ b/tasks/henrygd__beszel-2387/tests/oracle.patch @@ -0,0 +1,762 @@ +diff --git a/agent/gpu_intel.go b/agent/gpu_intel.go +index fd73ed84..b0813ffa 100644 +--- a/agent/gpu_intel.go ++++ b/agent/gpu_intel.go +@@ -2,7 +2,9 @@ package agent + + import ( + "bufio" ++ "encoding/json" + "io" ++ "log/slog" + "os/exec" + "strconv" + "strings" +@@ -49,10 +51,10 @@ func (gm *GPUManager) updateIntelFromStats(sample *intelGpuStats) bool { + return true + } + +-// collectIntelStats executes intel_gpu_top in text mode (-l) and parses the output ++// collectIntelStats executes intel_gpu_top in JSON mode (-J) and parses the output. + func (gm *GPUManager) collectIntelStats() (err error) { + // Build command arguments, optionally selecting a device via -d +- args := []string{"-s", intelGpuStatsInterval, "-l"} ++ args := []string{"-s", intelGpuStatsInterval, "-J"} + if dev, ok := utils.GetEnv("INTEL_GPU_DEVICE"); ok && dev != "" { + args = append(args, "-d", dev) + } +@@ -80,48 +82,64 @@ func (gm *GPUManager) collectIntelStats() (err error) { + } + }() + +- scanner := bufio.NewScanner(stdout) +- var header1 string +- var engineNames []string +- var friendlyNames []string +- var preEngineCols int +- var powerIndex int +- var hadDataRow bool +- // skip first data row because it sometimes has erroneous data +- var skippedFirstDataRow bool +- +- for scanner.Scan() { +- line := strings.TrimSpace(scanner.Text()) +- if line == "" { +- continue +- } ++ if err := gm.parseIntelJSONStream(stdout); err != nil { ++ return err ++ } ++ // The closing "]" is printed as the process exits, so read to EOF to let ++ // it finish instead of killing it. ++ _, _ = io.Copy(io.Discard, stdout) ++ return nil ++} + +- // first header line +- if strings.HasPrefix(line, "Freq") { +- header1 = line +- continue ++// parseIntelJSONStream decodes samples from intel_gpu_top -J output and ++// aggregates them. Since v1.28 the samples are wrapped in an array ("[", then ++// comma separated objects, and "]" only when the process exits). Older ++// versions print the same comma separated objects without the opening "[", so ++// it is added here to let both formats decode as an array. ++func (gm *GPUManager) parseIntelJSONStream(r io.Reader) error { ++ er := &eofReader{r: r} ++ br := bufio.NewReader(er) ++ first, err := peekNonSpace(br) ++ if err != nil { ++ if err == io.EOF { ++ return errNoValidData + } ++ return err ++ } ++ var src io.Reader = br ++ if first != '[' { ++ src = io.MultiReader(strings.NewReader("["), br) ++ } + +- // second header line +- if strings.HasPrefix(line, "req") { +- engineNames, friendlyNames, powerIndex, preEngineCols = gm.parseIntelHeaders(header1, line) +- continue ++ dec := json.NewDecoder(src) ++ if _, err := dec.Token(); err != nil { // opening "[" ++ return err ++ } ++ var hadDataRow bool ++ // skip first data row because it sometimes has erroneous data ++ var skippedFirstDataRow bool ++ // Decode reads one object and skips the commas between them. The array is ++ // usually never closed, so output ending mid-array or mid-sample (the ++ // process was killed) is the normal end of the stream rather than an error. ++ for dec.More() { ++ var sample intelGpuJSONSample ++ if err := dec.Decode(&sample); err != nil { ++ if er.eof { ++ break ++ } ++ return err + } +- +- // Data row + if !skippedFirstDataRow { + skippedFirstDataRow = true + continue + } +- sample, err := gm.parseIntelData(line, engineNames, friendlyNames, powerIndex, preEngineCols) +- if err != nil { +- return err ++ stats := parseIntelJSONSample(sample) ++ if !validIntelPower(stats.PowerGPU) || !validIntelPower(stats.PowerPkg) { ++ slog.Debug("Skipping intel_gpu_top sample with invalid power", "gpu", stats.PowerGPU, "pkg", stats.PowerPkg) ++ continue + } + hadDataRow = true +- gm.updateIntelFromStats(&sample) +- } +- if scanErr := scanner.Err(); scanErr != nil { +- return scanErr ++ gm.updateIntelFromStats(&stats) + } + if !hadDataRow { + return errNoValidData +@@ -129,80 +147,82 @@ func (gm *GPUManager) collectIntelStats() (err error) { + return nil + } + +-func (gm *GPUManager) parseIntelHeaders(header1 string, header2 string) (engineNames []string, friendlyNames []string, powerIndex int, preEngineCols int) { +- // Build indexes +- h1 := strings.Fields(header1) +- h2 := strings.Fields(header2) +- powerIndex = -1 // Initialize to -1, will be set to actual index if found +- // Collect engine names from header1 +- for _, col := range h1 { +- key := strings.TrimRightFunc(col, func(r rune) bool { +- return (r >= '0' && r <= '9') || r == '/' +- }) +- var friendly string +- switch key { +- case "RCS": +- friendly = "Render/3D" +- case "BCS": +- friendly = "Blitter" +- case "VCS": +- friendly = "Video" +- case "VECS": +- friendly = "VideoEnhance" +- case "CCS": +- friendly = "Compute" +- default: +- continue ++// eofReader records whether the underlying reader has returned io.EOF. The ++// json decoder reports a stream ending mid-value as a syntax error, so this ++// is how a truncated final sample is told apart from invalid output. ++type eofReader struct { ++ r io.Reader ++ eof bool ++} ++ ++func (e *eofReader) Read(p []byte) (int, error) { ++ n, err := e.r.Read(p) ++ if err == io.EOF { ++ e.eof = true ++ } ++ return n, err ++} ++ ++// peekNonSpace discards leading JSON whitespace and returns the next byte without consuming it. ++func peekNonSpace(br *bufio.Reader) (byte, error) { ++ for { ++ b, err := br.Peek(1) ++ if err != nil { ++ return 0, err + } +- engineNames = append(engineNames, key) +- friendlyNames = append(friendlyNames, friendly) +- } +- // find power gpu index among pre-engine columns +- if n := len(engineNames); n > 0 { +- preEngineCols = max(len(h2)-3*n, 0) +- limit := min(len(h2), preEngineCols) +- for i := range limit { +- if strings.EqualFold(h2[i], "gpu") { +- powerIndex = i +- break +- } ++ switch b[0] { ++ case ' ', '\t', '\n', '\r': ++ _, _ = br.ReadByte() ++ default: ++ return b[0], nil + } + } +- return engineNames, friendlyNames, powerIndex, preEngineCols + } + +-func (gm *GPUManager) parseIntelData(line string, engineNames []string, friendlyNames []string, powerIndex int, preEngineCols int) (sample intelGpuStats, err error) { +- fields := strings.Fields(line) +- if len(fields) == 0 { +- return sample, errNoValidData +- } +- // Make sure row has enough columns for engines +- if need := preEngineCols + 3*len(engineNames); len(fields) < need { +- return sample, errNoValidData ++// intelGpuJSONSample is a single sample from intel_gpu_top -J output. Only the ++// needed fields are mapped. ++type intelGpuJSONSample struct { ++ Power *struct { ++ GPU float64 `json:"GPU"` ++ Package float64 `json:"Package"` ++ } `json:"power"` ++ Engines map[string]struct { ++ Busy float64 `json:"busy"` ++ } `json:"engines"` ++} ++ ++// validIntelPower reports whether a power reading from intel_gpu_top is plausible. ++func validIntelPower(watts float64) bool { ++ // 5000 is well above any real GPU or package draw. intel_gpu_top ++ // computes power from unsigned energy counter deltas, so a counter that reads ++ // lower than the previous sample produces an enormous value for that period. ++ return watts >= 0 && watts <= 5000 ++} ++ ++// parseIntelJSONSample converts one intel_gpu_top JSON sample into intelGpuStats. ++func parseIntelJSONSample(sample intelGpuJSONSample) (stats intelGpuStats) { ++ if sample.Power != nil { ++ stats.PowerGPU = sample.Power.GPU ++ stats.PowerPkg = sample.Power.Package + } +- if powerIndex >= 0 && powerIndex < len(fields) { +- if v, perr := strconv.ParseFloat(fields[powerIndex], 64); perr == nil { +- sample.PowerGPU = v +- } +- if v, perr := strconv.ParseFloat(fields[powerIndex+1], 64); perr == nil { +- sample.PowerPkg = v ++ if len(sample.Engines) > 0 { ++ stats.Engines = make(map[string]float64, len(sample.Engines)) ++ for key, engine := range sample.Engines { ++ stats.Engines[intelEngineClass(key)] += engine.Busy + } + } +- if len(engineNames) > 0 { +- sample.Engines = make(map[string]float64, len(engineNames)) +- for k := range engineNames { +- base := preEngineCols + 3*k +- if base < len(fields) { +- busy := 0.0 +- if v, e := strconv.ParseFloat(fields[base], 64); e == nil { +- busy = v +- } +- cur := sample.Engines[friendlyNames[k]] +- sample.Engines[friendlyNames[k]] = cur + busy +- } else { +- sample.Engines[friendlyNames[k]] = 0 +- } ++ return stats ++} ++ ++// intelEngineClass returns the engine class name for an engine key. Keys are ++// class names ("Render/3D", "Video") in class view, which JSON output uses by ++// default since v1.28, and instance names ("Render/3D/0", "Video/1") in ++// physical view, which older versions use. ++func intelEngineClass(key string) string { ++ if i := strings.LastIndexByte(key, '/'); i >= 0 { ++ if _, err := strconv.ParseUint(key[i+1:], 10, 32); err == nil { ++ return key[:i] + } + } +- return sample, nil ++ return key + } +diff --git a/agent/gpu_test.go b/agent/gpu_test.go +index 889f6c26..82a83a73 100644 +--- a/agent/gpu_test.go ++++ b/agent/gpu_test.go +@@ -3,9 +3,11 @@ + package agent + + import ( ++ "encoding/json" + "fmt" + "os" + "path/filepath" ++ "slices" + "strings" + "testing" + "time" +@@ -1431,12 +1433,10 @@ func TestNewGPUManagerPriorityMixedCollectors(t *testing.T) { + t.Setenv("BESZEL_AGENT_GPU_COLLECTOR", "intel_gpu_top,rocm-smi") + + intelPath := filepath.Join(dir, "intel_gpu_top") +- intelScript := `#!/bin/sh +-echo "Freq MHz IRQ RC6 Power W IMC MiB/s RCS VCS" +-echo " req act /s % gpu pkg rd wr % se wa % se wa" +-echo "226 223 338 58 2.00 2.69 1820 965 0.00 0 0 0.00 0 0" +-echo "189 187 412 67 1.80 2.45 1950 823 8.50 2 1 15.00 1 0" +-` ++ intelScript := "#!/bin/sh\necho '" + intelJSONStream(true, ++ intelJSONSample(2, 2.69, map[string]float64{"Render/3D": 0, "Video": 0}), ++ intelJSONSample(1.8, 2.45, map[string]float64{"Render/3D": 8.5, "Video": 15}), ++ ) + "'\n" + require.NoError(t, os.WriteFile(intelPath, []byte(intelScript), 0755)) + + rocmPath := filepath.Join(dir, "rocm-smi") +@@ -1752,19 +1752,61 @@ func TestIntelUpdateFromStats(t *testing.T) { + assert.Equal(t, float64(2), gpu.Count) + } + ++// intelJSONSample returns one sample object formatted like intel_gpu_top -J output ++func intelJSONSample(powerGPU, powerPkg float64, engines map[string]float64) string { ++ var sb strings.Builder ++ sb.WriteString("{\n\t\"period\": {\n\t\t\"duration\": 3300.123456,\n\t\t\"unit\": \"ms\"\n\t},\n") ++ sb.WriteString("\t\"frequency\": {\n\t\t\"requested\": 373.000000,\n\t\t\"actual\": 373.000000,\n\t\t\"unit\": \"MHz\"\n\t},\n") ++ fmt.Fprintf(&sb, "\t\"power\": {\n\t\t\"GPU\": %f,\n\t\t\"Package\": %f,\n\t\t\"unit\": \"W\"\n\t},\n", powerGPU, powerPkg) ++ sb.WriteString("\t\"engines\": {") ++ names := make([]string, 0, len(engines)) ++ for name := range engines { ++ names = append(names, name) ++ } ++ slices.Sort(names) ++ for i, name := range names { ++ if i > 0 { ++ sb.WriteString(",") ++ } ++ fmt.Fprintf(&sb, "\n\t\t%q: {\n\t\t\t\"busy\": %f,\n\t\t\t\"sema\": 0.000000,\n\t\t\t\"wait\": 0.000000,\n\t\t\t\"unit\": \"%%\"\n\t\t}", name, engines[name]) ++ } ++ sb.WriteString("\n\t}\n}") ++ return sb.String() ++} ++ ++// intelJSONStream joins samples as intel_gpu_top -J prints them. Since v1.28 ++// the output starts with "[" (withArray); older versions omit it. ++func intelJSONStream(withArray bool, samples ...string) string { ++ var sb strings.Builder ++ if withArray { ++ sb.WriteString("[\n") ++ } ++ for i, s := range samples { ++ if i > 0 { ++ sb.WriteString(",\n") ++ } ++ sb.WriteString(s) ++ } ++ return sb.String() ++} ++ + func TestIntelCollectorStreaming(t *testing.T) { + dir := t.TempDir() + t.Setenv("PATH", dir) + +- // Create a fake intel_gpu_top that prints -l format with four samples (first will be skipped) and exits ++ engines := func(render, blitter, video float64) map[string]float64 { ++ return map[string]float64{"Render/3D": render, "Blitter": blitter, "Video": video} ++ } ++ output := intelJSONStream(true, ++ intelJSONSample(1.5, 4.13, engines(12.34, 0, 5)), ++ intelJSONSample(2.0, 2.69, engines(0, 0, 0)), ++ intelJSONSample(1.8, 2.45, engines(8.5, 15, 22)), ++ intelJSONSample(2.2, 3.12, engines(5.75, 9.5, 12)), ++ ) + "\n]" ++ ++ // Create a fake intel_gpu_top that prints -J output with four samples (first will be skipped) and exits + scriptPath := filepath.Join(dir, "intel_gpu_top") +- script := `#!/bin/sh +-echo "Freq MHz IRQ RC6 Power W IMC MiB/s RCS BCS VCS" +-echo " req act /s % gpu pkg rd wr % se wa % se wa % se wa" +-echo "373 373 224 45 1.50 4.13 2554 714 12.34 0 0 0.00 0 0 5.00 0 0" +-echo "226 223 338 58 2.00 2.69 1820 965 0.00 0 0 0.00 0 0 0.00 0 0" +-echo "189 187 412 67 1.80 2.45 1950 823 8.50 2 1 15.00 1 0 22.00 0 1" +-echo "298 295 278 51 2.20 3.12 1675 942 5.75 1 2 9.50 3 1 12.00 1 0"` ++ script := "#!/bin/sh\necho '" + output + "'\n" + if err := os.WriteFile(scriptPath, []byte(script), 0755); err != nil { + t.Fatal(err) + } +@@ -1781,229 +1823,168 @@ echo "298 295 278 51 2.20 3.12 1675 942 5.75 1 2 9.50 + gpu := gm.GpuDataMap["i0"] + require.NotNil(t, gpu) + // Power should be sum of samples 2-4 (first is skipped): 2.0 + 1.8 + 2.2 = 6.0 +- assert.EqualValues(t, 6.0, gpu.Power) ++ assert.InDelta(t, 6.0, gpu.Power, 0.001) + assert.InDelta(t, 8.26, gpu.PowerPkg, 0.01) // Allow small floating point differences + // Engines aggregated from samples 2-4 +- assert.EqualValues(t, 14.25, gpu.Engines["Render/3D"]) // 0.00 + 8.50 + 5.75 +- assert.EqualValues(t, 34.0, gpu.Engines["Video"]) // 0.00 + 22.00 + 12.00 +- assert.EqualValues(t, 24.5, gpu.Engines["Blitter"]) // 0.00 + 15.00 + 9.50 ++ assert.InDelta(t, 14.25, gpu.Engines["Render/3D"], 0.001) // 0.00 + 8.50 + 5.75 ++ assert.InDelta(t, 34.0, gpu.Engines["Video"], 0.001) // 0.00 + 22.00 + 12.00 ++ assert.InDelta(t, 24.5, gpu.Engines["Blitter"], 0.001) // 0.00 + 15.00 + 9.50 + // Count should be 3 samples (first is skipped) + assert.Equal(t, float64(3), gpu.Count) + } + +-func TestParseIntelHeaders(t *testing.T) { ++func TestParseIntelJSONStream(t *testing.T) { ++ first := intelJSONSample(9, 9, map[string]float64{"Render/3D": 99, "Compute": 99}) ++ classView := []string{ ++ intelJSONSample(2, 3, map[string]float64{"Render/3D": 10, "Blitter": 1, "Video": 5, "VideoEnhance": 0, "Compute": 40}), ++ intelJSONSample(1, 2, map[string]float64{"Render/3D": 20, "Blitter": 0, "Video": 5, "VideoEnhance": 3, "Compute": 60}), ++ } ++ classViewWant := map[string]float64{"Render/3D": 30, "Blitter": 1, "Video": 10, "VideoEnhance": 3, "Compute": 100} ++ + tests := []struct { +- name string +- header1 string +- header2 string +- wantEngineNames []string +- wantFriendlyNames []string +- wantPowerIndex int +- wantPreEngineCols int ++ name string ++ input string ++ wantErr error ++ wantAnyErr bool ++ wantCount float64 ++ wantPower float64 ++ wantPkg float64 ++ wantEngines map[string]float64 + }{ + { +- name: "basic headers with RCS BCS VCS", +- header1: "Freq MHz IRQ RC6 Power W IMC MiB/s RCS BCS VCS", +- header2: " req act /s % gpu pkg rd wr % se wa % se wa % se wa", +- wantEngineNames: []string{"RCS", "BCS", "VCS"}, +- wantFriendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- wantPowerIndex: 4, // "gpu" is at index 4 +- wantPreEngineCols: 8, // 17 total cols - 3*3 = 8 ++ name: "array still open while process runs", ++ input: intelJSONStream(true, first, classView[0], classView[1]), ++ wantCount: 2, ++ wantPower: 3, ++ wantPkg: 5, ++ wantEngines: classViewWant, ++ }, ++ { ++ name: "closed array", ++ input: intelJSONStream(true, first, classView[0], classView[1]) + "\n]\n", ++ wantCount: 2, ++ wantPower: 3, ++ wantPkg: 5, ++ wantEngines: classViewWant, ++ }, ++ { ++ name: "truncated final sample", ++ input: intelJSONStream(true, first, classView[0], classView[1], `{"period": {"duration": 33`), ++ wantCount: 2, ++ wantPower: 3, ++ wantPkg: 5, ++ wantEngines: classViewWant, + }, + { +- name: "basic headers with RCS BCS VCS using index in name", +- header1: "Freq MHz IRQ RC6 Power W IMC MiB/s RCS/0 BCS/1 VCS/2", +- header2: " req act /s % gpu pkg rd wr % se wa % se wa % se wa", +- wantEngineNames: []string{"RCS", "BCS", "VCS"}, +- wantFriendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- wantPowerIndex: 4, // "gpu" is at index 4 +- wantPreEngineCols: 8, // 17 total cols - 3*3 = 8 ++ // intel_gpu_top < 1.28 omits the opening "[" and uses physical engine names ++ name: "legacy output without array and with engine instances", ++ input: intelJSONStream(false, ++ intelJSONSample(9, 9, map[string]float64{"Render/3D/0": 99}), ++ intelJSONSample(1.5, 2.5, map[string]float64{"Render/3D/0": 12, "Blitter/0": 1, "Video/0": 4, "Video/1": 6, "VideoEnhance/0": 2}), ++ ), ++ wantCount: 1, ++ wantPower: 1.5, ++ wantPkg: 2.5, ++ wantEngines: map[string]float64{"Render/3D": 12, "Blitter": 1, "Video": 10, "VideoEnhance": 2}, + }, + { +- name: "headers with only RCS", +- header1: "Freq MHz IRQ RC6 Power W IMC MiB/s RCS", +- header2: " req act /s % gpu pkg rd wr % se wa", +- wantEngineNames: []string{"RCS"}, +- wantFriendlyNames: []string{"Render/3D"}, +- wantPowerIndex: 4, +- wantPreEngineCols: 8, // 11 total - 3*1 = 8 ++ // energy counter read lower than the previous sample in intel_gpu_top ++ name: "sample with invalid power is skipped", ++ input: intelJSONStream(true, first, classView[0], ++ intelJSONSample(86_000_000, 3, map[string]float64{"Render/3D": 50}), ++ intelJSONSample(2, 90_000_000, map[string]float64{"Render/3D": 50}), ++ classView[1], ++ ), ++ wantCount: 2, ++ wantPower: 3, ++ wantPkg: 5, ++ wantEngines: classViewWant, + }, + { +- name: "headers with VECS and CCS", +- header1: "Freq MHz IRQ RC6 Power W IMC MiB/s VECS CCS", +- header2: " req act /s % gpu pkg rd wr % se wa % se wa", +- wantEngineNames: []string{"VECS", "CCS"}, +- wantFriendlyNames: []string{"VideoEnhance", "Compute"}, +- wantPowerIndex: 4, +- wantPreEngineCols: 8, // 14 total - 3*2 = 8 ++ name: "only samples with invalid power", ++ input: intelJSONStream(true, first, intelJSONSample(86_000_000, 3, map[string]float64{"Render/3D": 50})), ++ wantErr: errNoValidData, + }, + { +- name: "no engines", +- header1: "Freq MHz IRQ RC6 Power W IMC MiB/s", +- header2: " req act /s % gpu pkg rd wr", +- wantEngineNames: nil, // no engines found, slices remain nil +- wantFriendlyNames: nil, +- wantPowerIndex: -1, // no engines, so no search +- wantPreEngineCols: 0, ++ name: "empty output", ++ input: "", ++ wantErr: errNoValidData, + }, + { +- name: "power index not found", +- header1: "Freq MHz IRQ RC6 Power W IMC MiB/s RCS", +- header2: " req act /s % pkg cpu rd wr % se wa", // no "gpu" +- wantEngineNames: []string{"RCS"}, +- wantFriendlyNames: []string{"Render/3D"}, +- wantPowerIndex: -1, // "gpu" not found +- wantPreEngineCols: 8, // 11 total - 3*1 = 8 ++ name: "only first sample, which is skipped", ++ input: intelJSONStream(true, first), ++ wantErr: errNoValidData, + }, + { +- name: "empty headers", +- header1: "", +- header2: "", +- wantEngineNames: nil, // empty input, slices remain nil +- wantFriendlyNames: nil, +- wantPowerIndex: -1, +- wantPreEngineCols: 0, ++ name: "invalid output", ++ input: "intel_gpu_top: command failed", ++ wantAnyErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { +- gm := &GPUManager{} +- engineNames, friendlyNames, powerIndex, preEngineCols := gm.parseIntelHeaders(tt.header1, tt.header2) +- +- assert.Equal(t, tt.wantEngineNames, engineNames) +- assert.Equal(t, tt.wantFriendlyNames, friendlyNames) +- assert.Equal(t, tt.wantPowerIndex, powerIndex) +- assert.Equal(t, tt.wantPreEngineCols, preEngineCols) ++ gm := &GPUManager{GpuDataMap: make(map[string]*system.GPUData)} ++ err := gm.parseIntelJSONStream(strings.NewReader(tt.input)) ++ if tt.wantAnyErr { ++ assert.Error(t, err) ++ return ++ } ++ if tt.wantErr != nil { ++ assert.ErrorIs(t, err, tt.wantErr) ++ assert.Empty(t, gm.GpuDataMap) ++ return ++ } ++ require.NoError(t, err) ++ ++ gpu := gm.GpuDataMap["i0"] ++ require.NotNil(t, gpu) ++ assert.Equal(t, tt.wantCount, gpu.Count) ++ assert.InDelta(t, tt.wantPower, gpu.Power, 0.001) ++ assert.InDelta(t, tt.wantPkg, gpu.PowerPkg, 0.001) ++ assert.Len(t, gpu.Engines, len(tt.wantEngines)) ++ for name, want := range tt.wantEngines { ++ assert.InDelta(t, want, gpu.Engines[name], 0.001, name) ++ } + }) + } + } + +-func TestParseIntelData(t *testing.T) { +- tests := []struct { +- name string +- line string +- engineNames []string +- friendlyNames []string +- powerIndex int +- preEngineCols int +- wantPowerGPU float64 +- wantEngines map[string]float64 +- wantErr error +- }{ +- { +- name: "basic data with power and engines", +- line: "373 373 224 45 1.50 4.13 2554 714 12.34 0 0 0.00 0 0 5.00 0 0", +- engineNames: []string{"RCS", "BCS", "VCS"}, +- friendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 1.50, +- wantEngines: map[string]float64{ +- "Render/3D": 12.34, +- "Blitter": 0.00, +- "Video": 5.00, +- }, +- }, +- { +- name: "data with zero power", +- line: "226 223 338 58 0.00 2.69 1820 965 0.00 0 0 0.00 0 0 0.00 0 0", +- engineNames: []string{"RCS", "BCS", "VCS"}, +- friendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 0.00, +- wantEngines: map[string]float64{ +- "Render/3D": 0.00, +- "Blitter": 0.00, +- "Video": 0.00, +- }, +- }, +- { +- name: "data with no power index", +- line: "373 373 224 45 1.50 4.13 2554 714 12.34 0 0 0.00 0 0 5.00 0 0", +- engineNames: []string{"RCS", "BCS", "VCS"}, +- friendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- powerIndex: -1, +- preEngineCols: 8, +- wantPowerGPU: 0.0, // no power parsed +- wantEngines: map[string]float64{ +- "Render/3D": 12.34, +- "Blitter": 0.00, +- "Video": 5.00, +- }, +- }, +- { +- name: "data with insufficient columns", +- line: "373 373 224 45 1.50", // too few columns +- engineNames: []string{"RCS", "BCS", "VCS"}, +- friendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 0.0, +- wantEngines: nil, // empty sample returned +- wantErr: errNoValidData, +- }, +- { +- name: "empty line", +- line: "", +- engineNames: []string{"RCS"}, +- friendlyNames: []string{"Render/3D"}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 0.0, +- wantEngines: nil, +- wantErr: errNoValidData, +- }, +- { +- name: "data with invalid power value", +- line: "373 373 224 45 N/A 4.13 2554 714 12.34 0 0 0.00 0 0 5.00 0 0", +- engineNames: []string{"RCS", "BCS", "VCS"}, +- friendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 0.0, // N/A can't be parsed +- wantEngines: map[string]float64{ +- "Render/3D": 12.34, +- "Blitter": 0.00, +- "Video": 5.00, +- }, +- }, +- { +- name: "data with invalid engine value", +- line: "373 373 224 45 1.50 4.13 2554 714 N/A 0 0 0.00 0 0 5.00 0 0", +- engineNames: []string{"RCS", "BCS", "VCS"}, +- friendlyNames: []string{"Render/3D", "Blitter", "Video"}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 1.50, +- wantEngines: map[string]float64{ +- "Render/3D": 0.0, // N/A becomes 0 +- "Blitter": 0.00, +- "Video": 5.00, +- }, +- }, +- { +- name: "data with no engines", +- line: "373 373 224 45 1.50 4.13 2554 714", +- engineNames: []string{}, +- friendlyNames: []string{}, +- powerIndex: 4, +- preEngineCols: 8, +- wantPowerGPU: 1.50, +- wantEngines: nil, +- }, +- } ++func TestParseIntelJSONSample(t *testing.T) { ++ t.Run("without power", func(t *testing.T) { ++ var sample intelGpuJSONSample ++ require.NoError(t, json.Unmarshal([]byte(`{"engines": {"Render/3D": {"busy": 7.5, "unit": "%"}}}`), &sample)) ++ stats := parseIntelJSONSample(sample) ++ assert.Zero(t, stats.PowerGPU) ++ assert.Zero(t, stats.PowerPkg) ++ assert.Equal(t, map[string]float64{"Render/3D": 7.5}, stats.Engines) ++ }) + +- for _, tt := range tests { +- t.Run(tt.name, func(t *testing.T) { +- gm := &GPUManager{} +- sample, err := gm.parseIntelData(tt.line, tt.engineNames, tt.friendlyNames, tt.powerIndex, tt.preEngineCols) +- assert.Equal(t, tt.wantErr, err) ++ t.Run("without engines", func(t *testing.T) { ++ var sample intelGpuJSONSample ++ require.NoError(t, json.Unmarshal([]byte(`{"power": {"GPU": 1.25, "Package": 4.5, "unit": "W"}}`), &sample)) ++ stats := parseIntelJSONSample(sample) ++ assert.Equal(t, 1.25, stats.PowerGPU) ++ assert.Equal(t, 4.5, stats.PowerPkg) ++ assert.Nil(t, stats.Engines) ++ }) ++} + +- assert.Equal(t, tt.wantPowerGPU, sample.PowerGPU) +- assert.Equal(t, tt.wantEngines, sample.Engines) +- }) ++func TestIntelEngineClass(t *testing.T) { ++ tests := map[string]string{ ++ "Render/3D": "Render/3D", ++ "Render/3D/0": "Render/3D", ++ "Blitter": "Blitter", ++ "Blitter/0": "Blitter", ++ "Video/1": "Video", ++ "VideoEnhance/0": "VideoEnhance", ++ "Compute/3": "Compute", ++ "[unknown]": "[unknown]", ++ "[unknown]/0": "[unknown]", ++ "Video/": "Video/", ++ } ++ for key, want := range tests { ++ assert.Equal(t, want, intelEngineClass(key), key) + } + } + +@@ -2016,13 +1997,11 @@ func TestIntelCollectorDeviceEnv(t *testing.T) { + + // Create a fake intel_gpu_top that records its arguments and prints minimal valid output + scriptPath := filepath.Join(dir, "intel_gpu_top") +- script := fmt.Sprintf(`#!/bin/sh +-echo "$@" > %s +-echo "Freq MHz IRQ RC6 Power W IMC MiB/s RCS VCS" +-echo " req act /s %% gpu pkg rd wr %% se wa %% se wa" +-echo "226 223 338 58 2.00 2.69 1820 965 0.00 0 0 0.00 0 0" +-echo "189 187 412 67 1.80 2.45 1950 823 8.50 2 1 15.00 1 0" +-`, argsFile) ++ output := intelJSONStream(true, ++ intelJSONSample(2, 2.69, map[string]float64{"Render/3D": 0, "Video": 0}), ++ intelJSONSample(1.8, 2.45, map[string]float64{"Render/3D": 8.5, "Video": 15}), ++ ) ++ script := fmt.Sprintf("#!/bin/sh\necho \"$@\" > %s\necho '%s'\n", argsFile, output) + if err := os.WriteFile(scriptPath, []byte(script), 0755); err != nil { + t.Fatal(err) + } +@@ -2043,5 +2022,5 @@ echo "189 187 412 67 1.80 2.45 1950 823 8.50 2 1 15.00 + argsStr := strings.TrimSpace(string(data)) + require.Contains(t, argsStr, "-d sriov") + require.Contains(t, argsStr, "-s ") +- require.Contains(t, argsStr, "-l") ++ require.Contains(t, argsStr, "-J") + } diff --git a/tasks/henrygd__beszel-2387/tests/test.sh b/tasks/henrygd__beszel-2387/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f6b8acb86478bc33d9ed200334a336f6223d6766 --- /dev/null +++ b/tasks/henrygd__beszel-2387/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 3f20ecae503117ff052061136b080b8f8cce2df9 > "$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/henrygd__beszel-2387/tests/verifier.py b/tasks/henrygd__beszel-2387/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2387/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/henrygd__beszel-2391/environment/Dockerfile b/tasks/henrygd__beszel-2391/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ead3c0d158c358e2ba96e657007e27952236ac9b --- /dev/null +++ b/tasks/henrygd__beszel-2391/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 97ea3c16cb079133929b98cf41b35a3651586a1a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 97ea3c16cb079133929b98cf41b35a3651586a1a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 97ea3c16cb079133929b98cf41b35a3651586a1a \ + && 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/henrygd__beszel-2391/instruction.md b/tasks/henrygd__beszel-2391/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..40eeaaaaaf56ebebe870ce693c8e22bb2d115fcb --- /dev/null +++ b/tasks/henrygd__beszel-2391/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix(ui): preserve paused systems in network monitors table + +## Description + +## 📃 Description + +Pausing a system was clearing its entire `info` record, including the agent version. The network monitors table uses that version to decide whether a system supports network monitoring (added in agent 0.20.0), so once a system was paused its monitors would silently disappear from the table instead of just being marked inactive. + +This PR preserves the agent version when clearing `info` on pause, and mutes (dims) the monitor's row in the network monitors table when its system is paused, matching the existing behavior in the main systems table. + +## 🔧 Fixed + +- Pausing a system no longer hides its rows from the network monitors table +- Network monitors table now visually mutes rows belonging to paused systems, consistent with the systems table + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97ea3c16cb07`. 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/henrygd__beszel-2391/solution/patch.diff b/tasks/henrygd__beszel-2391/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..60e388841210526512e5c3dfe28613aeecd2af56 --- /dev/null +++ b/tasks/henrygd__beszel-2391/solution/patch.diff @@ -0,0 +1,85 @@ +diff --git a/internal/hub/systems/system_manager.go b/internal/hub/systems/system_manager.go +index d1ff9633..be3a61fa 100644 +--- a/internal/hub/systems/system_manager.go ++++ b/internal/hub/systems/system_manager.go +@@ -190,7 +190,9 @@ func (sm *SystemManager) onRecordAfterCreateSuccess(e *core.RecordEvent) error { + // It clears system info when the status is changed to paused. + func (sm *SystemManager) onRecordUpdate(e *core.RecordEvent) error { + if e.Record.GetString("status") == paused { +- e.Record.Set("info", system.Info{}) ++ var prevInfo system.Info ++ e.Record.UnmarshalJSONField("info", &prevInfo) ++ e.Record.Set("info", system.Info{AgentVersion: prevInfo.AgentVersion}) + } + return e.Next() + } +diff --git a/internal/hub/systems/systems_test.go b/internal/hub/systems/systems_test.go +index cf4997f8..5063b22c 100644 +--- a/internal/hub/systems/systems_test.go ++++ b/internal/hub/systems/systems_test.go +@@ -18,6 +18,38 @@ import ( + "github.com/stretchr/testify/require" + ) + ++func TestPauseSystemPreservesAgentVersion(t *testing.T) { ++ hub, user := tests.GetHubWithUser(t) ++ defer hub.Cleanup() ++ ++ record, err := tests.CreateRecord(hub, "systems", map[string]any{ ++ "name": "pause-info-test", ++ "host": "localhost", ++ "port": "33914", ++ "users": []string{user.Id}, ++ }) ++ require.NoError(t, err) ++ ++ record.Set("info", system.Info{ ++ AgentVersion: "0.20.0", ++ Cpu: 42.5, ++ MemPct: 60, ++ Uptime: 3600, ++ Services: []uint16{3, 1}, ++ }) ++ require.NoError(t, hub.Save(record)) ++ ++ record.Set("status", "paused") ++ require.NoError(t, hub.Save(record)) ++ ++ pausedRecord, err := hub.FindRecordById("systems", record.Id) ++ require.NoError(t, err) ++ assert.Equal(t, "paused", pausedRecord.GetString("status")) ++ var info system.Info ++ require.NoError(t, pausedRecord.UnmarshalJSONField("info", &info)) ++ assert.Equal(t, system.Info{AgentVersion: "0.20.0"}, info) ++} ++ + func TestSystemManagerNew(t *testing.T) { + hub, err := tests.NewTestHub(t.TempDir()) + if err != nil { +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +index b330126f..e670986c 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +@@ -34,6 +34,7 @@ import { TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/compon + import { useToast } from "@/components/ui/use-toast" + import { isReadOnlyUser } from "@/lib/api" + import { pb } from "@/lib/api" ++import { SystemStatus } from "@/lib/enums" + import { $allSystemsById, $direction, $userSettings } from "@/lib/stores" + import { + cn, +@@ -450,10 +451,13 @@ const NetworkMonitorTableRow = memo(function NetworkMonitorTableRow({ + rowSelection: RowSelectionState + openSheet: (monitor: NetworkMonitorRecord) => void + }) { ++ const system = useStore($allSystemsById)[row.original.system] + return ( + openSheet(row.original)} + > + {row.getVisibleCells().map((cell) => ( diff --git a/tasks/henrygd__beszel-2391/solution/solve.sh b/tasks/henrygd__beszel-2391/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2391/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/henrygd__beszel-2391/task.toml b/tasks/henrygd__beszel-2391/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..939c991ca37fc351146792d4b11c75cacbe69c07 --- /dev/null +++ b/tasks/henrygd__beszel-2391/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2391" +description = "fix(ui): preserve paused systems in network monitors table" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "97ea3c16cb079133929b98cf41b35a3651586a1a" +reference = "https://github.com/henrygd/beszel/pull/2391" +source_access = "auto" +built_at = "2026-11-16T16:09:53.492134+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d9cf38475f9556d7951c134451439056618569e509365f7b5a3faf44e233c6b5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-22T22:40:47Z" +diff_format = "unified" +context_files = [ + "internal/hub/systems/system_manager.go", + "internal/hub/systems/systems_test.go", + "internal/site/src/components/network-monitors-table/network-monitors-table.tsx", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 42 +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:00.818850+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8703324cb54ea9fe8d24124fb9cd9ad3513883b22245c21fecdb853b0f68f29f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2391/tests/capture.py b/tasks/henrygd__beszel-2391/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2391/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/henrygd__beszel-2391/tests/instruction.md b/tasks/henrygd__beszel-2391/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..40eeaaaaaf56ebebe870ce693c8e22bb2d115fcb --- /dev/null +++ b/tasks/henrygd__beszel-2391/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix(ui): preserve paused systems in network monitors table + +## Description + +## 📃 Description + +Pausing a system was clearing its entire `info` record, including the agent version. The network monitors table uses that version to decide whether a system supports network monitoring (added in agent 0.20.0), so once a system was paused its monitors would silently disappear from the table instead of just being marked inactive. + +This PR preserves the agent version when clearing `info` on pause, and mutes (dims) the monitor's row in the network monitors table when its system is paused, matching the existing behavior in the main systems table. + +## 🔧 Fixed + +- Pausing a system no longer hides its rows from the network monitors table +- Network monitors table now visually mutes rows belonging to paused systems, consistent with the systems table + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97ea3c16cb07`. 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/henrygd__beszel-2391/tests/oracle.patch b/tasks/henrygd__beszel-2391/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..60e388841210526512e5c3dfe28613aeecd2af56 --- /dev/null +++ b/tasks/henrygd__beszel-2391/tests/oracle.patch @@ -0,0 +1,85 @@ +diff --git a/internal/hub/systems/system_manager.go b/internal/hub/systems/system_manager.go +index d1ff9633..be3a61fa 100644 +--- a/internal/hub/systems/system_manager.go ++++ b/internal/hub/systems/system_manager.go +@@ -190,7 +190,9 @@ func (sm *SystemManager) onRecordAfterCreateSuccess(e *core.RecordEvent) error { + // It clears system info when the status is changed to paused. + func (sm *SystemManager) onRecordUpdate(e *core.RecordEvent) error { + if e.Record.GetString("status") == paused { +- e.Record.Set("info", system.Info{}) ++ var prevInfo system.Info ++ e.Record.UnmarshalJSONField("info", &prevInfo) ++ e.Record.Set("info", system.Info{AgentVersion: prevInfo.AgentVersion}) + } + return e.Next() + } +diff --git a/internal/hub/systems/systems_test.go b/internal/hub/systems/systems_test.go +index cf4997f8..5063b22c 100644 +--- a/internal/hub/systems/systems_test.go ++++ b/internal/hub/systems/systems_test.go +@@ -18,6 +18,38 @@ import ( + "github.com/stretchr/testify/require" + ) + ++func TestPauseSystemPreservesAgentVersion(t *testing.T) { ++ hub, user := tests.GetHubWithUser(t) ++ defer hub.Cleanup() ++ ++ record, err := tests.CreateRecord(hub, "systems", map[string]any{ ++ "name": "pause-info-test", ++ "host": "localhost", ++ "port": "33914", ++ "users": []string{user.Id}, ++ }) ++ require.NoError(t, err) ++ ++ record.Set("info", system.Info{ ++ AgentVersion: "0.20.0", ++ Cpu: 42.5, ++ MemPct: 60, ++ Uptime: 3600, ++ Services: []uint16{3, 1}, ++ }) ++ require.NoError(t, hub.Save(record)) ++ ++ record.Set("status", "paused") ++ require.NoError(t, hub.Save(record)) ++ ++ pausedRecord, err := hub.FindRecordById("systems", record.Id) ++ require.NoError(t, err) ++ assert.Equal(t, "paused", pausedRecord.GetString("status")) ++ var info system.Info ++ require.NoError(t, pausedRecord.UnmarshalJSONField("info", &info)) ++ assert.Equal(t, system.Info{AgentVersion: "0.20.0"}, info) ++} ++ + func TestSystemManagerNew(t *testing.T) { + hub, err := tests.NewTestHub(t.TempDir()) + if err != nil { +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +index b330126f..e670986c 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +@@ -34,6 +34,7 @@ import { TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/compon + import { useToast } from "@/components/ui/use-toast" + import { isReadOnlyUser } from "@/lib/api" + import { pb } from "@/lib/api" ++import { SystemStatus } from "@/lib/enums" + import { $allSystemsById, $direction, $userSettings } from "@/lib/stores" + import { + cn, +@@ -450,10 +451,13 @@ const NetworkMonitorTableRow = memo(function NetworkMonitorTableRow({ + rowSelection: RowSelectionState + openSheet: (monitor: NetworkMonitorRecord) => void + }) { ++ const system = useStore($allSystemsById)[row.original.system] + return ( + openSheet(row.original)} + > + {row.getVisibleCells().map((cell) => ( diff --git a/tasks/henrygd__beszel-2391/tests/test.sh b/tasks/henrygd__beszel-2391/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f1eda824e00a5f2c398053de78016fbb82c1f851 --- /dev/null +++ b/tasks/henrygd__beszel-2391/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 97ea3c16cb079133929b98cf41b35a3651586a1a > "$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/henrygd__beszel-2391/tests/verifier.py b/tasks/henrygd__beszel-2391/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2391/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/henrygd__beszel-2392/environment/Dockerfile b/tasks/henrygd__beszel-2392/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ead3c0d158c358e2ba96e657007e27952236ac9b --- /dev/null +++ b/tasks/henrygd__beszel-2392/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 97ea3c16cb079133929b98cf41b35a3651586a1a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 97ea3c16cb079133929b98cf41b35a3651586a1a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 97ea3c16cb079133929b98cf41b35a3651586a1a \ + && 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/henrygd__beszel-2392/instruction.md b/tasks/henrygd__beszel-2392/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0728462e531313b1ea0c7ef28792de07c85f22d8 --- /dev/null +++ b/tasks/henrygd__beszel-2392/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** fix(ui): disable Add Monitor button when no eligible systems exist + +## Description + +## 📃 Description + +The "Add Monitor" button (and its "Bulk Add" menu item) on the Network Monitors page was always clickable, even when there were no systems eligible to attach a monitor to. Clicking it opened a dialog with an empty/unusable system picker, and the mistake was only caught at submit time. This disables the trigger button up front and adds a tooltip explaining why. + +## 📖 Documentation + +N/A + +## 🪵 Changelog + +### 🔧 Fixed + +- "Add Monitor" and "Bulk Add" are now disabled when no systems support network monitors (agent ≥ 0.20.0), instead of silently failing after opening the dialog +- Added a tooltip ("Add a system first") explaining why the buttons are disabled in that state + +## 📷 Screenshots + +Scherm­afbeelding 2026-09-22 om 20 49 42 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97ea3c16cb07`. 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/henrygd__beszel-2392/solution/patch.diff b/tasks/henrygd__beszel-2392/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d850d20cb497fb3884ddaa33997f5300b6548d03 --- /dev/null +++ b/tasks/henrygd__beszel-2392/solution/patch.diff @@ -0,0 +1,35 @@ +diff --git a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +index 733935dc..a227ef20 100644 +--- a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx ++++ b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +@@ -353,6 +353,8 @@ export function AddMonitorDialog({ systemId, monitors }: { systemId?: string; mo + const bulkFormRef = useRef(null) + const { toast } = useToast() + const { t } = useLingui() ++ const systems = useStore($systems) ++ const hasEligibleSystems = systemId ? true : systems.some(supportsNetworkMonitors) + + const resetBulkForm = () => { + setBulkInput("") +@@ -443,14 +445,19 @@ export function AddMonitorDialog({ systemId, monitors }: { systemId?: string; mo + return ( + <> +
+- +
+ + +- + diff --git a/tasks/henrygd__beszel-2392/solution/solve.sh b/tasks/henrygd__beszel-2392/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2392/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/henrygd__beszel-2392/task.toml b/tasks/henrygd__beszel-2392/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0db42f19d857dfab8e5d3b79b04eeb808132ffc3 --- /dev/null +++ b/tasks/henrygd__beszel-2392/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2392" +description = "fix(ui): disable Add Monitor button when no eligible systems exist" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "97ea3c16cb079133929b98cf41b35a3651586a1a" +reference = "https://github.com/henrygd/beszel/pull/2392" +source_access = "auto" +built_at = "2026-11-16T16:09:53.490582+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:95dc3bb249ad6bf394dbdf4632f76aaef46ad88ed409b5eae7cf29f0bf44e9f1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-22T23:04:49Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/network-monitors-table/monitor-dialog.tsx", +] +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:00.819297+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8703324cb54ea9fe8d24124fb9cd9ad3513883b22245c21fecdb853b0f68f29f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2392/tests/capture.py b/tasks/henrygd__beszel-2392/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2392/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/henrygd__beszel-2392/tests/instruction.md b/tasks/henrygd__beszel-2392/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0728462e531313b1ea0c7ef28792de07c85f22d8 --- /dev/null +++ b/tasks/henrygd__beszel-2392/tests/instruction.md @@ -0,0 +1,28 @@ +# Issue + +**Title:** fix(ui): disable Add Monitor button when no eligible systems exist + +## Description + +## 📃 Description + +The "Add Monitor" button (and its "Bulk Add" menu item) on the Network Monitors page was always clickable, even when there were no systems eligible to attach a monitor to. Clicking it opened a dialog with an empty/unusable system picker, and the mistake was only caught at submit time. This disables the trigger button up front and adds a tooltip explaining why. + +## 📖 Documentation + +N/A + +## 🪵 Changelog + +### 🔧 Fixed + +- "Add Monitor" and "Bulk Add" are now disabled when no systems support network monitors (agent ≥ 0.20.0), instead of silently failing after opening the dialog +- Added a tooltip ("Add a system first") explaining why the buttons are disabled in that state + +## 📷 Screenshots + +Scherm­afbeelding 2026-09-22 om 20 49 42 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97ea3c16cb07`. 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/henrygd__beszel-2392/tests/oracle.patch b/tasks/henrygd__beszel-2392/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d850d20cb497fb3884ddaa33997f5300b6548d03 --- /dev/null +++ b/tasks/henrygd__beszel-2392/tests/oracle.patch @@ -0,0 +1,35 @@ +diff --git a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +index 733935dc..a227ef20 100644 +--- a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx ++++ b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +@@ -353,6 +353,8 @@ export function AddMonitorDialog({ systemId, monitors }: { systemId?: string; mo + const bulkFormRef = useRef(null) + const { toast } = useToast() + const { t } = useLingui() ++ const systems = useStore($systems) ++ const hasEligibleSystems = systemId ? true : systems.some(supportsNetworkMonitors) + + const resetBulkForm = () => { + setBulkInput("") +@@ -443,14 +445,19 @@ export function AddMonitorDialog({ systemId, monitors }: { systemId?: string; mo + return ( + <> +
+- +
+ + +- + diff --git a/tasks/henrygd__beszel-2392/tests/test.sh b/tasks/henrygd__beszel-2392/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f1eda824e00a5f2c398053de78016fbb82c1f851 --- /dev/null +++ b/tasks/henrygd__beszel-2392/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 97ea3c16cb079133929b98cf41b35a3651586a1a > "$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/henrygd__beszel-2392/tests/verifier.py b/tasks/henrygd__beszel-2392/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2392/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/henrygd__beszel-2396/environment/Dockerfile b/tasks/henrygd__beszel-2396/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d8a268ff42020ecca25e11c81b2ba3ac80eaf63e --- /dev/null +++ b/tasks/henrygd__beszel-2396/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9042a8c5c8448344de968d4476a3cfa6ba1a02a1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9042a8c5c8448344de968d4476a3cfa6ba1a02a1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9042a8c5c8448344de968d4476a3cfa6ba1a02a1 \ + && 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/henrygd__beszel-2396/instruction.md b/tasks/henrygd__beszel-2396/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9280949ba2ac82a4088a56d4dd0057d194dc3078 --- /dev/null +++ b/tasks/henrygd__beszel-2396/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** feat(ui): Add view settings to network monitors table + +## Description + +## 📃 Description + +Adds a "View" dropdown to the network monitors table for controlling column sort and visibility, with the selection persisted per-user (server-synced settings, falling back to local/session storage) instead of being lost on reload. Following the pattern as the system table. + +## 🪵 Changelog + +### ➕ Added + +- "View" dropdown on the network monitors table with **Sort By** and **Visible Fields** sections for each column +- Column labels (`meta.label`) added to all network monitor columns for use in the new dropdown +- Sort order and column visibility are now persisted to user settings (`monitorCols`, `monitorSortMode`, `monitorSortModeSystem`) and synced across devices, with local/session storage as a fallback while settings load + +## 📷 Screenshots + +Scherm­afbeelding 2026-09-23 om 06 46 47 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9042a8c5c844`. 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/henrygd__beszel-2396/solution/patch.diff b/tasks/henrygd__beszel-2396/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..98222430305853c65321caa96a1aab4b16d93b47 --- /dev/null +++ b/tasks/henrygd__beszel-2396/solution/patch.diff @@ -0,0 +1,487 @@ +diff --git a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +index a227ef20..565c0eb8 100644 +--- a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx ++++ b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +@@ -23,7 +23,7 @@ import { Input } from "@/components/ui/input" + import { Label } from "@/components/ui/label" + import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" + import { Textarea } from "@/components/ui/textarea" +-import { ChevronDownIcon, ListIcon, SearchIcon, ServerIcon } from "lucide-react" ++import { ChevronDownIcon, ListIcon, PlusIcon, SearchIcon, ServerIcon } from "lucide-react" + import { useToast } from "@/components/ui/use-toast" + import { $systems } from "@/lib/stores" + import { cn, supportsNetworkMonitors } from "@/lib/utils" +@@ -446,8 +446,13 @@ export function AddMonitorDialog({ systemId, monitors }: { systemId?: string; mo + <> +
+ +
+ +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx +index 92d25aba..f0c4af0d 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx +@@ -40,6 +40,12 @@ import { Badge } from "../ui/badge" + import { getMonitorTarget } from "@/lib/network-monitor-utils" + import { pb } from "@/lib/api" + ++declare module "@tanstack/react-table" { ++ interface ColumnMeta { ++ label?: string ++ } ++} ++ + const protocolColors: Record = { + icmp: "bg-blue-500/15! text-blue-600 dark:text-blue-400", + tcp: "bg-purple-500/15! text-purple-600 dark:text-purple-400", +@@ -98,6 +104,7 @@ export function getMonitorColumns( + }, + { + id: "system", ++ meta: { label: t`System` }, + accessorFn: (record) => record.system, + sortingFn: (a, b) => { + const allSystems = $allSystemsById.get() +@@ -134,6 +141,7 @@ export function getMonitorColumns( + }, + { + id: "target", ++ meta: { label: t`Target` }, + sortingFn: (a, b) => a.original.target.localeCompare(b.original.target), + accessorFn: (record) => getMonitorTarget(record), + header: ({ column }) => , +@@ -164,6 +172,7 @@ export function getMonitorColumns( + }, + { + id: "protocol", ++ meta: { label: t`Protocol` }, + accessorFn: (record) => record.protocol, + header: ({ column }) => , + cell: ({ getValue }) => { +@@ -173,6 +182,7 @@ export function getMonitorColumns( + }, + { + id: "interval", ++ meta: { label: t`Interval` }, + accessorFn: (record) => record.interval, + invertSorting: true, + header: ({ column }) => , +@@ -180,6 +190,7 @@ export function getMonitorColumns( + }, + { + id: "res", ++ meta: { label: t`Response` }, + accessorFn: (record) => record.res, + invertSorting: true, + header: ({ column }) => , +@@ -187,6 +198,7 @@ export function getMonitorColumns( + }, + { + id: "res1h", ++ meta: { label: t`Avg 1h` }, + accessorFn: (record) => record.resAvg1h, + invertSorting: true, + header: ({ column }) => , +@@ -194,6 +206,7 @@ export function getMonitorColumns( + }, + { + id: "max1h", ++ meta: { label: t`Max 1h` }, + accessorFn: (record) => record.resMax1h, + invertSorting: true, + header: ({ column }) => , +@@ -201,6 +214,7 @@ export function getMonitorColumns( + }, + { + id: "min1h", ++ meta: { label: t`Min 1h` }, + accessorFn: (record) => record.resMin1h, + invertSorting: true, + header: ({ column }) => , +@@ -208,6 +222,7 @@ export function getMonitorColumns( + }, + { + id: "loss", ++ meta: { label: t`Loss 1h` }, + accessorFn: (record) => record.loss1h, + invertSorting: true, + header: ({ column }) => , +@@ -236,6 +251,7 @@ export function getMonitorColumns( + }, + { + id: "updated", ++ meta: { label: t`Updated` }, + invertSorting: true, + accessorFn: (record) => record.updated, + header: ({ column }) => , +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +index 4f381795..78f81efb 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +@@ -26,27 +26,47 @@ import { + AlertDialogTitle, + } from "@/components/ui/alert-dialog" + import { Button, buttonVariants } from "@/components/ui/button" +-import { memo, useCallback, useMemo, useRef, useState } from "react" ++import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react" ++import { subscribeKeys } from "nanostores" + import { getMonitorColumns } from "@/components/network-monitors-table/network-monitors-columns" + import { Card, CardHeader, CardTitle } from "@/components/ui/card" + import { Input } from "@/components/ui/input" + import { TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" + import { useToast } from "@/components/ui/use-toast" +-import { isReadOnlyUser } from "@/lib/api" ++import { isReadOnlyUser, queueUserSettings } from "@/lib/api" + import { pb } from "@/lib/api" + import { SystemStatus } from "@/lib/enums" +-import { $allSystemsById, $direction, getUserChartTime } from "@/lib/stores" ++import { $allSystemsById, $direction, $userSettings, getUserChartTime } from "@/lib/stores" + import { + cn, + isVisuallyLonger, + matchesFilterGroups, + parseFilterGroups, + parseSemVer, +- useBrowserStorage, + } from "@/lib/utils" + import type { ChartData, NetworkMonitorRecord } from "@/types" + import { AddMonitorDialog, EditMonitorDialog } from "./monitor-dialog" +-import { ArrowLeftRightIcon, EthernetPortIcon, LoaderCircleIcon, ServerIcon, XIcon } from "lucide-react" ++import { ++ ArrowDownIcon, ++ ArrowLeftRightIcon, ++ ArrowUpDownIcon, ++ ArrowUpIcon, ++ EthernetPortIcon, ++ EyeIcon, ++ LoaderCircleIcon, ++ ServerIcon, ++ Settings2Icon, ++ XIcon, ++} from "lucide-react" ++import { ++ DropdownMenu, ++ DropdownMenuCheckboxItem, ++ DropdownMenuContent, ++ DropdownMenuItem, ++ DropdownMenuLabel, ++ DropdownMenuSeparator, ++ DropdownMenuTrigger, ++} from "@/components/ui/dropdown-menu" + import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet" + import ChartTimeSelect from "@/components/charts/chart-time-select" + import { LossChart, AvgMinMaxResponseChart } from "@/components/routes/system/charts/monitors-charts" +@@ -66,13 +86,19 @@ export default function NetworkMonitorsTableNew({ + monitors: NetworkMonitorRecord[] + isLoading: boolean + }) { +- const [sorting, setSorting] = useBrowserStorage( +- `sort-np-target-${systemId ? 1 : 0}`, +- [{ id: systemId ? "target" : "system", desc: false }], +- sessionStorage ++ const sortSettingsKey = systemId ? "monitorSortModeSystem" : "monitorSortMode" ++ const sortStorageKey = `besz-sort-np-target-${systemId ? 1 : 0}` ++ const [sorting, setSorting] = useState( ++ () => ++ $userSettings.get()[sortSettingsKey] ?? ++ JSON.parse(sessionStorage.getItem(sortStorageKey) || "null") ?? [ ++ { id: systemId ? "target" : "system", desc: false }, ++ ] + ) + const [columnFilters, setColumnFilters] = useState([]) +- const [columnVisibility, setColumnVisibility] = useState({}) ++ const [columnVisibility, setColumnVisibility] = useState( ++ () => $userSettings.get().monitorCols ?? JSON.parse(localStorage.getItem("besz-monitor-cols") || "{}") ++ ) + const [rowSelection, setRowSelection] = useState({}) + const [globalFilter, setGlobalFilter] = useState("") + const [deleteOpen, setDeleteOpen] = useState(false) +@@ -82,6 +108,47 @@ export default function NetworkMonitorsTableNew({ + const { toast } = useToast() + const canManageMonitors = !isReadOnlyUser() + ++ // Apply settings from server once they load (handles incognito / new devices) ++ const appliedSettings = useRef(new Set()) ++ useEffect(() => { ++ return subscribeKeys($userSettings, ["monitorCols", sortSettingsKey], (vals) => { ++ if (!appliedSettings.current.has("monitorCols") && vals.monitorCols !== undefined) { ++ appliedSettings.current.add("monitorCols") ++ setColumnVisibility(vals.monitorCols) ++ } ++ if (!appliedSettings.current.has(sortSettingsKey) && vals[sortSettingsKey] !== undefined) { ++ appliedSettings.current.add(sortSettingsKey) ++ setSorting(vals[sortSettingsKey] as SortingState) ++ } ++ }) ++ }, [sortSettingsKey]) ++ ++ const handleColumnVisibilityChange = useCallback( ++ (updater: VisibilityState | ((prev: VisibilityState) => VisibilityState)) => { ++ setColumnVisibility((prev) => { ++ const next = typeof updater === "function" ? updater(prev) : updater ++ localStorage.setItem("besz-monitor-cols", JSON.stringify(next)) ++ $userSettings.setKey("monitorCols", next) ++ queueUserSettings({ monitorCols: next }) ++ return next ++ }) ++ }, ++ [] ++ ) ++ ++ const handleSortingChange = useCallback( ++ (updater: SortingState | ((prev: SortingState) => SortingState)) => { ++ setSorting((prev) => { ++ const next = typeof updater === "function" ? updater(prev) : updater ++ sessionStorage.setItem(sortStorageKey, JSON.stringify(next)) ++ $userSettings.setKey(sortSettingsKey, next) ++ queueUserSettings({ [sortSettingsKey]: next }) ++ return next ++ }) ++ }, ++ [sortSettingsKey, sortStorageKey] ++ ) ++ + const longestTarget = useMemo(() => { + let longestTarget = "" + for (const p of monitors) { +@@ -208,9 +275,9 @@ export default function NetworkMonitorsTableNew({ + getCoreRowModel: getCoreRowModel(), + getSortedRowModel: getSortedRowModel(), + getFilteredRowModel: getFilteredRowModel(), +- onSortingChange: setSorting, ++ onSortingChange: handleSortingChange, + onColumnFiltersChange: setColumnFilters, +- onColumnVisibilityChange: setColumnVisibility, ++ onColumnVisibilityChange: handleColumnVisibilityChange, + onRowSelectionChange: setRowSelection, + defaultColumn: { + sortUndefined: "last", +@@ -237,11 +304,12 @@ export default function NetworkMonitorsTableNew({ + + const rows = table.getRowModel().rows + const visibleColumns = table.getVisibleLeafColumns() ++ const visibleColumnsKey = visibleColumns.map((column) => column.id).join(",") + + return ( + + +-
++
+
+ + Network Monitors +@@ -250,14 +318,14 @@ export default function NetworkMonitorsTableNew({ + Response time monitoring from agents. +
+
+-
++
+ {monitors.length > 0 && ( +-
++
+ setGlobalFilter(e.target.value)} +- className="ms-auto px-4 w-full max-w-full md:w-50" ++ className="ms-auto px-4 w-full max-w-full md-lg:w-50" + /> + {globalFilter && ( + ++ ++ ++
++
++ ++ ++ Sort By ++ ++ ++
++ {table.getAllColumns().map((column) => { ++ if (!column.getCanSort()) return null ++ let Icon = ++ if (sorting[0]?.id === column.id) { ++ Icon = sorting[0]?.desc ? ( ++ ++ ) : ( ++ ++ ) ++ } ++ return ( ++ { ++ e.preventDefault() ++ handleSortingChange([ ++ { id: column.id, desc: sorting[0]?.id === column.id && !sorting[0]?.desc }, ++ ]) ++ }} ++ key={column.id} ++ > ++ {Icon} ++ {column.columnDef.meta?.label ?? column.id} ++ ++ ) ++ })} ++
++
++
++ ++ ++ Visible Fields ++ ++ ++
++ {table ++ .getAllColumns() ++ .filter((column) => column.getCanHide()) ++ .map((column) => ( ++ e.preventDefault()} ++ checked={column.getIsVisible()} ++ onCheckedChange={(value) => column.toggleVisibility(!!value)} ++ > ++ {column.columnDef.meta?.label ?? column.id} ++ ++ ))} ++
++
++
++
++ + {canManageMonitors ? : null} + {canManageMonitors ? ( + +@@ -337,12 +474,14 @@ const NetworkMonitorsTable = memo(function NetworkMonitorTable({ + table, + rows, + colLength, ++ visibleColumnsKey, + rowSelection, + isLoading, + }: { + table: TableType + rows: Row[] + colLength: number ++ visibleColumnsKey: string + rowSelection: RowSelectionState + isLoading: boolean + }) { +@@ -390,6 +529,7 @@ const NetworkMonitorsTable = memo(function NetworkMonitorTable({ + virtualRow={virtualRow} + isSelected={row.getIsSelected()} + rowSelection={rowSelection} ++ visibleColumnsKey={visibleColumnsKey} + openSheet={openSheet} + /> + ) +@@ -442,6 +582,9 @@ const NetworkMonitorTableRow = memo(function NetworkMonitorTableRow({ + virtualRow, + isSelected, + rowSelection: _rowSelection, ++ // Column visibility doesn't change the row object identity, so this prop exists only ++ // to force a re-render (and a fresh row.getVisibleCells() read) when columns are toggled. ++ visibleColumnsKey: _visibleColumnsKey, + openSheet, + }: { + row: Row +@@ -449,6 +592,7 @@ const NetworkMonitorTableRow = memo(function NetworkMonitorTableRow({ + isSelected: boolean + // Menus depend on the entire selection, including changes to other rows. + rowSelection: RowSelectionState ++ visibleColumnsKey: string + openSheet: (monitor: NetworkMonitorRecord) => void + }) { + const system = useStore($allSystemsById)[row.original.system] +diff --git a/internal/site/src/index.css b/internal/site/src/index.css +index d9e26c9d..d3f34f09 100644 +--- a/internal/site/src/index.css ++++ b/internal/site/src/index.css +@@ -68,6 +68,7 @@ + + --breakpoint-xs: 26.6rem; + --breakpoint-450: 28rem; ++ --breakpoint-md-lg: 53rem; + --breakpoint-2xl: 90rem; + + --radius-sm: calc(var(--radius) - 4px); +@@ -117,6 +118,7 @@ + } + + @layer utilities { ++ + /* Fonts */ + @supports (font-variation-settings: normal) { + :root { +@@ -147,11 +149,11 @@ + button { + cursor: pointer; + } +- ++ + /* cosmetic patch for half pixel gap in table headers when scrolling content shows at top */ + thead.sticky:before { + content: ""; +- @apply absolute -top-2 left-0 w-full h-4 bg-table-header z-50 ++ @apply absolute -top-2 left-0 w-full h-4 bg-table-header z-50 + } + } + +@@ -172,6 +174,7 @@ + @utility scrollbar-hide { + -ms-overflow-style: none; + scrollbar-width: none; ++ + &::-webkit-scrollbar { + display: none; + } +@@ -188,4 +191,4 @@ + + .recharts-yAxis { + @apply tabular-nums; +-} ++} +\ No newline at end of file +diff --git a/internal/site/src/types.d.ts b/internal/site/src/types.d.ts +index e39997a7..a8c2a3db 100644 +--- a/internal/site/src/types.d.ts ++++ b/internal/site/src/types.d.ts +@@ -377,6 +377,9 @@ export interface UserSettings { + statusFilter?: "all" | "up" | "down" | "paused" | "pending" + viewMode?: "table" | "grid" + sortMode?: Array<{ id: string; desc: boolean }> ++ monitorCols?: Record ++ monitorSortMode?: Array<{ id: string; desc: boolean }> ++ monitorSortModeSystem?: Array<{ id: string; desc: boolean }> + grid?: boolean + displayMode?: "default" | "tabs" + } diff --git a/tasks/henrygd__beszel-2396/solution/solve.sh b/tasks/henrygd__beszel-2396/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2396/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/henrygd__beszel-2396/task.toml b/tasks/henrygd__beszel-2396/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5c73790a18bf7e8d2c187384171c03018b844224 --- /dev/null +++ b/tasks/henrygd__beszel-2396/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2396" +description = "feat(ui): Add view settings to network monitors table" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "9042a8c5c8448344de968d4476a3cfa6ba1a02a1" +reference = "https://github.com/henrygd/beszel/pull/2396" +source_access = "auto" +built_at = "2026-11-16T16:09:53.488878+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c5ef121551e63d9deb6467e157497790e697190497e50c71869f642948fd6e7d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-23T17:47:43Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/network-monitors-table/monitor-dialog.tsx", + "internal/site/src/components/network-monitors-table/network-monitors-columns.tsx", + "internal/site/src/components/network-monitors-table/network-monitors-table.tsx", + "internal/site/src/index.css", + "internal/site/src/types.d.ts", +] +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:00.819756+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7417c38a0c08f67bbe31af4178a620265ed39308e3d54d1cdc22ed8ac44e151d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2396/tests/capture.py b/tasks/henrygd__beszel-2396/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2396/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/henrygd__beszel-2396/tests/instruction.md b/tasks/henrygd__beszel-2396/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9280949ba2ac82a4088a56d4dd0057d194dc3078 --- /dev/null +++ b/tasks/henrygd__beszel-2396/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** feat(ui): Add view settings to network monitors table + +## Description + +## 📃 Description + +Adds a "View" dropdown to the network monitors table for controlling column sort and visibility, with the selection persisted per-user (server-synced settings, falling back to local/session storage) instead of being lost on reload. Following the pattern as the system table. + +## 🪵 Changelog + +### ➕ Added + +- "View" dropdown on the network monitors table with **Sort By** and **Visible Fields** sections for each column +- Column labels (`meta.label`) added to all network monitor columns for use in the new dropdown +- Sort order and column visibility are now persisted to user settings (`monitorCols`, `monitorSortMode`, `monitorSortModeSystem`) and synced across devices, with local/session storage as a fallback while settings load + +## 📷 Screenshots + +Scherm­afbeelding 2026-09-23 om 06 46 47 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9042a8c5c844`. 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/henrygd__beszel-2396/tests/oracle.patch b/tasks/henrygd__beszel-2396/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..98222430305853c65321caa96a1aab4b16d93b47 --- /dev/null +++ b/tasks/henrygd__beszel-2396/tests/oracle.patch @@ -0,0 +1,487 @@ +diff --git a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +index a227ef20..565c0eb8 100644 +--- a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx ++++ b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +@@ -23,7 +23,7 @@ import { Input } from "@/components/ui/input" + import { Label } from "@/components/ui/label" + import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" + import { Textarea } from "@/components/ui/textarea" +-import { ChevronDownIcon, ListIcon, SearchIcon, ServerIcon } from "lucide-react" ++import { ChevronDownIcon, ListIcon, PlusIcon, SearchIcon, ServerIcon } from "lucide-react" + import { useToast } from "@/components/ui/use-toast" + import { $systems } from "@/lib/stores" + import { cn, supportsNetworkMonitors } from "@/lib/utils" +@@ -446,8 +446,13 @@ export function AddMonitorDialog({ systemId, monitors }: { systemId?: string; mo + <> +
+ +
+ +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx +index 92d25aba..f0c4af0d 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx +@@ -40,6 +40,12 @@ import { Badge } from "../ui/badge" + import { getMonitorTarget } from "@/lib/network-monitor-utils" + import { pb } from "@/lib/api" + ++declare module "@tanstack/react-table" { ++ interface ColumnMeta { ++ label?: string ++ } ++} ++ + const protocolColors: Record = { + icmp: "bg-blue-500/15! text-blue-600 dark:text-blue-400", + tcp: "bg-purple-500/15! text-purple-600 dark:text-purple-400", +@@ -98,6 +104,7 @@ export function getMonitorColumns( + }, + { + id: "system", ++ meta: { label: t`System` }, + accessorFn: (record) => record.system, + sortingFn: (a, b) => { + const allSystems = $allSystemsById.get() +@@ -134,6 +141,7 @@ export function getMonitorColumns( + }, + { + id: "target", ++ meta: { label: t`Target` }, + sortingFn: (a, b) => a.original.target.localeCompare(b.original.target), + accessorFn: (record) => getMonitorTarget(record), + header: ({ column }) => , +@@ -164,6 +172,7 @@ export function getMonitorColumns( + }, + { + id: "protocol", ++ meta: { label: t`Protocol` }, + accessorFn: (record) => record.protocol, + header: ({ column }) => , + cell: ({ getValue }) => { +@@ -173,6 +182,7 @@ export function getMonitorColumns( + }, + { + id: "interval", ++ meta: { label: t`Interval` }, + accessorFn: (record) => record.interval, + invertSorting: true, + header: ({ column }) => , +@@ -180,6 +190,7 @@ export function getMonitorColumns( + }, + { + id: "res", ++ meta: { label: t`Response` }, + accessorFn: (record) => record.res, + invertSorting: true, + header: ({ column }) => , +@@ -187,6 +198,7 @@ export function getMonitorColumns( + }, + { + id: "res1h", ++ meta: { label: t`Avg 1h` }, + accessorFn: (record) => record.resAvg1h, + invertSorting: true, + header: ({ column }) => , +@@ -194,6 +206,7 @@ export function getMonitorColumns( + }, + { + id: "max1h", ++ meta: { label: t`Max 1h` }, + accessorFn: (record) => record.resMax1h, + invertSorting: true, + header: ({ column }) => , +@@ -201,6 +214,7 @@ export function getMonitorColumns( + }, + { + id: "min1h", ++ meta: { label: t`Min 1h` }, + accessorFn: (record) => record.resMin1h, + invertSorting: true, + header: ({ column }) => , +@@ -208,6 +222,7 @@ export function getMonitorColumns( + }, + { + id: "loss", ++ meta: { label: t`Loss 1h` }, + accessorFn: (record) => record.loss1h, + invertSorting: true, + header: ({ column }) => , +@@ -236,6 +251,7 @@ export function getMonitorColumns( + }, + { + id: "updated", ++ meta: { label: t`Updated` }, + invertSorting: true, + accessorFn: (record) => record.updated, + header: ({ column }) => , +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +index 4f381795..78f81efb 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +@@ -26,27 +26,47 @@ import { + AlertDialogTitle, + } from "@/components/ui/alert-dialog" + import { Button, buttonVariants } from "@/components/ui/button" +-import { memo, useCallback, useMemo, useRef, useState } from "react" ++import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react" ++import { subscribeKeys } from "nanostores" + import { getMonitorColumns } from "@/components/network-monitors-table/network-monitors-columns" + import { Card, CardHeader, CardTitle } from "@/components/ui/card" + import { Input } from "@/components/ui/input" + import { TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" + import { useToast } from "@/components/ui/use-toast" +-import { isReadOnlyUser } from "@/lib/api" ++import { isReadOnlyUser, queueUserSettings } from "@/lib/api" + import { pb } from "@/lib/api" + import { SystemStatus } from "@/lib/enums" +-import { $allSystemsById, $direction, getUserChartTime } from "@/lib/stores" ++import { $allSystemsById, $direction, $userSettings, getUserChartTime } from "@/lib/stores" + import { + cn, + isVisuallyLonger, + matchesFilterGroups, + parseFilterGroups, + parseSemVer, +- useBrowserStorage, + } from "@/lib/utils" + import type { ChartData, NetworkMonitorRecord } from "@/types" + import { AddMonitorDialog, EditMonitorDialog } from "./monitor-dialog" +-import { ArrowLeftRightIcon, EthernetPortIcon, LoaderCircleIcon, ServerIcon, XIcon } from "lucide-react" ++import { ++ ArrowDownIcon, ++ ArrowLeftRightIcon, ++ ArrowUpDownIcon, ++ ArrowUpIcon, ++ EthernetPortIcon, ++ EyeIcon, ++ LoaderCircleIcon, ++ ServerIcon, ++ Settings2Icon, ++ XIcon, ++} from "lucide-react" ++import { ++ DropdownMenu, ++ DropdownMenuCheckboxItem, ++ DropdownMenuContent, ++ DropdownMenuItem, ++ DropdownMenuLabel, ++ DropdownMenuSeparator, ++ DropdownMenuTrigger, ++} from "@/components/ui/dropdown-menu" + import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet" + import ChartTimeSelect from "@/components/charts/chart-time-select" + import { LossChart, AvgMinMaxResponseChart } from "@/components/routes/system/charts/monitors-charts" +@@ -66,13 +86,19 @@ export default function NetworkMonitorsTableNew({ + monitors: NetworkMonitorRecord[] + isLoading: boolean + }) { +- const [sorting, setSorting] = useBrowserStorage( +- `sort-np-target-${systemId ? 1 : 0}`, +- [{ id: systemId ? "target" : "system", desc: false }], +- sessionStorage ++ const sortSettingsKey = systemId ? "monitorSortModeSystem" : "monitorSortMode" ++ const sortStorageKey = `besz-sort-np-target-${systemId ? 1 : 0}` ++ const [sorting, setSorting] = useState( ++ () => ++ $userSettings.get()[sortSettingsKey] ?? ++ JSON.parse(sessionStorage.getItem(sortStorageKey) || "null") ?? [ ++ { id: systemId ? "target" : "system", desc: false }, ++ ] + ) + const [columnFilters, setColumnFilters] = useState([]) +- const [columnVisibility, setColumnVisibility] = useState({}) ++ const [columnVisibility, setColumnVisibility] = useState( ++ () => $userSettings.get().monitorCols ?? JSON.parse(localStorage.getItem("besz-monitor-cols") || "{}") ++ ) + const [rowSelection, setRowSelection] = useState({}) + const [globalFilter, setGlobalFilter] = useState("") + const [deleteOpen, setDeleteOpen] = useState(false) +@@ -82,6 +108,47 @@ export default function NetworkMonitorsTableNew({ + const { toast } = useToast() + const canManageMonitors = !isReadOnlyUser() + ++ // Apply settings from server once they load (handles incognito / new devices) ++ const appliedSettings = useRef(new Set()) ++ useEffect(() => { ++ return subscribeKeys($userSettings, ["monitorCols", sortSettingsKey], (vals) => { ++ if (!appliedSettings.current.has("monitorCols") && vals.monitorCols !== undefined) { ++ appliedSettings.current.add("monitorCols") ++ setColumnVisibility(vals.monitorCols) ++ } ++ if (!appliedSettings.current.has(sortSettingsKey) && vals[sortSettingsKey] !== undefined) { ++ appliedSettings.current.add(sortSettingsKey) ++ setSorting(vals[sortSettingsKey] as SortingState) ++ } ++ }) ++ }, [sortSettingsKey]) ++ ++ const handleColumnVisibilityChange = useCallback( ++ (updater: VisibilityState | ((prev: VisibilityState) => VisibilityState)) => { ++ setColumnVisibility((prev) => { ++ const next = typeof updater === "function" ? updater(prev) : updater ++ localStorage.setItem("besz-monitor-cols", JSON.stringify(next)) ++ $userSettings.setKey("monitorCols", next) ++ queueUserSettings({ monitorCols: next }) ++ return next ++ }) ++ }, ++ [] ++ ) ++ ++ const handleSortingChange = useCallback( ++ (updater: SortingState | ((prev: SortingState) => SortingState)) => { ++ setSorting((prev) => { ++ const next = typeof updater === "function" ? updater(prev) : updater ++ sessionStorage.setItem(sortStorageKey, JSON.stringify(next)) ++ $userSettings.setKey(sortSettingsKey, next) ++ queueUserSettings({ [sortSettingsKey]: next }) ++ return next ++ }) ++ }, ++ [sortSettingsKey, sortStorageKey] ++ ) ++ + const longestTarget = useMemo(() => { + let longestTarget = "" + for (const p of monitors) { +@@ -208,9 +275,9 @@ export default function NetworkMonitorsTableNew({ + getCoreRowModel: getCoreRowModel(), + getSortedRowModel: getSortedRowModel(), + getFilteredRowModel: getFilteredRowModel(), +- onSortingChange: setSorting, ++ onSortingChange: handleSortingChange, + onColumnFiltersChange: setColumnFilters, +- onColumnVisibilityChange: setColumnVisibility, ++ onColumnVisibilityChange: handleColumnVisibilityChange, + onRowSelectionChange: setRowSelection, + defaultColumn: { + sortUndefined: "last", +@@ -237,11 +304,12 @@ export default function NetworkMonitorsTableNew({ + + const rows = table.getRowModel().rows + const visibleColumns = table.getVisibleLeafColumns() ++ const visibleColumnsKey = visibleColumns.map((column) => column.id).join(",") + + return ( + + +-
++
+
+ + Network Monitors +@@ -250,14 +318,14 @@ export default function NetworkMonitorsTableNew({ + Response time monitoring from agents. +
+
+-
++
+ {monitors.length > 0 && ( +-
++
+ setGlobalFilter(e.target.value)} +- className="ms-auto px-4 w-full max-w-full md:w-50" ++ className="ms-auto px-4 w-full max-w-full md-lg:w-50" + /> + {globalFilter && ( + ++ ++ ++
++
++ ++ ++ Sort By ++ ++ ++
++ {table.getAllColumns().map((column) => { ++ if (!column.getCanSort()) return null ++ let Icon = ++ if (sorting[0]?.id === column.id) { ++ Icon = sorting[0]?.desc ? ( ++ ++ ) : ( ++ ++ ) ++ } ++ return ( ++ { ++ e.preventDefault() ++ handleSortingChange([ ++ { id: column.id, desc: sorting[0]?.id === column.id && !sorting[0]?.desc }, ++ ]) ++ }} ++ key={column.id} ++ > ++ {Icon} ++ {column.columnDef.meta?.label ?? column.id} ++ ++ ) ++ })} ++
++
++
++ ++ ++ Visible Fields ++ ++ ++
++ {table ++ .getAllColumns() ++ .filter((column) => column.getCanHide()) ++ .map((column) => ( ++ e.preventDefault()} ++ checked={column.getIsVisible()} ++ onCheckedChange={(value) => column.toggleVisibility(!!value)} ++ > ++ {column.columnDef.meta?.label ?? column.id} ++ ++ ))} ++
++
++
++
++ + {canManageMonitors ? : null} + {canManageMonitors ? ( + +@@ -337,12 +474,14 @@ const NetworkMonitorsTable = memo(function NetworkMonitorTable({ + table, + rows, + colLength, ++ visibleColumnsKey, + rowSelection, + isLoading, + }: { + table: TableType + rows: Row[] + colLength: number ++ visibleColumnsKey: string + rowSelection: RowSelectionState + isLoading: boolean + }) { +@@ -390,6 +529,7 @@ const NetworkMonitorsTable = memo(function NetworkMonitorTable({ + virtualRow={virtualRow} + isSelected={row.getIsSelected()} + rowSelection={rowSelection} ++ visibleColumnsKey={visibleColumnsKey} + openSheet={openSheet} + /> + ) +@@ -442,6 +582,9 @@ const NetworkMonitorTableRow = memo(function NetworkMonitorTableRow({ + virtualRow, + isSelected, + rowSelection: _rowSelection, ++ // Column visibility doesn't change the row object identity, so this prop exists only ++ // to force a re-render (and a fresh row.getVisibleCells() read) when columns are toggled. ++ visibleColumnsKey: _visibleColumnsKey, + openSheet, + }: { + row: Row +@@ -449,6 +592,7 @@ const NetworkMonitorTableRow = memo(function NetworkMonitorTableRow({ + isSelected: boolean + // Menus depend on the entire selection, including changes to other rows. + rowSelection: RowSelectionState ++ visibleColumnsKey: string + openSheet: (monitor: NetworkMonitorRecord) => void + }) { + const system = useStore($allSystemsById)[row.original.system] +diff --git a/internal/site/src/index.css b/internal/site/src/index.css +index d9e26c9d..d3f34f09 100644 +--- a/internal/site/src/index.css ++++ b/internal/site/src/index.css +@@ -68,6 +68,7 @@ + + --breakpoint-xs: 26.6rem; + --breakpoint-450: 28rem; ++ --breakpoint-md-lg: 53rem; + --breakpoint-2xl: 90rem; + + --radius-sm: calc(var(--radius) - 4px); +@@ -117,6 +118,7 @@ + } + + @layer utilities { ++ + /* Fonts */ + @supports (font-variation-settings: normal) { + :root { +@@ -147,11 +149,11 @@ + button { + cursor: pointer; + } +- ++ + /* cosmetic patch for half pixel gap in table headers when scrolling content shows at top */ + thead.sticky:before { + content: ""; +- @apply absolute -top-2 left-0 w-full h-4 bg-table-header z-50 ++ @apply absolute -top-2 left-0 w-full h-4 bg-table-header z-50 + } + } + +@@ -172,6 +174,7 @@ + @utility scrollbar-hide { + -ms-overflow-style: none; + scrollbar-width: none; ++ + &::-webkit-scrollbar { + display: none; + } +@@ -188,4 +191,4 @@ + + .recharts-yAxis { + @apply tabular-nums; +-} ++} +\ No newline at end of file +diff --git a/internal/site/src/types.d.ts b/internal/site/src/types.d.ts +index e39997a7..a8c2a3db 100644 +--- a/internal/site/src/types.d.ts ++++ b/internal/site/src/types.d.ts +@@ -377,6 +377,9 @@ export interface UserSettings { + statusFilter?: "all" | "up" | "down" | "paused" | "pending" + viewMode?: "table" | "grid" + sortMode?: Array<{ id: string; desc: boolean }> ++ monitorCols?: Record ++ monitorSortMode?: Array<{ id: string; desc: boolean }> ++ monitorSortModeSystem?: Array<{ id: string; desc: boolean }> + grid?: boolean + displayMode?: "default" | "tabs" + } diff --git a/tasks/henrygd__beszel-2396/tests/test.sh b/tasks/henrygd__beszel-2396/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..184eded4d085a8506807b9623846f228997442a2 --- /dev/null +++ b/tasks/henrygd__beszel-2396/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 9042a8c5c8448344de968d4476a3cfa6ba1a02a1 > "$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/henrygd__beszel-2396/tests/verifier.py b/tasks/henrygd__beszel-2396/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2396/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/henrygd__beszel-2399/environment/Dockerfile b/tasks/henrygd__beszel-2399/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b7c9bacc56408cc05cd8649b3f5b537a62f44bf8 --- /dev/null +++ b/tasks/henrygd__beszel-2399/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e4b84b72abac255f5604776632af1662a453f7f4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e4b84b72abac255f5604776632af1662a453f7f4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e4b84b72abac255f5604776632af1662a453f7f4 \ + && 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/henrygd__beszel-2399/instruction.md b/tasks/henrygd__beszel-2399/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..430df287e88d5ea216ccd1048d07a97919425693 --- /dev/null +++ b/tasks/henrygd__beszel-2399/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** feat(ui): simplify Services column in systems table + +## Description + +## 📃 Description + +Makes the Services column in the systems table easier to read at a glance. Instead of `12 (failed: 2)`, the cell now shows just the service count, and the colored dot shows whether any have failed. + +With the failed count removed from the cell, sorting now matches what's on screen: rows are grouped by dot color first, then sorted by total services. + +## 🪵 Changelog + +### ✏️ Changed + +- Services column shows `1 service` / `N services` (properly pluralized) instead of the bare number. +- Services column sorts by whether a system has failed services (dot color) first, then by total count. It previously sorted by the failed count, which is no longer shown. + +### 🗑️ Removed + +- `(failed: N)` text from the Services column. The red dot still shows when any service has failed, and the exact count is on the system page. + +## 📷 Screenshots + +Scherm­afbeelding 2026-09-23 om 18 11 58 + +Scherm­afbeelding 2026-09-23 om 20 21 49 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e4b84b72abac`. 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/henrygd__beszel-2399/solution/patch.diff b/tasks/henrygd__beszel-2399/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f06e58d5ef2d5efe0ed483426e6160cbbae65227 --- /dev/null +++ b/tasks/henrygd__beszel-2399/solution/patch.diff @@ -0,0 +1,72 @@ +diff --git a/internal/site/src/components/systems-table/systems-table-columns.tsx b/internal/site/src/components/systems-table/systems-table-columns.tsx +index 1db27673..c49b8ca6 100644 +--- a/internal/site/src/components/systems-table/systems-table-columns.tsx ++++ b/internal/site/src/components/systems-table/systems-table-columns.tsx +@@ -1,5 +1,5 @@ + /** biome-ignore-all lint/correctness/useHookAtTopLevel: Hooks live inside memoized column definitions */ +-import { t } from "@lingui/core/macro" ++import { plural, t } from "@lingui/core/macro" + import { Trans, useLingui } from "@lingui/react/macro" + import { useStore } from "@nanostores/react" + import { getPagePath } from "@nanostores/router" +@@ -345,11 +345,13 @@ export function SystemsTableColumns(viewMode: "table" | "grid"): ColumnDef { +- // sort priorities: 1) failed services, 2) total services ++ // sort priorities: 1) has failed services (dot color), 2) total services + const [totalCountA, numFailedA] = a.original.info.sv ?? [0, 0] + const [totalCountB, numFailedB] = b.original.info.sv ?? [0, 0] +- if (numFailedA !== numFailedB) { +- return numFailedA - numFailedB ++ const hasFailedA = numFailedA > 0 ? 1 : 0 ++ const hasFailedB = numFailedB > 0 ? 1 : 0 ++ if (hasFailedA !== hasFailedB) { ++ return hasFailedA - hasFailedB + } + return totalCountA - totalCountB + }, +@@ -359,20 +361,36 @@ export function SystemsTableColumns(viewMode: "table" | "grid"): ColumnDef + 0, +- [STATUS_COLORS[SystemStatus.Up]]: numFailed === 0, ++ [STATUS_COLORS.pending]: numFailed > 0, ++ [STATUS_COLORS.up]: numFailed === 0, + })} + /> +- {totalCount}{" "} +- +- ({t`Failed`.toLowerCase()}: {numFailed}) +- ++ {plural(totalCount, { one: "# service", other: "# services" })} + + ) ++ if (numFailed === 0) { ++ return content ++ } ++ return ( ++ ++ ++ ++ {content} ++ ++ ++ ++ {plural(numFailed, { one: "# failed service", other: "# failed services" })} ++ ++ ++ ) + }, + }, + { diff --git a/tasks/henrygd__beszel-2399/solution/solve.sh b/tasks/henrygd__beszel-2399/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2399/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/henrygd__beszel-2399/task.toml b/tasks/henrygd__beszel-2399/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e3415181d04591a9478d43d1bb90ac569bcddd10 --- /dev/null +++ b/tasks/henrygd__beszel-2399/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2399" +description = "feat(ui): simplify Services column in systems table" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "e4b84b72abac255f5604776632af1662a453f7f4" +reference = "https://github.com/henrygd/beszel/pull/2399" +source_access = "auto" +built_at = "2026-11-16T16:09:53.487280+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3c294ed3a4df19942bd3f11113f9564e40aaa956c90887dca9f5c67e3cf56d56" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-24T16:05:27Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/systems-table/systems-table-columns.tsx", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 40 +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:00.820206+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c19eeae41eb88ce5af38a64e4691938fff662963875195ca28e9f675841f0310" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2399/tests/capture.py b/tasks/henrygd__beszel-2399/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2399/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/henrygd__beszel-2399/tests/instruction.md b/tasks/henrygd__beszel-2399/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..430df287e88d5ea216ccd1048d07a97919425693 --- /dev/null +++ b/tasks/henrygd__beszel-2399/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** feat(ui): simplify Services column in systems table + +## Description + +## 📃 Description + +Makes the Services column in the systems table easier to read at a glance. Instead of `12 (failed: 2)`, the cell now shows just the service count, and the colored dot shows whether any have failed. + +With the failed count removed from the cell, sorting now matches what's on screen: rows are grouped by dot color first, then sorted by total services. + +## 🪵 Changelog + +### ✏️ Changed + +- Services column shows `1 service` / `N services` (properly pluralized) instead of the bare number. +- Services column sorts by whether a system has failed services (dot color) first, then by total count. It previously sorted by the failed count, which is no longer shown. + +### 🗑️ Removed + +- `(failed: N)` text from the Services column. The red dot still shows when any service has failed, and the exact count is on the system page. + +## 📷 Screenshots + +Scherm­afbeelding 2026-09-23 om 18 11 58 + +Scherm­afbeelding 2026-09-23 om 20 21 49 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e4b84b72abac`. 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/henrygd__beszel-2399/tests/oracle.patch b/tasks/henrygd__beszel-2399/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f06e58d5ef2d5efe0ed483426e6160cbbae65227 --- /dev/null +++ b/tasks/henrygd__beszel-2399/tests/oracle.patch @@ -0,0 +1,72 @@ +diff --git a/internal/site/src/components/systems-table/systems-table-columns.tsx b/internal/site/src/components/systems-table/systems-table-columns.tsx +index 1db27673..c49b8ca6 100644 +--- a/internal/site/src/components/systems-table/systems-table-columns.tsx ++++ b/internal/site/src/components/systems-table/systems-table-columns.tsx +@@ -1,5 +1,5 @@ + /** biome-ignore-all lint/correctness/useHookAtTopLevel: Hooks live inside memoized column definitions */ +-import { t } from "@lingui/core/macro" ++import { plural, t } from "@lingui/core/macro" + import { Trans, useLingui } from "@lingui/react/macro" + import { useStore } from "@nanostores/react" + import { getPagePath } from "@nanostores/router" +@@ -345,11 +345,13 @@ export function SystemsTableColumns(viewMode: "table" | "grid"): ColumnDef { +- // sort priorities: 1) failed services, 2) total services ++ // sort priorities: 1) has failed services (dot color), 2) total services + const [totalCountA, numFailedA] = a.original.info.sv ?? [0, 0] + const [totalCountB, numFailedB] = b.original.info.sv ?? [0, 0] +- if (numFailedA !== numFailedB) { +- return numFailedA - numFailedB ++ const hasFailedA = numFailedA > 0 ? 1 : 0 ++ const hasFailedB = numFailedB > 0 ? 1 : 0 ++ if (hasFailedA !== hasFailedB) { ++ return hasFailedA - hasFailedB + } + return totalCountA - totalCountB + }, +@@ -359,20 +361,36 @@ export function SystemsTableColumns(viewMode: "table" | "grid"): ColumnDef + 0, +- [STATUS_COLORS[SystemStatus.Up]]: numFailed === 0, ++ [STATUS_COLORS.pending]: numFailed > 0, ++ [STATUS_COLORS.up]: numFailed === 0, + })} + /> +- {totalCount}{" "} +- +- ({t`Failed`.toLowerCase()}: {numFailed}) +- ++ {plural(totalCount, { one: "# service", other: "# services" })} + + ) ++ if (numFailed === 0) { ++ return content ++ } ++ return ( ++ ++ ++ ++ {content} ++ ++ ++ ++ {plural(numFailed, { one: "# failed service", other: "# failed services" })} ++ ++ ++ ) + }, + }, + { diff --git a/tasks/henrygd__beszel-2399/tests/test.sh b/tasks/henrygd__beszel-2399/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..32402f24890e85a3a3cc177afa49975209a72f15 --- /dev/null +++ b/tasks/henrygd__beszel-2399/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 e4b84b72abac255f5604776632af1662a453f7f4 > "$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/henrygd__beszel-2399/tests/verifier.py b/tasks/henrygd__beszel-2399/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2399/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/henrygd__beszel-2405/environment/Dockerfile b/tasks/henrygd__beszel-2405/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4fedb090dbd1cf1b7c4d77a71b0c457b12235b96 --- /dev/null +++ b/tasks/henrygd__beszel-2405/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3281055d95b365964e67296c8935cdcbc4bfaec1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3281055d95b365964e67296c8935cdcbc4bfaec1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3281055d95b365964e67296c8935cdcbc4bfaec1 \ + && 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/henrygd__beszel-2405/instruction.md b/tasks/henrygd__beszel-2405/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6f898417a539d9bf8ba35664f60f1e3bc0d91417 --- /dev/null +++ b/tasks/henrygd__beszel-2405/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** fix(ui): refresh interpolated translations on locale change + +## Description + +## 📃 Description + +Previously, translations weren't picked up everywhere when the language was changed; now it uses `useLingui()`, so it re-renders upon a language switch. + +## 📷 Screenshots + +
+ before +1 +
+
+ + after +2 +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3281055d95b3`. 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/henrygd__beszel-2405/solution/patch.diff b/tasks/henrygd__beszel-2405/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e1327b48b02be7bff895dac032f3dffad5a3edc4 --- /dev/null +++ b/tasks/henrygd__beszel-2405/solution/patch.diff @@ -0,0 +1,69 @@ +diff --git a/internal/site/src/components/add-system.tsx b/internal/site/src/components/add-system.tsx +index 9991ba25..e3a8e1b0 100644 +--- a/internal/site/src/components/add-system.tsx ++++ b/internal/site/src/components/add-system.tsx +@@ -1,5 +1,4 @@ +-import { t } from "@lingui/core/macro" +-import { Trans } from "@lingui/react/macro" ++import { Trans, useLingui } from "@lingui/react/macro" + import { useStore } from "@nanostores/react" + import { getPagePath } from "@nanostores/router" + import { ChevronDownIcon, ExternalLinkIcon } from "lucide-react" +@@ -65,6 +64,7 @@ let nextSystemToken: string | null = null + * @param {SystemRecord} [props.system] - Optional system record for editing an existing system. + */ + export const SystemDialog = ({ setOpen, system }: { setOpen: (open: boolean) => void; system?: SystemRecord }) => { ++ const { t } = useLingui() + const publicKey = useStore($publicKey) + const port = useRef(null) + const [hostValue, setHostValue] = useState(system?.host ?? "") +diff --git a/internal/site/src/components/navbar.tsx b/internal/site/src/components/navbar.tsx +index 28bf234c..79b50c31 100644 +--- a/internal/site/src/components/navbar.tsx ++++ b/internal/site/src/components/navbar.tsx +@@ -1,4 +1,4 @@ +-import { Trans } from "@lingui/react/macro" ++import { Trans, useLingui } from "@lingui/react/macro" + import { getPagePath } from "@nanostores/router" + import { + ContainerIcon, +@@ -42,6 +42,7 @@ const CommandPalette = lazy(() => import("./command-palette")) + const isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0 + + export default function Navbar() { ++ const { t } = useLingui() + const [addSystemDialogOpen, setAddSystemDialogOpen] = useState(false) + const [commandPaletteOpen, setCommandPaletteOpen] = useState(false) + +diff --git a/internal/site/src/components/routes/settings/quiet-hours.tsx b/internal/site/src/components/routes/settings/quiet-hours.tsx +index a23f9dee..8d45d501 100644 +--- a/internal/site/src/components/routes/settings/quiet-hours.tsx ++++ b/internal/site/src/components/routes/settings/quiet-hours.tsx +@@ -1,5 +1,4 @@ +-import { t } from "@lingui/core/macro" +-import { Trans } from "@lingui/react/macro" ++import { Trans, useLingui } from "@lingui/react/macro" + import { useStore } from "@nanostores/react" + import { + MoreHorizontalIcon, +@@ -42,9 +41,9 @@ import { $systems } from "@/lib/stores" + import { formatShortDate } from "@/lib/utils" + import type { QuietHoursRecord, SystemRecord } from "@/types" + +-const quietHoursTranslation = t`Quiet Hours` +- + export function QuietHours() { ++ const { t } = useLingui() ++ const quietHoursTranslation = t`Quiet Hours` + const [data, setData] = useState([]) + const [dialogOpen, setDialogOpen] = useState(false) + const [editingRecord, setEditingRecord] = useState(null) +@@ -293,6 +292,8 @@ function QuietHoursDialog({ + onClose: () => void + toast: ReturnType["toast"] + }) { ++ const { t } = useLingui() ++ const quietHoursTranslation = t`Quiet Hours` + const [selectedSystem, setSelectedSystem] = useState(editingRecord?.system || "") + const [isGlobal, setIsGlobal] = useState(!editingRecord?.system) + const [windowType, setWindowType] = useState<"one-time" | "daily">(editingRecord?.type || "one-time") diff --git a/tasks/henrygd__beszel-2405/solution/solve.sh b/tasks/henrygd__beszel-2405/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2405/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/henrygd__beszel-2405/task.toml b/tasks/henrygd__beszel-2405/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1931dbe86c315174683b8bd2599aa17aed5b915a --- /dev/null +++ b/tasks/henrygd__beszel-2405/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2405" +description = "fix(ui): refresh interpolated translations on locale change" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "3281055d95b365964e67296c8935cdcbc4bfaec1" +reference = "https://github.com/henrygd/beszel/pull/2405" +source_access = "auto" +built_at = "2026-11-16T16:09:53.460094+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:325017dc4c6e7807c2cdc00331ba8b179b66908ec6ebbc65b3dc510d9df11886" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-29T16:57:58Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/add-system.tsx", + "internal/site/src/components/navbar.tsx", + "internal/site/src/components/routes/settings/quiet-hours.tsx", +] +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:00.820647+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:25f5eeafad0168c585def440ef4f64e6ec3bc3566074be91ab771565c7c89bea" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2405/tests/capture.py b/tasks/henrygd__beszel-2405/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2405/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/henrygd__beszel-2405/tests/instruction.md b/tasks/henrygd__beszel-2405/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6f898417a539d9bf8ba35664f60f1e3bc0d91417 --- /dev/null +++ b/tasks/henrygd__beszel-2405/tests/instruction.md @@ -0,0 +1,25 @@ +# Issue + +**Title:** fix(ui): refresh interpolated translations on locale change + +## Description + +## 📃 Description + +Previously, translations weren't picked up everywhere when the language was changed; now it uses `useLingui()`, so it re-renders upon a language switch. + +## 📷 Screenshots + +
+ before +1 +
+
+ + after +2 +
+ +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3281055d95b3`. 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/henrygd__beszel-2405/tests/oracle.patch b/tasks/henrygd__beszel-2405/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e1327b48b02be7bff895dac032f3dffad5a3edc4 --- /dev/null +++ b/tasks/henrygd__beszel-2405/tests/oracle.patch @@ -0,0 +1,69 @@ +diff --git a/internal/site/src/components/add-system.tsx b/internal/site/src/components/add-system.tsx +index 9991ba25..e3a8e1b0 100644 +--- a/internal/site/src/components/add-system.tsx ++++ b/internal/site/src/components/add-system.tsx +@@ -1,5 +1,4 @@ +-import { t } from "@lingui/core/macro" +-import { Trans } from "@lingui/react/macro" ++import { Trans, useLingui } from "@lingui/react/macro" + import { useStore } from "@nanostores/react" + import { getPagePath } from "@nanostores/router" + import { ChevronDownIcon, ExternalLinkIcon } from "lucide-react" +@@ -65,6 +64,7 @@ let nextSystemToken: string | null = null + * @param {SystemRecord} [props.system] - Optional system record for editing an existing system. + */ + export const SystemDialog = ({ setOpen, system }: { setOpen: (open: boolean) => void; system?: SystemRecord }) => { ++ const { t } = useLingui() + const publicKey = useStore($publicKey) + const port = useRef(null) + const [hostValue, setHostValue] = useState(system?.host ?? "") +diff --git a/internal/site/src/components/navbar.tsx b/internal/site/src/components/navbar.tsx +index 28bf234c..79b50c31 100644 +--- a/internal/site/src/components/navbar.tsx ++++ b/internal/site/src/components/navbar.tsx +@@ -1,4 +1,4 @@ +-import { Trans } from "@lingui/react/macro" ++import { Trans, useLingui } from "@lingui/react/macro" + import { getPagePath } from "@nanostores/router" + import { + ContainerIcon, +@@ -42,6 +42,7 @@ const CommandPalette = lazy(() => import("./command-palette")) + const isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0 + + export default function Navbar() { ++ const { t } = useLingui() + const [addSystemDialogOpen, setAddSystemDialogOpen] = useState(false) + const [commandPaletteOpen, setCommandPaletteOpen] = useState(false) + +diff --git a/internal/site/src/components/routes/settings/quiet-hours.tsx b/internal/site/src/components/routes/settings/quiet-hours.tsx +index a23f9dee..8d45d501 100644 +--- a/internal/site/src/components/routes/settings/quiet-hours.tsx ++++ b/internal/site/src/components/routes/settings/quiet-hours.tsx +@@ -1,5 +1,4 @@ +-import { t } from "@lingui/core/macro" +-import { Trans } from "@lingui/react/macro" ++import { Trans, useLingui } from "@lingui/react/macro" + import { useStore } from "@nanostores/react" + import { + MoreHorizontalIcon, +@@ -42,9 +41,9 @@ import { $systems } from "@/lib/stores" + import { formatShortDate } from "@/lib/utils" + import type { QuietHoursRecord, SystemRecord } from "@/types" + +-const quietHoursTranslation = t`Quiet Hours` +- + export function QuietHours() { ++ const { t } = useLingui() ++ const quietHoursTranslation = t`Quiet Hours` + const [data, setData] = useState([]) + const [dialogOpen, setDialogOpen] = useState(false) + const [editingRecord, setEditingRecord] = useState(null) +@@ -293,6 +292,8 @@ function QuietHoursDialog({ + onClose: () => void + toast: ReturnType["toast"] + }) { ++ const { t } = useLingui() ++ const quietHoursTranslation = t`Quiet Hours` + const [selectedSystem, setSelectedSystem] = useState(editingRecord?.system || "") + const [isGlobal, setIsGlobal] = useState(!editingRecord?.system) + const [windowType, setWindowType] = useState<"one-time" | "daily">(editingRecord?.type || "one-time") diff --git a/tasks/henrygd__beszel-2405/tests/test.sh b/tasks/henrygd__beszel-2405/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..272ada35e7aa7dc2c2cde82ec4effdbaf8eae2c7 --- /dev/null +++ b/tasks/henrygd__beszel-2405/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 3281055d95b365964e67296c8935cdcbc4bfaec1 > "$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/henrygd__beszel-2405/tests/verifier.py b/tasks/henrygd__beszel-2405/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2405/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/henrygd__beszel-2406/environment/Dockerfile b/tasks/henrygd__beszel-2406/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..be6c4a0a0a9216bff54becc590824a3c5cac425c --- /dev/null +++ b/tasks/henrygd__beszel-2406/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 08707160528048b97556b984b2cff338580474dd 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 08707160528048b97556b984b2cff338580474dd \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 08707160528048b97556b984b2cff338580474dd \ + && 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/henrygd__beszel-2406/instruction.md b/tasks/henrygd__beszel-2406/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f02f362fc57c4f16027915b5e704cf0d086363de --- /dev/null +++ b/tasks/henrygd__beszel-2406/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** fix(ui): prevent scrollbar layout shifts + +## Description + +## 📃 Description + +The page can shift horizontally when its content starts or stops overflowing, and when a modal sheet locks background scrolling. +- Add scrollbar-gutter: stable to reserve space for the page scrollbar. +- Remove the extra margin-right applied during Radix scroll locking, since the gutter already preserves that space. +- Keep the override conditional on browser support for scrollbar-gutter. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `087071605280`. 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/henrygd__beszel-2406/solution/patch.diff b/tasks/henrygd__beszel-2406/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..56ae9cdfc33430ddec4552a3b29dbba08a5e1df1 --- /dev/null +++ b/tasks/henrygd__beszel-2406/solution/patch.diff @@ -0,0 +1,29 @@ +diff --git a/internal/site/src/index.css b/internal/site/src/index.css +index d3f34f09..974d2b6f 100644 +--- a/internal/site/src/index.css ++++ b/internal/site/src/index.css +@@ -141,6 +141,17 @@ + overflow-anchor: none; + } + ++ html { ++ scrollbar-gutter: stable; ++ } ++ ++ @supports (scrollbar-gutter: stable) { ++ /* Radix scroll lock adds this margin even though the viewport keeps its gutter. */ ++ html body[data-scroll-locked] { ++ margin-right: 0 !important; ++ } ++ } ++ + body { + @apply bg-background text-foreground; + font-variant-ligatures: no-contextual; +@@ -191,4 +202,4 @@ + + .recharts-yAxis { + @apply tabular-nums; +-} +\ No newline at end of file ++} diff --git a/tasks/henrygd__beszel-2406/solution/solve.sh b/tasks/henrygd__beszel-2406/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2406/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/henrygd__beszel-2406/task.toml b/tasks/henrygd__beszel-2406/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..799c2a06dbe1540d2024d60a1b6eb615ebdbf867 --- /dev/null +++ b/tasks/henrygd__beszel-2406/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2406" +description = "fix(ui): prevent scrollbar layout shifts" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "08707160528048b97556b984b2cff338580474dd" +reference = "https://github.com/henrygd/beszel/pull/2406" +source_access = "auto" +built_at = "2026-11-16T16:09:53.461425+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6cee89bb3e91d7b1b3266d15ba5af775e18164a1bab139362504bbea8d2dc093" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-24T23:25:57Z" +diff_format = "unified" +context_files = [ + "internal/site/src/index.css", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 13 +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:00.821100+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:22aa0f66154b84356609c67c1b6f43f9e071a5ccb228ba46ef82d9675af2807c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2406/tests/capture.py b/tasks/henrygd__beszel-2406/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2406/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/henrygd__beszel-2406/tests/instruction.md b/tasks/henrygd__beszel-2406/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f02f362fc57c4f16027915b5e704cf0d086363de --- /dev/null +++ b/tasks/henrygd__beszel-2406/tests/instruction.md @@ -0,0 +1,16 @@ +# Issue + +**Title:** fix(ui): prevent scrollbar layout shifts + +## Description + +## 📃 Description + +The page can shift horizontally when its content starts or stops overflowing, and when a modal sheet locks background scrolling. +- Add scrollbar-gutter: stable to reserve space for the page scrollbar. +- Remove the extra margin-right applied during Radix scroll locking, since the gutter already preserves that space. +- Keep the override conditional on browser support for scrollbar-gutter. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `087071605280`. 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/henrygd__beszel-2406/tests/oracle.patch b/tasks/henrygd__beszel-2406/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..56ae9cdfc33430ddec4552a3b29dbba08a5e1df1 --- /dev/null +++ b/tasks/henrygd__beszel-2406/tests/oracle.patch @@ -0,0 +1,29 @@ +diff --git a/internal/site/src/index.css b/internal/site/src/index.css +index d3f34f09..974d2b6f 100644 +--- a/internal/site/src/index.css ++++ b/internal/site/src/index.css +@@ -141,6 +141,17 @@ + overflow-anchor: none; + } + ++ html { ++ scrollbar-gutter: stable; ++ } ++ ++ @supports (scrollbar-gutter: stable) { ++ /* Radix scroll lock adds this margin even though the viewport keeps its gutter. */ ++ html body[data-scroll-locked] { ++ margin-right: 0 !important; ++ } ++ } ++ + body { + @apply bg-background text-foreground; + font-variant-ligatures: no-contextual; +@@ -191,4 +202,4 @@ + + .recharts-yAxis { + @apply tabular-nums; +-} +\ No newline at end of file ++} diff --git a/tasks/henrygd__beszel-2406/tests/test.sh b/tasks/henrygd__beszel-2406/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ea653e8cb0148e5e08779d36118ec7b6f2e971f0 --- /dev/null +++ b/tasks/henrygd__beszel-2406/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 08707160528048b97556b984b2cff338580474dd > "$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/henrygd__beszel-2406/tests/verifier.py b/tasks/henrygd__beszel-2406/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2406/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/henrygd__beszel-2407/environment/Dockerfile b/tasks/henrygd__beszel-2407/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6a5ffc4ffdf6811dce40ac9acdeffe9d1021819b --- /dev/null +++ b/tasks/henrygd__beszel-2407/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a99fe5e99725edf2a8ff582f5b21793fc88731f2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a99fe5e99725edf2a8ff582f5b21793fc88731f2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a99fe5e99725edf2a8ff582f5b21793fc88731f2 \ + && 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/henrygd__beszel-2407/instruction.md b/tasks/henrygd__beszel-2407/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..75c8e9313c376f58a4e0439d724ff2837064c03d --- /dev/null +++ b/tasks/henrygd__beszel-2407/instruction.md @@ -0,0 +1,57 @@ +# Issue + +**Title:** fix(agent): handle 32-bit wrap of disk I/O time counters + +## Description + +## 📃 Description + +On Linux, four millisecond counters in `/proc/diskstats` are 32-bit values. These are read time, write time, io time and weighted io time (fields 4, 8, 10 and 11). `diskstats_show` in [`block/genhd.c`](https://github.com/torvalds/linux/blob/fe2ec83746e501645709761605c2464a44fd2929/block/genhd.c#L1392-L1417) casts them to `unsigned int`, and [`iostats.rst`](https://github.com/torvalds/linux/blob/fe2ec83746e501645709761605c2464a44fd2929/Documentation/admin-guide/iostats.rst) lists them with that type. They wrap to zero after 2^32 ms. Weighted io time grows by the queue depth per millisecond. At an average depth of 10, it wraps after about 5 days. + +gopsutil parses the fields as `uint64`. `updateDiskIo` subtracts the previous value without a check, so the subtraction underflows after a wrap. One sample then reports about 3e16 % for the four time percentages. `r_await` and `w_await` become about 2^64 ms divided by the number of operations, for example 1.8e18 ms for 10 reads. In the hub, `records.go` averages that sample into the longer records and keeps it in `MaxDiskIoStats` as the maximum. The existing 50,000 MB/s check does not see it, because it only looks at the byte counters, and those do not wrap. + +The new `ioTimeDelta` helper adds 2^32 when a counter goes down and the previous value fits in 32 bits. A previous value above 2^32 cannot come from a 32-bit field. In that case a lower value is a reset, and the delta is 0. A device reset on Linux also resets the byte counters, so the existing byte check still skips that sample. + +Two other fixes were possible: + +- Subtract as `uint32` everywhere. This gives the correct delta after a wrap, as long as one interval adds less than 2^32 ms. After a counter reset it gives an arbitrary value below 2^32, which can still be about 7e6 % for a 60 s interval. +- Discard samples above a limit, like the byte check does. That loses a valid sample, and there is no clear limit for weighted io, which can be above 100 % by design. + +I did not see a wrap on a real host. The cause and the numbers come from the kernel source and from the test below. + +## 🪵 Changelog + +### 🔧 Fixed + +- Disk I/O time metrics no longer spike to about 3e16 % when a Linux diskstats time counter wraps at 2^32 ms. + +## Verification + +`TestUpdateDiskIoTimeCounterWrap` writes a diskstats file through `HOST_PROC` and calls `updateDiskIo` with a previous sample 60 s old. The `no wrap` case is a control. The `32-bit wrap` case puts all four time counters just below 2^32. The test file is Linux-only, because gopsutil reads diskstats only on Linux. I ran it on Debian 13.7 (Linux 6.12, arm64), built with `GOOS=linux GOARCH=arm64 go test -c -tags='testing no_ui' ./agent`. + +Before the change (`08707160`), shortened: + +``` +Error: Max difference between 2 and 3.074457344902431e+16 allowed is 0.01, but difference was -3.074457344902431e+16 +Messages: DiskIoStats[2] +Error: Max difference between 30 and 1.8446744069414584e+18 allowed is 0.01, but difference was -1.8446744069414584e+18 +Messages: DiskIoStats[3] +Error: Max difference between 5 and 3.074457344902431e+16 allowed is 0.01, but difference was -3.0744573449024308e+16 +Messages: DiskIoStats[5] +[...] +--- FAIL: TestUpdateDiskIoTimeCounterWrap (0.00s) + --- PASS: TestUpdateDiskIoTimeCounterWrap/no_wrap (0.00s) + --- FAIL: TestUpdateDiskIoTimeCounterWrap/32-bit_wrap (0.00s) +``` + +All six values fail in the wrap case, for `fs.DiskIoStats` and for the system stats. The control passes. After the change, both cases pass. + +- Full `./agent` test binary on the Debian host, two runs each: before the change only the new test fails, after it the package passes. +- `go test -tags='testing no_ui' ./...` on macOS 26 arm64: the same result before and after the change. 20 packages pass. `./agent` fails in 4 GPU tests (`TestCollectorStartHelpers`, `TestNewGPUManagerPriority*`) on both `main` and this branch. They wait a fixed 50 or 150 ms for a script that the test just wrote. On this Mac the first run of such a script takes 145 to 269 ms. On Linux they pass. +- The `internal/hub` packages need `internal/site/dist` to build. I added a placeholder `index.html` locally. It is not part of this change. +- `go vet -tags='testing no_ui' ./agent` for linux/arm64 and darwin/arm64, and `gofmt -l` on the changed files: clean. +- I changed each of the four `ioTimeDelta` calls back to plain subtraction, one at a time. The test fails for each change. It also fails when I disable the wrap branch in `ioTimeDelta`. The `return 0` branch for 64-bit counters has no test. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a99fe5e99725`. 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/henrygd__beszel-2407/solution/patch.diff b/tasks/henrygd__beszel-2407/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d87dfd32eba9474e1ff570ec36091a878b20909f --- /dev/null +++ b/tasks/henrygd__beszel-2407/solution/patch.diff @@ -0,0 +1,181 @@ +diff --git a/agent/disk.go b/agent/disk.go +index 9e89f9cd..13bb1b1c 100644 +--- a/agent/disk.go ++++ b/agent/disk.go +@@ -3,6 +3,7 @@ package agent + import ( + "context" + "log/slog" ++ "math" + "os" + "path/filepath" + "runtime" +@@ -686,25 +687,27 @@ func (a *Agent) updateDiskIo(cacheTimeMs uint16, systemStats *system.Stats) { + // This is the total number of milliseconds spent by all reads (as + // measured from __make_request() to end_that_request_last()). + // https://www.kernel.org/doc/Documentation/iostats.txt (fields 4, 8) +- diskReadTime := utils.TwoDecimals(float64(d.ReadTime-prev.readTime) / float64(msElapsed) * 100) +- diskWriteTime := utils.TwoDecimals(float64(d.WriteTime-prev.writeTime) / float64(msElapsed) * 100) ++ deltaReadTime := ioTimeDelta(d.ReadTime, prev.readTime) ++ deltaWriteTime := ioTimeDelta(d.WriteTime, prev.writeTime) ++ diskReadTime := utils.TwoDecimals(float64(deltaReadTime) / float64(msElapsed) * 100) ++ diskWriteTime := utils.TwoDecimals(float64(deltaWriteTime) / float64(msElapsed) * 100) + + // I/O utilization %: fraction of wall time the device had any I/O in progress (0-100). +- diskIoUtilPct := utils.TwoDecimals(float64(d.IoTime-prev.ioTime) / float64(msElapsed) * 100) ++ diskIoUtilPct := utils.TwoDecimals(float64(ioTimeDelta(d.IoTime, prev.ioTime)) / float64(msElapsed) * 100) + + // Weighted I/O: queue-depth weighted I/O time, normalized to interval (can exceed 100%). + // Linux kernel field 11: incremented by iops_in_progress × ms_since_last_update. + // Used to display queue depth. Multipled by 100 to increase accuracy of digit truncation (divided by 100 in UI). +- diskWeightedIO := utils.TwoDecimals(float64(d.WeightedIO-prev.weightedIO) / float64(msElapsed) * 100) ++ diskWeightedIO := utils.TwoDecimals(float64(ioTimeDelta(d.WeightedIO, prev.weightedIO)) / float64(msElapsed) * 100) + + // r_await / w_await: average time per read/write operation in milliseconds. + // Equivalent to r_await and w_await in iostat. + var rAwait, wAwait float64 + if deltaReadCount := d.ReadCount - prev.readCount; deltaReadCount > 0 { +- rAwait = utils.TwoDecimals(float64(d.ReadTime-prev.readTime) / float64(deltaReadCount)) ++ rAwait = utils.TwoDecimals(float64(deltaReadTime) / float64(deltaReadCount)) + } + if deltaWriteCount := d.WriteCount - prev.writeCount; deltaWriteCount > 0 { +- wAwait = utils.TwoDecimals(float64(d.WriteTime-prev.writeTime) / float64(deltaWriteCount)) ++ wAwait = utils.TwoDecimals(float64(deltaWriteTime) / float64(deltaWriteCount)) + } + + // Update global fsStats baseline for cross-interval correctness +@@ -740,6 +743,21 @@ func (a *Agent) updateDiskIo(cacheTimeMs uint16, systemStats *system.Stats) { + } + } + ++// ioTimeDelta returns the increase of a cumulative millisecond counter from ++// the disk I/O stats. Linux prints these fields of /proc/diskstats as 32-bit ++// unsigned ints, so they wrap to zero at 2^32. A busy disk reaches that in ++// days for the weighted I/O time. Other platforms report 64-bit counters, ++// so a lower value there is a reset. ++func ioTimeDelta(current, previous uint64) uint64 { ++ if current >= previous { ++ return current - previous ++ } ++ if runtime.GOOS == "linux" && previous <= math.MaxUint32 { ++ return current + (math.MaxUint32 + 1 - previous) ++ } ++ return 0 ++} ++ + // getRootMountPoint returns the appropriate root mount point for the system. + // On Windows it returns the system drive (e.g. "C:"). + // For immutable systems like Fedora Silverblue, it returns /sysroot instead of / +diff --git a/agent/disk_io_linux_test.go b/agent/disk_io_linux_test.go +new file mode 100644 +index 00000000..90e462a0 +--- /dev/null ++++ b/agent/disk_io_linux_test.go +@@ -0,0 +1,75 @@ ++//go:build linux ++ ++package agent ++ ++import ( ++ "fmt" ++ "os" ++ "path/filepath" ++ "testing" ++ "time" ++ ++ "github.com/henrygd/beszel/internal/entities/system" ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/require" ++) ++ ++// Linux prints four millisecond fields of /proc/diskstats as 32-bit unsigned ints: ++// read time, write time, io time and weighted io time. They wrap to zero at 2^32. ++func TestUpdateDiskIoTimeCounterWrap(t *testing.T) { ++ const wrap = uint64(1) << 32 ++ ++ tests := []struct { ++ name string ++ base uint64 // added to every previous time counter ++ }{ ++ {"no wrap", 0}, ++ {"32-bit wrap", wrap - 1000}, ++ } ++ ++ for _, tt := range tests { ++ t.Run(tt.name, func(t *testing.T) { ++ // Deltas over 60s: read 300ms / 10 ops, write 400ms / 20 ops, ++ // io time 1200ms, weighted io 3000ms. ++ prev := prevDisk{ ++ readBytes: 20000 * 512, ++ writeBytes: 10000 * 512, ++ readTime: tt.base + 900, ++ writeTime: tt.base + 700, ++ ioTime: tt.base + 400, ++ weightedIO: tt.base, ++ readCount: 1000, ++ writeCount: 500, ++ at: time.Now().Add(-60 * time.Second), ++ } ++ cur := func(v uint64) uint64 { return v % wrap } ++ line := fmt.Sprintf(" 8 0 sda %d 0 %d %d %d 0 %d %d 0 %d %d\n", ++ 1010, 21200, cur(prev.readTime+300), ++ 520, 10400, cur(prev.writeTime+400), ++ cur(prev.ioTime+1200), cur(prev.weightedIO+3000)) ++ ++ dir := t.TempDir() ++ require.NoError(t, os.WriteFile(filepath.Join(dir, "diskstats"), []byte(line), 0o644)) ++ t.Setenv("HOST_PROC", dir) ++ t.Setenv("HOST_SYS", dir) ++ t.Setenv("HOST_DEV", dir) ++ t.Setenv("HOST_RUN", dir) ++ ++ fs := &system.FsStats{Root: true} ++ a := &Agent{ ++ fsNames: []string{"sda"}, ++ fsStats: map[string]*system.FsStats{"sda": fs}, ++ diskPrev: map[uint16]map[string]prevDisk{60000: {"sda": prev}}, ++ } ++ var stats system.Stats ++ a.updateDiskIo(60000, &stats) ++ ++ // Same order as DiskIoStats in system.FsStats. ++ want := [6]float64{0.5, 0.67, 2, 30, 20, 5} ++ for i := range want { ++ assert.InDelta(t, want[i], fs.DiskIoStats[i], 0.01, "DiskIoStats[%d]", i) ++ assert.InDelta(t, want[i], stats.DiskIoStats[i], 0.01, "system DiskIoStats[%d]", i) ++ } ++ }) ++ } ++} +diff --git a/agent/disk_test.go b/agent/disk_test.go +index 9e8b3d2b..70fa2083 100644 +--- a/agent/disk_test.go ++++ b/agent/disk_test.go +@@ -3,7 +3,9 @@ + package agent + + import ( ++ "math" + "os" ++ "runtime" + "strings" + "testing" + "time" +@@ -1041,3 +1043,17 @@ func TestInitializeDiskIoStatsResetsTrackedDevices(t *testing.T) { + assert.Equal(t, uint64(50), agent.fsStats["sdb"].TotalRead) + assert.Equal(t, uint64(60), agent.fsStats["sdb"].TotalWrite) + } ++ ++func TestIoTimeDelta(t *testing.T) { ++ assert.Equal(t, uint64(300), ioTimeDelta(1200, 900)) ++ ++ // A lower value is a 32-bit wrap only on Linux. Other platforms ++ // report 64-bit counters, so there it is a reset. ++ var want uint64 ++ if runtime.GOOS == "linux" { ++ want = 1200 ++ } ++ assert.Equal(t, want, ioTimeDelta(200, math.MaxUint32+1-1000)) ++ ++ assert.Equal(t, uint64(0), ioTimeDelta(200, math.MaxUint32+1000)) ++} diff --git a/tasks/henrygd__beszel-2407/solution/solve.sh b/tasks/henrygd__beszel-2407/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2407/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/henrygd__beszel-2407/task.toml b/tasks/henrygd__beszel-2407/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9336055eb24a60b3d1b572b9915aadd4d32c6934 --- /dev/null +++ b/tasks/henrygd__beszel-2407/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2407" +description = "fix(agent): handle 32-bit wrap of disk I/O time counters" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "a99fe5e99725edf2a8ff582f5b21793fc88731f2" +reference = "https://github.com/henrygd/beszel/pull/2407" +source_access = "auto" +built_at = "2026-11-16T16:09:53.485117+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b945e2e18f8447b8f31534d60b578c9e4d5b316046df4c4fde4b94f119eb4f33" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-24T21:39:54Z" +diff_format = "unified" +context_files = [ + "agent/disk.go", + "agent/disk_io_linux_test.go", + "agent/disk_test.go", +] +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:00.821543+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:81e4be62628c78838b45815d054bb0d0c5800b6952389c0051eff2fbe2b5c7d5" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2407/tests/capture.py b/tasks/henrygd__beszel-2407/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2407/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/henrygd__beszel-2407/tests/instruction.md b/tasks/henrygd__beszel-2407/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..75c8e9313c376f58a4e0439d724ff2837064c03d --- /dev/null +++ b/tasks/henrygd__beszel-2407/tests/instruction.md @@ -0,0 +1,57 @@ +# Issue + +**Title:** fix(agent): handle 32-bit wrap of disk I/O time counters + +## Description + +## 📃 Description + +On Linux, four millisecond counters in `/proc/diskstats` are 32-bit values. These are read time, write time, io time and weighted io time (fields 4, 8, 10 and 11). `diskstats_show` in [`block/genhd.c`](https://github.com/torvalds/linux/blob/fe2ec83746e501645709761605c2464a44fd2929/block/genhd.c#L1392-L1417) casts them to `unsigned int`, and [`iostats.rst`](https://github.com/torvalds/linux/blob/fe2ec83746e501645709761605c2464a44fd2929/Documentation/admin-guide/iostats.rst) lists them with that type. They wrap to zero after 2^32 ms. Weighted io time grows by the queue depth per millisecond. At an average depth of 10, it wraps after about 5 days. + +gopsutil parses the fields as `uint64`. `updateDiskIo` subtracts the previous value without a check, so the subtraction underflows after a wrap. One sample then reports about 3e16 % for the four time percentages. `r_await` and `w_await` become about 2^64 ms divided by the number of operations, for example 1.8e18 ms for 10 reads. In the hub, `records.go` averages that sample into the longer records and keeps it in `MaxDiskIoStats` as the maximum. The existing 50,000 MB/s check does not see it, because it only looks at the byte counters, and those do not wrap. + +The new `ioTimeDelta` helper adds 2^32 when a counter goes down and the previous value fits in 32 bits. A previous value above 2^32 cannot come from a 32-bit field. In that case a lower value is a reset, and the delta is 0. A device reset on Linux also resets the byte counters, so the existing byte check still skips that sample. + +Two other fixes were possible: + +- Subtract as `uint32` everywhere. This gives the correct delta after a wrap, as long as one interval adds less than 2^32 ms. After a counter reset it gives an arbitrary value below 2^32, which can still be about 7e6 % for a 60 s interval. +- Discard samples above a limit, like the byte check does. That loses a valid sample, and there is no clear limit for weighted io, which can be above 100 % by design. + +I did not see a wrap on a real host. The cause and the numbers come from the kernel source and from the test below. + +## 🪵 Changelog + +### 🔧 Fixed + +- Disk I/O time metrics no longer spike to about 3e16 % when a Linux diskstats time counter wraps at 2^32 ms. + +## Verification + +`TestUpdateDiskIoTimeCounterWrap` writes a diskstats file through `HOST_PROC` and calls `updateDiskIo` with a previous sample 60 s old. The `no wrap` case is a control. The `32-bit wrap` case puts all four time counters just below 2^32. The test file is Linux-only, because gopsutil reads diskstats only on Linux. I ran it on Debian 13.7 (Linux 6.12, arm64), built with `GOOS=linux GOARCH=arm64 go test -c -tags='testing no_ui' ./agent`. + +Before the change (`08707160`), shortened: + +``` +Error: Max difference between 2 and 3.074457344902431e+16 allowed is 0.01, but difference was -3.074457344902431e+16 +Messages: DiskIoStats[2] +Error: Max difference between 30 and 1.8446744069414584e+18 allowed is 0.01, but difference was -1.8446744069414584e+18 +Messages: DiskIoStats[3] +Error: Max difference between 5 and 3.074457344902431e+16 allowed is 0.01, but difference was -3.0744573449024308e+16 +Messages: DiskIoStats[5] +[...] +--- FAIL: TestUpdateDiskIoTimeCounterWrap (0.00s) + --- PASS: TestUpdateDiskIoTimeCounterWrap/no_wrap (0.00s) + --- FAIL: TestUpdateDiskIoTimeCounterWrap/32-bit_wrap (0.00s) +``` + +All six values fail in the wrap case, for `fs.DiskIoStats` and for the system stats. The control passes. After the change, both cases pass. + +- Full `./agent` test binary on the Debian host, two runs each: before the change only the new test fails, after it the package passes. +- `go test -tags='testing no_ui' ./...` on macOS 26 arm64: the same result before and after the change. 20 packages pass. `./agent` fails in 4 GPU tests (`TestCollectorStartHelpers`, `TestNewGPUManagerPriority*`) on both `main` and this branch. They wait a fixed 50 or 150 ms for a script that the test just wrote. On this Mac the first run of such a script takes 145 to 269 ms. On Linux they pass. +- The `internal/hub` packages need `internal/site/dist` to build. I added a placeholder `index.html` locally. It is not part of this change. +- `go vet -tags='testing no_ui' ./agent` for linux/arm64 and darwin/arm64, and `gofmt -l` on the changed files: clean. +- I changed each of the four `ioTimeDelta` calls back to plain subtraction, one at a time. The test fails for each change. It also fails when I disable the wrap branch in `ioTimeDelta`. The `return 0` branch for 64-bit counters has no test. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a99fe5e99725`. 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/henrygd__beszel-2407/tests/oracle.patch b/tasks/henrygd__beszel-2407/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d87dfd32eba9474e1ff570ec36091a878b20909f --- /dev/null +++ b/tasks/henrygd__beszel-2407/tests/oracle.patch @@ -0,0 +1,181 @@ +diff --git a/agent/disk.go b/agent/disk.go +index 9e89f9cd..13bb1b1c 100644 +--- a/agent/disk.go ++++ b/agent/disk.go +@@ -3,6 +3,7 @@ package agent + import ( + "context" + "log/slog" ++ "math" + "os" + "path/filepath" + "runtime" +@@ -686,25 +687,27 @@ func (a *Agent) updateDiskIo(cacheTimeMs uint16, systemStats *system.Stats) { + // This is the total number of milliseconds spent by all reads (as + // measured from __make_request() to end_that_request_last()). + // https://www.kernel.org/doc/Documentation/iostats.txt (fields 4, 8) +- diskReadTime := utils.TwoDecimals(float64(d.ReadTime-prev.readTime) / float64(msElapsed) * 100) +- diskWriteTime := utils.TwoDecimals(float64(d.WriteTime-prev.writeTime) / float64(msElapsed) * 100) ++ deltaReadTime := ioTimeDelta(d.ReadTime, prev.readTime) ++ deltaWriteTime := ioTimeDelta(d.WriteTime, prev.writeTime) ++ diskReadTime := utils.TwoDecimals(float64(deltaReadTime) / float64(msElapsed) * 100) ++ diskWriteTime := utils.TwoDecimals(float64(deltaWriteTime) / float64(msElapsed) * 100) + + // I/O utilization %: fraction of wall time the device had any I/O in progress (0-100). +- diskIoUtilPct := utils.TwoDecimals(float64(d.IoTime-prev.ioTime) / float64(msElapsed) * 100) ++ diskIoUtilPct := utils.TwoDecimals(float64(ioTimeDelta(d.IoTime, prev.ioTime)) / float64(msElapsed) * 100) + + // Weighted I/O: queue-depth weighted I/O time, normalized to interval (can exceed 100%). + // Linux kernel field 11: incremented by iops_in_progress × ms_since_last_update. + // Used to display queue depth. Multipled by 100 to increase accuracy of digit truncation (divided by 100 in UI). +- diskWeightedIO := utils.TwoDecimals(float64(d.WeightedIO-prev.weightedIO) / float64(msElapsed) * 100) ++ diskWeightedIO := utils.TwoDecimals(float64(ioTimeDelta(d.WeightedIO, prev.weightedIO)) / float64(msElapsed) * 100) + + // r_await / w_await: average time per read/write operation in milliseconds. + // Equivalent to r_await and w_await in iostat. + var rAwait, wAwait float64 + if deltaReadCount := d.ReadCount - prev.readCount; deltaReadCount > 0 { +- rAwait = utils.TwoDecimals(float64(d.ReadTime-prev.readTime) / float64(deltaReadCount)) ++ rAwait = utils.TwoDecimals(float64(deltaReadTime) / float64(deltaReadCount)) + } + if deltaWriteCount := d.WriteCount - prev.writeCount; deltaWriteCount > 0 { +- wAwait = utils.TwoDecimals(float64(d.WriteTime-prev.writeTime) / float64(deltaWriteCount)) ++ wAwait = utils.TwoDecimals(float64(deltaWriteTime) / float64(deltaWriteCount)) + } + + // Update global fsStats baseline for cross-interval correctness +@@ -740,6 +743,21 @@ func (a *Agent) updateDiskIo(cacheTimeMs uint16, systemStats *system.Stats) { + } + } + ++// ioTimeDelta returns the increase of a cumulative millisecond counter from ++// the disk I/O stats. Linux prints these fields of /proc/diskstats as 32-bit ++// unsigned ints, so they wrap to zero at 2^32. A busy disk reaches that in ++// days for the weighted I/O time. Other platforms report 64-bit counters, ++// so a lower value there is a reset. ++func ioTimeDelta(current, previous uint64) uint64 { ++ if current >= previous { ++ return current - previous ++ } ++ if runtime.GOOS == "linux" && previous <= math.MaxUint32 { ++ return current + (math.MaxUint32 + 1 - previous) ++ } ++ return 0 ++} ++ + // getRootMountPoint returns the appropriate root mount point for the system. + // On Windows it returns the system drive (e.g. "C:"). + // For immutable systems like Fedora Silverblue, it returns /sysroot instead of / +diff --git a/agent/disk_io_linux_test.go b/agent/disk_io_linux_test.go +new file mode 100644 +index 00000000..90e462a0 +--- /dev/null ++++ b/agent/disk_io_linux_test.go +@@ -0,0 +1,75 @@ ++//go:build linux ++ ++package agent ++ ++import ( ++ "fmt" ++ "os" ++ "path/filepath" ++ "testing" ++ "time" ++ ++ "github.com/henrygd/beszel/internal/entities/system" ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/require" ++) ++ ++// Linux prints four millisecond fields of /proc/diskstats as 32-bit unsigned ints: ++// read time, write time, io time and weighted io time. They wrap to zero at 2^32. ++func TestUpdateDiskIoTimeCounterWrap(t *testing.T) { ++ const wrap = uint64(1) << 32 ++ ++ tests := []struct { ++ name string ++ base uint64 // added to every previous time counter ++ }{ ++ {"no wrap", 0}, ++ {"32-bit wrap", wrap - 1000}, ++ } ++ ++ for _, tt := range tests { ++ t.Run(tt.name, func(t *testing.T) { ++ // Deltas over 60s: read 300ms / 10 ops, write 400ms / 20 ops, ++ // io time 1200ms, weighted io 3000ms. ++ prev := prevDisk{ ++ readBytes: 20000 * 512, ++ writeBytes: 10000 * 512, ++ readTime: tt.base + 900, ++ writeTime: tt.base + 700, ++ ioTime: tt.base + 400, ++ weightedIO: tt.base, ++ readCount: 1000, ++ writeCount: 500, ++ at: time.Now().Add(-60 * time.Second), ++ } ++ cur := func(v uint64) uint64 { return v % wrap } ++ line := fmt.Sprintf(" 8 0 sda %d 0 %d %d %d 0 %d %d 0 %d %d\n", ++ 1010, 21200, cur(prev.readTime+300), ++ 520, 10400, cur(prev.writeTime+400), ++ cur(prev.ioTime+1200), cur(prev.weightedIO+3000)) ++ ++ dir := t.TempDir() ++ require.NoError(t, os.WriteFile(filepath.Join(dir, "diskstats"), []byte(line), 0o644)) ++ t.Setenv("HOST_PROC", dir) ++ t.Setenv("HOST_SYS", dir) ++ t.Setenv("HOST_DEV", dir) ++ t.Setenv("HOST_RUN", dir) ++ ++ fs := &system.FsStats{Root: true} ++ a := &Agent{ ++ fsNames: []string{"sda"}, ++ fsStats: map[string]*system.FsStats{"sda": fs}, ++ diskPrev: map[uint16]map[string]prevDisk{60000: {"sda": prev}}, ++ } ++ var stats system.Stats ++ a.updateDiskIo(60000, &stats) ++ ++ // Same order as DiskIoStats in system.FsStats. ++ want := [6]float64{0.5, 0.67, 2, 30, 20, 5} ++ for i := range want { ++ assert.InDelta(t, want[i], fs.DiskIoStats[i], 0.01, "DiskIoStats[%d]", i) ++ assert.InDelta(t, want[i], stats.DiskIoStats[i], 0.01, "system DiskIoStats[%d]", i) ++ } ++ }) ++ } ++} +diff --git a/agent/disk_test.go b/agent/disk_test.go +index 9e8b3d2b..70fa2083 100644 +--- a/agent/disk_test.go ++++ b/agent/disk_test.go +@@ -3,7 +3,9 @@ + package agent + + import ( ++ "math" + "os" ++ "runtime" + "strings" + "testing" + "time" +@@ -1041,3 +1043,17 @@ func TestInitializeDiskIoStatsResetsTrackedDevices(t *testing.T) { + assert.Equal(t, uint64(50), agent.fsStats["sdb"].TotalRead) + assert.Equal(t, uint64(60), agent.fsStats["sdb"].TotalWrite) + } ++ ++func TestIoTimeDelta(t *testing.T) { ++ assert.Equal(t, uint64(300), ioTimeDelta(1200, 900)) ++ ++ // A lower value is a 32-bit wrap only on Linux. Other platforms ++ // report 64-bit counters, so there it is a reset. ++ var want uint64 ++ if runtime.GOOS == "linux" { ++ want = 1200 ++ } ++ assert.Equal(t, want, ioTimeDelta(200, math.MaxUint32+1-1000)) ++ ++ assert.Equal(t, uint64(0), ioTimeDelta(200, math.MaxUint32+1000)) ++} diff --git a/tasks/henrygd__beszel-2407/tests/test.sh b/tasks/henrygd__beszel-2407/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3bf873bce0ed76630d9a2cefe967cec0a05c1adc --- /dev/null +++ b/tasks/henrygd__beszel-2407/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 a99fe5e99725edf2a8ff582f5b21793fc88731f2 > "$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/henrygd__beszel-2407/tests/verifier.py b/tasks/henrygd__beszel-2407/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2407/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/henrygd__beszel-2410/environment/Dockerfile b/tasks/henrygd__beszel-2410/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6a5ffc4ffdf6811dce40ac9acdeffe9d1021819b --- /dev/null +++ b/tasks/henrygd__beszel-2410/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a99fe5e99725edf2a8ff582f5b21793fc88731f2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a99fe5e99725edf2a8ff582f5b21793fc88731f2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a99fe5e99725edf2a8ff582f5b21793fc88731f2 \ + && 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/henrygd__beszel-2410/instruction.md b/tasks/henrygd__beszel-2410/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..77773f3db92e70398281bc264773fe1fa4b049c2 --- /dev/null +++ b/tasks/henrygd__beszel-2410/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** fix(hub): restart beszel-hub.service after update + +## Description + +## 📃 Description + +. + +`restartService()` only checked for a unit called `beszel.service`, but `install-hub.sh` installs the unit as `beszel-hub.service`. On a standard install the check never matched, so `beszel update` replaced the binary and then printed "Service restart not attempted", leaving the old version running. With `beszel-hub-update.timer` enabled the hub would keep running an outdated binary indefinitely. + +This tries the name the installer uses first and keeps the old one as a fallback for hand written units. The OpenRC branch got the same treatment. The duplicated result reporting moved into a small helper so both branches stay readable. + +The agent already does this correctly, `agent/update.go` checks `beszel-agent.service`, which matches its installer. + +Still not handled, and left out on purpose to keep this small: FreeBSD, where `install-hub.sh` creates `/usr/local/etc/rc.d/beszel-hub` but `restartService()` has no rc.d branch at all. Happy to add that too if you want it in the same PR. + +Checked with `gofmt -l`, `go build ./internal/hub/` and `go vet ./internal/hub/`, all clean. `go test ./internal/hub/` does not run here because `internal/site/embed.go` needs a built `dist`, which is unrelated to this change. + +## 🪵 Changelog + +### 🔧 Fixed + +- Hub now restarts after `beszel update` on systemd installs, where the unit is named `beszel-hub.service` +- Same fallback for OpenRC, trying `beszel-hub` before `beszel` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a99fe5e99725`. 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/henrygd__beszel-2410/solution/patch.diff b/tasks/henrygd__beszel-2410/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b31cb0ba5b662773982144b93b8f04f5a0d051e0 --- /dev/null +++ b/tasks/henrygd__beszel-2410/solution/patch.diff @@ -0,0 +1,62 @@ +diff --git a/internal/hub/update.go b/internal/hub/update.go +index 4ae990ef..2ba10601 100644 +--- a/internal/hub/update.go ++++ b/internal/hub/update.go +@@ -58,36 +58,38 @@ func Update(cmd *cobra.Command, _ []string) { + func restartService() { + // Check if we're running as a service by looking for systemd + if _, err := exec.LookPath("systemctl"); err == nil { +- // Check if beszel service exists and is active +- cmd := exec.Command("systemctl", "is-active", "beszel.service") +- if err := cmd.Run(); err == nil { +- ghupdate.ColorPrint(ghupdate.ColorYellow, "Restarting beszel service...") +- restartCmd := exec.Command("systemctl", "restart", "beszel.service") +- if err := restartCmd.Run(); err != nil { +- ghupdate.ColorPrintf(ghupdate.ColorYellow, "Warning: Failed to restart service: %v\n", err) +- ghupdate.ColorPrint(ghupdate.ColorYellow, "Please restart the service manually: sudo systemctl restart beszel") +- } else { +- ghupdate.ColorPrint(ghupdate.ColorGreen, "Service restarted successfully") ++ // install-hub.sh names the unit beszel-hub.service. beszel.service is ++ // kept as a fallback for hand written units. ++ for _, unit := range []string{"beszel-hub.service", "beszel.service"} { ++ if err := exec.Command("systemctl", "is-active", unit).Run(); err != nil { ++ continue + } ++ reportRestart(exec.Command("systemctl", "restart", unit), "sudo systemctl restart "+unit) + return + } + } + + // Check for OpenRC (Alpine Linux) + if _, err := exec.LookPath("rc-service"); err == nil { +- cmd := exec.Command("rc-service", "beszel", "status") +- if err := cmd.Run(); err == nil { +- ghupdate.ColorPrint(ghupdate.ColorYellow, "Restarting beszel service...") +- restartCmd := exec.Command("rc-service", "beszel", "restart") +- if err := restartCmd.Run(); err != nil { +- ghupdate.ColorPrintf(ghupdate.ColorYellow, "Warning: Failed to restart service: %v\n", err) +- ghupdate.ColorPrint(ghupdate.ColorYellow, "Please restart the service manually: sudo rc-service beszel restart") +- } else { +- ghupdate.ColorPrint(ghupdate.ColorGreen, "Service restarted successfully") ++ for _, service := range []string{"beszel-hub", "beszel"} { ++ if err := exec.Command("rc-service", service, "status").Run(); err != nil { ++ continue + } ++ reportRestart(exec.Command("rc-service", service, "restart"), "sudo rc-service "+service+" restart") + return + } + } + + ghupdate.ColorPrint(ghupdate.ColorYellow, "Service restart not attempted. If running as a service, restart manually.") + } ++ ++// reportRestart runs the restart command and prints the result. ++func reportRestart(cmd *exec.Cmd, manualCommand string) { ++ ghupdate.ColorPrint(ghupdate.ColorYellow, "Restarting beszel service...") ++ if err := cmd.Run(); err != nil { ++ ghupdate.ColorPrintf(ghupdate.ColorYellow, "Warning: Failed to restart service: %v\n", err) ++ ghupdate.ColorPrint(ghupdate.ColorYellow, "Please restart the service manually: "+manualCommand) ++ } else { ++ ghupdate.ColorPrint(ghupdate.ColorGreen, "Service restarted successfully") ++ } ++} diff --git a/tasks/henrygd__beszel-2410/solution/solve.sh b/tasks/henrygd__beszel-2410/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2410/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/henrygd__beszel-2410/task.toml b/tasks/henrygd__beszel-2410/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bfa05f73ac52fde8f1838dbd6ed5516a4037a920 --- /dev/null +++ b/tasks/henrygd__beszel-2410/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2410" +description = "fix(hub): restart beszel-hub.service after update" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "a99fe5e99725edf2a8ff582f5b21793fc88731f2" +reference = "https://github.com/henrygd/beszel/pull/2410" +source_access = "auto" +built_at = "2026-11-16T16:09:53.412443+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e43b1645550151724fe3b85e0c85011867c12e82fea2eb91cda5801938720f27" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-24T14:00:19Z" +diff_format = "unified" +context_files = [ + "internal/hub/update.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 40 +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:00.821998+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:81e4be62628c78838b45815d054bb0d0c5800b6952389c0051eff2fbe2b5c7d5" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2410/tests/capture.py b/tasks/henrygd__beszel-2410/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2410/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/henrygd__beszel-2410/tests/instruction.md b/tasks/henrygd__beszel-2410/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..77773f3db92e70398281bc264773fe1fa4b049c2 --- /dev/null +++ b/tasks/henrygd__beszel-2410/tests/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** fix(hub): restart beszel-hub.service after update + +## Description + +## 📃 Description + +. + +`restartService()` only checked for a unit called `beszel.service`, but `install-hub.sh` installs the unit as `beszel-hub.service`. On a standard install the check never matched, so `beszel update` replaced the binary and then printed "Service restart not attempted", leaving the old version running. With `beszel-hub-update.timer` enabled the hub would keep running an outdated binary indefinitely. + +This tries the name the installer uses first and keeps the old one as a fallback for hand written units. The OpenRC branch got the same treatment. The duplicated result reporting moved into a small helper so both branches stay readable. + +The agent already does this correctly, `agent/update.go` checks `beszel-agent.service`, which matches its installer. + +Still not handled, and left out on purpose to keep this small: FreeBSD, where `install-hub.sh` creates `/usr/local/etc/rc.d/beszel-hub` but `restartService()` has no rc.d branch at all. Happy to add that too if you want it in the same PR. + +Checked with `gofmt -l`, `go build ./internal/hub/` and `go vet ./internal/hub/`, all clean. `go test ./internal/hub/` does not run here because `internal/site/embed.go` needs a built `dist`, which is unrelated to this change. + +## 🪵 Changelog + +### 🔧 Fixed + +- Hub now restarts after `beszel update` on systemd installs, where the unit is named `beszel-hub.service` +- Same fallback for OpenRC, trying `beszel-hub` before `beszel` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a99fe5e99725`. 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/henrygd__beszel-2410/tests/oracle.patch b/tasks/henrygd__beszel-2410/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b31cb0ba5b662773982144b93b8f04f5a0d051e0 --- /dev/null +++ b/tasks/henrygd__beszel-2410/tests/oracle.patch @@ -0,0 +1,62 @@ +diff --git a/internal/hub/update.go b/internal/hub/update.go +index 4ae990ef..2ba10601 100644 +--- a/internal/hub/update.go ++++ b/internal/hub/update.go +@@ -58,36 +58,38 @@ func Update(cmd *cobra.Command, _ []string) { + func restartService() { + // Check if we're running as a service by looking for systemd + if _, err := exec.LookPath("systemctl"); err == nil { +- // Check if beszel service exists and is active +- cmd := exec.Command("systemctl", "is-active", "beszel.service") +- if err := cmd.Run(); err == nil { +- ghupdate.ColorPrint(ghupdate.ColorYellow, "Restarting beszel service...") +- restartCmd := exec.Command("systemctl", "restart", "beszel.service") +- if err := restartCmd.Run(); err != nil { +- ghupdate.ColorPrintf(ghupdate.ColorYellow, "Warning: Failed to restart service: %v\n", err) +- ghupdate.ColorPrint(ghupdate.ColorYellow, "Please restart the service manually: sudo systemctl restart beszel") +- } else { +- ghupdate.ColorPrint(ghupdate.ColorGreen, "Service restarted successfully") ++ // install-hub.sh names the unit beszel-hub.service. beszel.service is ++ // kept as a fallback for hand written units. ++ for _, unit := range []string{"beszel-hub.service", "beszel.service"} { ++ if err := exec.Command("systemctl", "is-active", unit).Run(); err != nil { ++ continue + } ++ reportRestart(exec.Command("systemctl", "restart", unit), "sudo systemctl restart "+unit) + return + } + } + + // Check for OpenRC (Alpine Linux) + if _, err := exec.LookPath("rc-service"); err == nil { +- cmd := exec.Command("rc-service", "beszel", "status") +- if err := cmd.Run(); err == nil { +- ghupdate.ColorPrint(ghupdate.ColorYellow, "Restarting beszel service...") +- restartCmd := exec.Command("rc-service", "beszel", "restart") +- if err := restartCmd.Run(); err != nil { +- ghupdate.ColorPrintf(ghupdate.ColorYellow, "Warning: Failed to restart service: %v\n", err) +- ghupdate.ColorPrint(ghupdate.ColorYellow, "Please restart the service manually: sudo rc-service beszel restart") +- } else { +- ghupdate.ColorPrint(ghupdate.ColorGreen, "Service restarted successfully") ++ for _, service := range []string{"beszel-hub", "beszel"} { ++ if err := exec.Command("rc-service", service, "status").Run(); err != nil { ++ continue + } ++ reportRestart(exec.Command("rc-service", service, "restart"), "sudo rc-service "+service+" restart") + return + } + } + + ghupdate.ColorPrint(ghupdate.ColorYellow, "Service restart not attempted. If running as a service, restart manually.") + } ++ ++// reportRestart runs the restart command and prints the result. ++func reportRestart(cmd *exec.Cmd, manualCommand string) { ++ ghupdate.ColorPrint(ghupdate.ColorYellow, "Restarting beszel service...") ++ if err := cmd.Run(); err != nil { ++ ghupdate.ColorPrintf(ghupdate.ColorYellow, "Warning: Failed to restart service: %v\n", err) ++ ghupdate.ColorPrint(ghupdate.ColorYellow, "Please restart the service manually: "+manualCommand) ++ } else { ++ ghupdate.ColorPrint(ghupdate.ColorGreen, "Service restarted successfully") ++ } ++} diff --git a/tasks/henrygd__beszel-2410/tests/test.sh b/tasks/henrygd__beszel-2410/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3bf873bce0ed76630d9a2cefe967cec0a05c1adc --- /dev/null +++ b/tasks/henrygd__beszel-2410/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 a99fe5e99725edf2a8ff582f5b21793fc88731f2 > "$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/henrygd__beszel-2410/tests/verifier.py b/tasks/henrygd__beszel-2410/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2410/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/henrygd__beszel-2411/environment/Dockerfile b/tasks/henrygd__beszel-2411/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6a5ffc4ffdf6811dce40ac9acdeffe9d1021819b --- /dev/null +++ b/tasks/henrygd__beszel-2411/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a99fe5e99725edf2a8ff582f5b21793fc88731f2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a99fe5e99725edf2a8ff582f5b21793fc88731f2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a99fe5e99725edf2a8ff582f5b21793fc88731f2 \ + && 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/henrygd__beszel-2411/instruction.md b/tasks/henrygd__beszel-2411/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..271322c62eea639065825d8b63acaa8769c2bad6 --- /dev/null +++ b/tasks/henrygd__beszel-2411/instruction.md @@ -0,0 +1,40 @@ +# Issue + +**Title:** fix(site): measure the longest name instead of estimating it + +## Description + +## 📃 Description + +. + +The systems table reserves column width with a hidden span holding the longest system name. `getVisualStringWidth` counts every latin character as one unit, so two names of the same length always score the same. `isVisuallyLonger` compares with `>`, so on a tie the name that was set first stays, and a name of equal length but greater pixel width gets truncated. + +That is exactly the reported case. Measured against the InterVariable.woff2 that ships in this repo: + +| name | advance width | at 14px | current estimate | +|---|---|---|---| +| hazelnut | 8273 | 56.55px | 8.0 | +| router2b | 8348 | 57.07px | 8.0 | + +So `router2b` is 0.51px wider, which matches the "about a pixel" in the issue, but the estimate sees both as 8.0 and keeps `hazelnut`. + +Weighting individual characters would not fix this reliably. The two names differ by 0.9 percent in width, which is finer than any character bucket table can resolve, and the next report would just use a different pair of names. + +So this measures the string with canvas `measureText` in the font taken from the document, and keeps the existing estimate as a fallback where canvas is not available. Only relative widths matter for the comparison, so the font size used for measuring is arbitrary. Cached widths are cleared once `document.fonts.ready` resolves, because the fallback font has different metrics than InterVariable and the first measurements can happen before the web font is in. + +`network-monitors-table` uses the same helper for targets, so it benefits as well. + +## 🪵 Changelog + +### 🔧 Fixed + +- The longest system name is now measured instead of estimated, so names of equal length no longer truncate in the systems, containers and network monitors tables + +## 📷 Screenshots + +No visual change beyond the truncation being gone, the layout is the same. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a99fe5e99725`. 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/henrygd__beszel-2411/solution/patch.diff b/tasks/henrygd__beszel-2411/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..15504630619742d9e7add0c6f995e9bfa8264d32 --- /dev/null +++ b/tasks/henrygd__beszel-2411/solution/patch.diff @@ -0,0 +1,185 @@ +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx +index eebbb3a1..b6cccb24 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx +@@ -138,7 +138,7 @@ export function getMonitorColumns( +
+
+ ), +- [status, name] ++ [status, name, longestSystemName] + ) + }, + }, +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +index 793862e3..6618d234 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +@@ -36,7 +36,7 @@ import { useToast } from "@/components/ui/use-toast" + import { isReadOnlyUser, queueUserSettings } from "@/lib/api" + import { pb } from "@/lib/api" + import { SystemStatus } from "@/lib/enums" +-import { $allSystemsById, $direction, $userSettings, getUserChartTime } from "@/lib/stores" ++import { $allSystemsById, $direction, $textMeasureVersion, $userSettings, getUserChartTime } from "@/lib/stores" + import { cn, formatShortDate, isVisuallyLonger, matchesFilterGroups, parseFilterGroups, parseSemVer } from "@/lib/utils" + import type { ChartData, MonitorCertInfo, NetworkMonitorRecord } from "@/types" + import { AddMonitorDialog, EditMonitorDialog } from "./monitor-dialog" +@@ -145,6 +145,8 @@ export default function NetworkMonitorsTableNew({ + [sortSettingsKey, sortStorageKey] + ) + ++ // recompute when measured widths are invalidated (e.g. web font finished loading) ++ const textMeasureVersion = useStore($textMeasureVersion) + const longestTarget = useMemo(() => { + let longestTarget = "" + for (const p of monitors) { +@@ -153,7 +155,7 @@ export default function NetworkMonitorsTableNew({ + } + } + return longestTarget +- }, [monitors]) ++ }, [monitors, textMeasureVersion]) + + const runMonitorBatch = useCallback( + async (ids: string[], enqueue: (batch: ReturnType, id: string) => void) => { +diff --git a/internal/site/src/lib/stores.ts b/internal/site/src/lib/stores.ts +index fe0199b7..eb0e304c 100644 +--- a/internal/site/src/lib/stores.ts ++++ b/internal/site/src/lib/stores.ts +@@ -93,3 +93,8 @@ export const $direction = atom<"ltr" | "rtl">("ltr") + + /** Longest system name string. Used to reserve width in virtualized tables. */ + export const $longestSystemName = atom("") ++ ++/** Incremented when measured text widths are invalidated (e.g. web font finished loading). ++ * Anything that caches a comparison from isVisuallyLonger should recompute when this changes. ++ */ ++export const $textMeasureVersion = atom(0) +diff --git a/internal/site/src/lib/systemsManager.ts b/internal/site/src/lib/systemsManager.ts +index 287d58ee..1a222a85 100644 +--- a/internal/site/src/lib/systemsManager.ts ++++ b/internal/site/src/lib/systemsManager.ts +@@ -7,6 +7,7 @@ import { + $downSystems, + $longestSystemName, + $pausedSystems, ++ $textMeasureVersion, + $upSystems, + } from "@/lib/stores" + import { isVisuallyLonger, updateFavicon } from "@/lib/utils" +@@ -67,6 +68,11 @@ export function init() { + // run things that need to be done when systems change + onSystemsChanged(newSystems, newSystem, oldSystem) + }) ++ ++ // widths measured with the fallback font may rank names differently, so recompute once they're invalidated ++ $textMeasureVersion.listen(() => { ++ $longestSystemName.set(findLongestName($allSystemsById.get())) ++ }) + } + + /** Update the longest system name string and favicon based on system status */ +@@ -78,13 +84,7 @@ function onSystemsChanged(systems: Record, newSystem?: Sys + // otherwise, if the changed system's new name is longer than the current longest, update it + const longestName = $longestSystemName.get() + if (oldSystem?.name === longestName && oldSystem.name !== newSystem?.name) { +- let newLongest = "" +- for (const id in systems) { +- if (isVisuallyLonger(systems[id].name, newLongest)) { +- newLongest = systems[id].name +- } +- } +- $longestSystemName.set(newLongest) ++ $longestSystemName.set(findLongestName(systems)) + } else if (newSystem && newSystem.name !== longestName && isVisuallyLonger(newSystem.name, longestName)) { + $longestSystemName.set(newSystem.name) + } +@@ -92,6 +92,17 @@ function onSystemsChanged(systems: Record, newSystem?: Sys + updateFavicon(downSystems.length) + } + ++/** Find the visually longest system name */ ++function findLongestName(systems: Record): string { ++ let longest = "" ++ for (const id in systems) { ++ if (isVisuallyLonger(systems[id].name, longest)) { ++ longest = systems[id].name ++ } ++ } ++ return longest ++} ++ + /** Fetch systems from collection */ + async function fetchSystems(): Promise { + try { +diff --git a/internal/site/src/lib/utils.ts b/internal/site/src/lib/utils.ts +index 0b06f63b..69c6a1eb 100644 +--- a/internal/site/src/lib/utils.ts ++++ b/internal/site/src/lib/utils.ts +@@ -7,7 +7,7 @@ import { twMerge } from "tailwind-merge" + import { toast } from "@/components/ui/use-toast" + import type { ChartTimeData, FingerprintRecord, SemVer, SystemRecord } from "@/types" + import { HourFormat, Unit } from "./enums" +-import { $copyContent, $userSettings } from "./stores" ++import { $copyContent, $textMeasureVersion, $userSettings } from "./stores" + + export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)) +@@ -451,6 +451,45 @@ export function runOnce any>(fn: T): T { + + const visualWidthCache = new Map() + ++let measureContext: CanvasRenderingContext2D | null | undefined ++let measureFont = "" ++ ++/** Canvas context for measuring text in the font the app renders with, or null where canvas is unavailable. ++ * Only relative widths matter here, so the font size is arbitrary. ++ */ ++function getMeasureContext(): CanvasRenderingContext2D | null { ++ if (measureContext === undefined) { ++ measureContext = document.createElement("canvas").getContext("2d") ++ // the fallback font has different metrics, so re-measure whenever a font finishes loading. ++ // loadingdone also covers fonts that start loading after the first measurement, ++ // which fonts.ready does not if it has already resolved. ++ if (measureContext && "fonts" in document) { ++ document.fonts.addEventListener("loadingdone", invalidateVisualWidths) ++ } ++ } ++ if (measureContext) { ++ const { fontFamily, fontWeight } = getComputedStyle(document.body) ++ const font = `${fontWeight} 16px ${fontFamily}` ++ if (font !== measureFont) { ++ const isFirstFont = !measureFont ++ measureFont = font ++ measureContext.font = font ++ visualWidthCache.clear() ++ // defer so stores aren't updated in the middle of a comparison or a render ++ if (!isFirstFont) { ++ queueMicrotask(invalidateVisualWidths) ++ } ++ } ++ } ++ return measureContext ++} ++ ++/** Drop cached widths and notify anything holding a result from isVisuallyLonger */ ++function invalidateVisualWidths() { ++ visualWidthCache.clear() ++ $textMeasureVersion.set($textMeasureVersion.get() + 1) ++} ++ + /** Get the visual width of a string, accounting for full-width and narrow punctuation characters. + * Don't use for monospaced fonts, use .length instead + */ +@@ -459,6 +498,11 @@ function getVisualStringWidth(str: string): number { + if (cached !== undefined) { + return cached + } ++ const measured = getMeasureContext()?.measureText(str).width ++ if (measured !== undefined) { ++ visualWidthCache.set(str, measured) ++ return measured ++ } + let width = 0 + for (const char of str) { + if (char === ".") { diff --git a/tasks/henrygd__beszel-2411/solution/solve.sh b/tasks/henrygd__beszel-2411/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2411/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/henrygd__beszel-2411/task.toml b/tasks/henrygd__beszel-2411/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b9a89124d936d92d43600daf5f81d23b31cddb0e --- /dev/null +++ b/tasks/henrygd__beszel-2411/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2411" +description = "fix(site): measure the longest name instead of estimating it" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "a99fe5e99725edf2a8ff582f5b21793fc88731f2" +reference = "https://github.com/henrygd/beszel/pull/2411" +source_access = "auto" +built_at = "2026-11-16T16:09:53.410564+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6b6b18440331351e1745e40d505eb7021bc6b8fd28f6cfc1b694291094da2dca" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-24T15:32:22Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/network-monitors-table/network-monitors-columns.tsx", + "internal/site/src/components/network-monitors-table/network-monitors-table.tsx", + "internal/site/src/lib/stores.ts", + "internal/site/src/lib/systemsManager.ts", + "internal/site/src/lib/utils.ts", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 84 +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:00.822484+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:81e4be62628c78838b45815d054bb0d0c5800b6952389c0051eff2fbe2b5c7d5" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2411/tests/capture.py b/tasks/henrygd__beszel-2411/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2411/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/henrygd__beszel-2411/tests/instruction.md b/tasks/henrygd__beszel-2411/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..271322c62eea639065825d8b63acaa8769c2bad6 --- /dev/null +++ b/tasks/henrygd__beszel-2411/tests/instruction.md @@ -0,0 +1,40 @@ +# Issue + +**Title:** fix(site): measure the longest name instead of estimating it + +## Description + +## 📃 Description + +. + +The systems table reserves column width with a hidden span holding the longest system name. `getVisualStringWidth` counts every latin character as one unit, so two names of the same length always score the same. `isVisuallyLonger` compares with `>`, so on a tie the name that was set first stays, and a name of equal length but greater pixel width gets truncated. + +That is exactly the reported case. Measured against the InterVariable.woff2 that ships in this repo: + +| name | advance width | at 14px | current estimate | +|---|---|---|---| +| hazelnut | 8273 | 56.55px | 8.0 | +| router2b | 8348 | 57.07px | 8.0 | + +So `router2b` is 0.51px wider, which matches the "about a pixel" in the issue, but the estimate sees both as 8.0 and keeps `hazelnut`. + +Weighting individual characters would not fix this reliably. The two names differ by 0.9 percent in width, which is finer than any character bucket table can resolve, and the next report would just use a different pair of names. + +So this measures the string with canvas `measureText` in the font taken from the document, and keeps the existing estimate as a fallback where canvas is not available. Only relative widths matter for the comparison, so the font size used for measuring is arbitrary. Cached widths are cleared once `document.fonts.ready` resolves, because the fallback font has different metrics than InterVariable and the first measurements can happen before the web font is in. + +`network-monitors-table` uses the same helper for targets, so it benefits as well. + +## 🪵 Changelog + +### 🔧 Fixed + +- The longest system name is now measured instead of estimated, so names of equal length no longer truncate in the systems, containers and network monitors tables + +## 📷 Screenshots + +No visual change beyond the truncation being gone, the layout is the same. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a99fe5e99725`. 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/henrygd__beszel-2411/tests/oracle.patch b/tasks/henrygd__beszel-2411/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..15504630619742d9e7add0c6f995e9bfa8264d32 --- /dev/null +++ b/tasks/henrygd__beszel-2411/tests/oracle.patch @@ -0,0 +1,185 @@ +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx +index eebbb3a1..b6cccb24 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx +@@ -138,7 +138,7 @@ export function getMonitorColumns( +
+
+ ), +- [status, name] ++ [status, name, longestSystemName] + ) + }, + }, +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +index 793862e3..6618d234 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +@@ -36,7 +36,7 @@ import { useToast } from "@/components/ui/use-toast" + import { isReadOnlyUser, queueUserSettings } from "@/lib/api" + import { pb } from "@/lib/api" + import { SystemStatus } from "@/lib/enums" +-import { $allSystemsById, $direction, $userSettings, getUserChartTime } from "@/lib/stores" ++import { $allSystemsById, $direction, $textMeasureVersion, $userSettings, getUserChartTime } from "@/lib/stores" + import { cn, formatShortDate, isVisuallyLonger, matchesFilterGroups, parseFilterGroups, parseSemVer } from "@/lib/utils" + import type { ChartData, MonitorCertInfo, NetworkMonitorRecord } from "@/types" + import { AddMonitorDialog, EditMonitorDialog } from "./monitor-dialog" +@@ -145,6 +145,8 @@ export default function NetworkMonitorsTableNew({ + [sortSettingsKey, sortStorageKey] + ) + ++ // recompute when measured widths are invalidated (e.g. web font finished loading) ++ const textMeasureVersion = useStore($textMeasureVersion) + const longestTarget = useMemo(() => { + let longestTarget = "" + for (const p of monitors) { +@@ -153,7 +155,7 @@ export default function NetworkMonitorsTableNew({ + } + } + return longestTarget +- }, [monitors]) ++ }, [monitors, textMeasureVersion]) + + const runMonitorBatch = useCallback( + async (ids: string[], enqueue: (batch: ReturnType, id: string) => void) => { +diff --git a/internal/site/src/lib/stores.ts b/internal/site/src/lib/stores.ts +index fe0199b7..eb0e304c 100644 +--- a/internal/site/src/lib/stores.ts ++++ b/internal/site/src/lib/stores.ts +@@ -93,3 +93,8 @@ export const $direction = atom<"ltr" | "rtl">("ltr") + + /** Longest system name string. Used to reserve width in virtualized tables. */ + export const $longestSystemName = atom("") ++ ++/** Incremented when measured text widths are invalidated (e.g. web font finished loading). ++ * Anything that caches a comparison from isVisuallyLonger should recompute when this changes. ++ */ ++export const $textMeasureVersion = atom(0) +diff --git a/internal/site/src/lib/systemsManager.ts b/internal/site/src/lib/systemsManager.ts +index 287d58ee..1a222a85 100644 +--- a/internal/site/src/lib/systemsManager.ts ++++ b/internal/site/src/lib/systemsManager.ts +@@ -7,6 +7,7 @@ import { + $downSystems, + $longestSystemName, + $pausedSystems, ++ $textMeasureVersion, + $upSystems, + } from "@/lib/stores" + import { isVisuallyLonger, updateFavicon } from "@/lib/utils" +@@ -67,6 +68,11 @@ export function init() { + // run things that need to be done when systems change + onSystemsChanged(newSystems, newSystem, oldSystem) + }) ++ ++ // widths measured with the fallback font may rank names differently, so recompute once they're invalidated ++ $textMeasureVersion.listen(() => { ++ $longestSystemName.set(findLongestName($allSystemsById.get())) ++ }) + } + + /** Update the longest system name string and favicon based on system status */ +@@ -78,13 +84,7 @@ function onSystemsChanged(systems: Record, newSystem?: Sys + // otherwise, if the changed system's new name is longer than the current longest, update it + const longestName = $longestSystemName.get() + if (oldSystem?.name === longestName && oldSystem.name !== newSystem?.name) { +- let newLongest = "" +- for (const id in systems) { +- if (isVisuallyLonger(systems[id].name, newLongest)) { +- newLongest = systems[id].name +- } +- } +- $longestSystemName.set(newLongest) ++ $longestSystemName.set(findLongestName(systems)) + } else if (newSystem && newSystem.name !== longestName && isVisuallyLonger(newSystem.name, longestName)) { + $longestSystemName.set(newSystem.name) + } +@@ -92,6 +92,17 @@ function onSystemsChanged(systems: Record, newSystem?: Sys + updateFavicon(downSystems.length) + } + ++/** Find the visually longest system name */ ++function findLongestName(systems: Record): string { ++ let longest = "" ++ for (const id in systems) { ++ if (isVisuallyLonger(systems[id].name, longest)) { ++ longest = systems[id].name ++ } ++ } ++ return longest ++} ++ + /** Fetch systems from collection */ + async function fetchSystems(): Promise { + try { +diff --git a/internal/site/src/lib/utils.ts b/internal/site/src/lib/utils.ts +index 0b06f63b..69c6a1eb 100644 +--- a/internal/site/src/lib/utils.ts ++++ b/internal/site/src/lib/utils.ts +@@ -7,7 +7,7 @@ import { twMerge } from "tailwind-merge" + import { toast } from "@/components/ui/use-toast" + import type { ChartTimeData, FingerprintRecord, SemVer, SystemRecord } from "@/types" + import { HourFormat, Unit } from "./enums" +-import { $copyContent, $userSettings } from "./stores" ++import { $copyContent, $textMeasureVersion, $userSettings } from "./stores" + + export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)) +@@ -451,6 +451,45 @@ export function runOnce any>(fn: T): T { + + const visualWidthCache = new Map() + ++let measureContext: CanvasRenderingContext2D | null | undefined ++let measureFont = "" ++ ++/** Canvas context for measuring text in the font the app renders with, or null where canvas is unavailable. ++ * Only relative widths matter here, so the font size is arbitrary. ++ */ ++function getMeasureContext(): CanvasRenderingContext2D | null { ++ if (measureContext === undefined) { ++ measureContext = document.createElement("canvas").getContext("2d") ++ // the fallback font has different metrics, so re-measure whenever a font finishes loading. ++ // loadingdone also covers fonts that start loading after the first measurement, ++ // which fonts.ready does not if it has already resolved. ++ if (measureContext && "fonts" in document) { ++ document.fonts.addEventListener("loadingdone", invalidateVisualWidths) ++ } ++ } ++ if (measureContext) { ++ const { fontFamily, fontWeight } = getComputedStyle(document.body) ++ const font = `${fontWeight} 16px ${fontFamily}` ++ if (font !== measureFont) { ++ const isFirstFont = !measureFont ++ measureFont = font ++ measureContext.font = font ++ visualWidthCache.clear() ++ // defer so stores aren't updated in the middle of a comparison or a render ++ if (!isFirstFont) { ++ queueMicrotask(invalidateVisualWidths) ++ } ++ } ++ } ++ return measureContext ++} ++ ++/** Drop cached widths and notify anything holding a result from isVisuallyLonger */ ++function invalidateVisualWidths() { ++ visualWidthCache.clear() ++ $textMeasureVersion.set($textMeasureVersion.get() + 1) ++} ++ + /** Get the visual width of a string, accounting for full-width and narrow punctuation characters. + * Don't use for monospaced fonts, use .length instead + */ +@@ -459,6 +498,11 @@ function getVisualStringWidth(str: string): number { + if (cached !== undefined) { + return cached + } ++ const measured = getMeasureContext()?.measureText(str).width ++ if (measured !== undefined) { ++ visualWidthCache.set(str, measured) ++ return measured ++ } + let width = 0 + for (const char of str) { + if (char === ".") { diff --git a/tasks/henrygd__beszel-2411/tests/test.sh b/tasks/henrygd__beszel-2411/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3bf873bce0ed76630d9a2cefe967cec0a05c1adc --- /dev/null +++ b/tasks/henrygd__beszel-2411/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 a99fe5e99725edf2a8ff582f5b21793fc88731f2 > "$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/henrygd__beszel-2411/tests/verifier.py b/tasks/henrygd__beszel-2411/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2411/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/henrygd__beszel-2419/environment/Dockerfile b/tasks/henrygd__beszel-2419/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0bea7cc09bad556231e1ddcb430d17f735c27c3f --- /dev/null +++ b/tasks/henrygd__beszel-2419/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c25408651f076c59c13f35f27016461ada8a9093 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c25408651f076c59c13f35f27016461ada8a9093 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c25408651f076c59c13f35f27016461ada8a9093 \ + && 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/henrygd__beszel-2419/instruction.md b/tasks/henrygd__beszel-2419/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1a142b6bf4669877d47c4a1dde17529a78cfbfe1 --- /dev/null +++ b/tasks/henrygd__beszel-2419/instruction.md @@ -0,0 +1,48 @@ +# Issue + +**Title:** fix(agent): keep Windows volume names intact when matching I/O devices + +## Description + +## 📃 Description + +`normalizeDeviceName` normalizes every device string with `filepath.Base`. That is +platform-dependent for a bare Windows volume name: on Windows, `Base` strips the +`"C:"` specifier and, finding no path element left, returns `"\".` So `C:`, `D:` +and `P:` all normalize to the same key. + +`findIoDevice` matches on `normalizeDeviceName(d.Name) == filesystem`, so with all +three keys collapsed its exact match returns whichever entry the `disk.IOCounters` +map happened to yield first. The root filesystem is then registered under a random +drive — which is why the root disk vanishes with `EXTRA_FILESYSTEMS=D:,P:` (its +key is already taken), and why without that variable the root can show up under +another drive's I/O device. + +Two changes: + +- `normalizeDeviceName` recognizes a bare volume specifier and returns it in a + canonical form, so `C:`, `C:\` and `C:/` all name the same drive. A + drive-relative path such as `C:data` is still treated as a path. +- `addPartitionRootFs` passes the device to `findIoDevice` unchanged. The + `filepath.Base` there mangled the value before `findIoDevice` could normalize + it, and `findIoDevice` normalizes internally anyway. `registerFilesystemStats` + already avoids this by only taking a base when the agent is not on Windows. + +The device→I/O mapping is a pure string comparison, so the regression tests run +on any host rather than only on Windows. + +## 🪵 Changelog + +### 🔧 Fixed + +- Windows: the root filesystem is matched to its own drive's I/O counters instead + of a random drive, so it no longer disappears when `EXTRA_FILESYSTEMS` is set + or gets registered under another drive's device. + +## 📷 Screenshots + +None — agent-side device matching only, no UI change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c25408651f07`. 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/henrygd__beszel-2419/solution/patch.diff b/tasks/henrygd__beszel-2419/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9344240472d412fac7d6884474a47b64726d7aea --- /dev/null +++ b/tasks/henrygd__beszel-2419/solution/patch.diff @@ -0,0 +1,138 @@ +diff --git a/agent/disk.go b/agent/disk.go +index 13bb1b1c..8574beff 100644 +--- a/agent/disk.go ++++ b/agent/disk.go +@@ -204,7 +204,10 @@ func isRootFallbackPartition(p disk.PartitionStat, rootMountPoint string) bool { + // partition looks like the active root mount but still needs translating to an + // I/O device key. + func (d *diskDiscovery) addPartitionRootFs(device, mountpoint string) bool { +- fs, match := findIoDevice(filepath.Base(device), d.ctx.diskIoCounters) ++ // device is passed through as-is: findIoDevice normalizes it, and ++ // filepath.Base would turn a Windows volume name such as "C:" into "\" ++ // on the way in (#2417). ++ fs, match := findIoDevice(device, d.ctx.diskIoCounters) + if !match { + return false + } +@@ -527,13 +530,45 @@ func filesystemMatchesPartitionSetting(filesystem string, p disk.PartitionStat) + + // normalizeDeviceName canonicalizes device strings for comparisons. + func normalizeDeviceName(value string) string { +- name := filepath.Base(strings.TrimSpace(value)) ++ name := strings.TrimSpace(value) ++ if volume, ok := windowsVolumeName(name); ok { ++ return volume ++ } ++ name = filepath.Base(name) + if name == "." { + return "" + } + return name + } + ++// windowsVolumeName returns the canonical form of a bare Windows volume ++// specifier, so that "C:", `C:\` and "C:/" all name the same drive. ++// ++// filepath.Base cannot do this. On Windows it treats "C:" as a volume name ++// with no path element to take the base of and returns "\", so every drive ++// letter normalizes to the same key. findIoDevice then returns whichever ++// counter the map happened to yield first, which registers the root ++// filesystem under a random drive (#2417). ++func windowsVolumeName(value string) (string, bool) { ++ if len(value) < 2 || value[1] != ':' { ++ return "", false ++ } ++ if c := value[0]; !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') { ++ return "", false ++ } ++ if len(value) == 2 { ++ return value, true ++ } ++ // Only separators may follow the specifier. "C:data" is a drive-relative ++ // path, not a volume. ++ for i := 2; i < len(value); i++ { ++ if value[i] != '\\' && value[i] != '/' { ++ return "", false ++ } ++ } ++ return value[:2], true ++} ++ + // Sets start values for disk I/O stats. + func (a *Agent) initializeDiskIoStats(diskIoCounters map[string]disk.IOCountersStat) { + a.fsNames = a.fsNames[:0] +diff --git a/agent/disk_test.go b/agent/disk_test.go +index 70fa2083..59f423bf 100644 +--- a/agent/disk_test.go ++++ b/agent/disk_test.go +@@ -1057,3 +1057,70 @@ func TestIoTimeDelta(t *testing.T) { + + assert.Equal(t, uint64(0), ioTimeDelta(200, math.MaxUint32+1000)) + } ++ ++func TestNormalizeDeviceName(t *testing.T) { ++ // A Windows volume name is not a path element, so every spelling of the ++ // same drive has to normalize to the same key. filepath.Base cannot do ++ // this: on Windows it strips the "C:" specifier and returns "\", which ++ // collapses every drive letter onto one key (#2417). ++ for _, spelling := range []string{"C:", `C:\`, "C:/", `C:\\`} { ++ assert.Equal(t, "C:", normalizeDeviceName(spelling), "spelling %q", spelling) ++ } ++ // Case is left to the caller, as it already is for Linux device names. ++ assert.Equal(t, "d:", normalizeDeviceName("d:")) ++ assert.Equal(t, "c:", normalizeDeviceName(" c: ")) ++ ++ // Non-volume inputs keep using filepath.Base. ++ assert.Equal(t, "sda1", normalizeDeviceName("/dev/sda1")) ++ assert.Equal(t, "sda1", normalizeDeviceName("/dev/sda1/")) ++ assert.Equal(t, "nvme0n1p2", normalizeDeviceName(" /dev/nvme0n1p2 ")) ++ assert.Equal(t, "", normalizeDeviceName(".")) ++ assert.Equal(t, "", normalizeDeviceName(" ")) ++ ++ // A drive-relative path is a path, not a volume. ++ assert.Equal(t, `C:data`, normalizeDeviceName(`C:data`)) ++} ++ ++func TestFindIoDeviceWindowsVolumeNames(t *testing.T) { ++ // Every drive normalizes to a distinct key, so the root drive resolves ++ // exactly instead of to whichever counter the map yielded first (#2417). ++ ioCounters := map[string]disk.IOCountersStat{ ++ "C:": {Name: "C:", ReadBytes: 10, WriteBytes: 10}, ++ "D:": {Name: "D:", ReadBytes: 20, WriteBytes: 20}, ++ "P:": {Name: "P:", ReadBytes: 30, WriteBytes: 30}, ++ } ++ ++ for i := 0; i < 32; i++ { ++ device, ok := findIoDevice("C:", ioCounters) ++ assert.True(t, ok) ++ assert.Equal(t, "C:", device) ++ } ++ ++ // The drive may arrive with a trailing separator, as a mount point does. ++ device, ok := findIoDevice(`C:\`, ioCounters) ++ assert.True(t, ok) ++ assert.Equal(t, "C:", device) ++} ++ ++func TestAddPartitionRootFsWindowsDrive(t *testing.T) { ++ agent := &Agent{fsStats: make(map[string]*system.FsStats)} ++ discovery := diskDiscovery{ ++ agent: agent, ++ ctx: fsRegistrationContext{ ++ isWindows: true, ++ diskIoCounters: map[string]disk.IOCountersStat{ ++ "C:": {Name: "C:"}, ++ "D:": {Name: "D:"}, ++ "P:": {Name: "P:"}, ++ }, ++ }, ++ } ++ ++ ok := discovery.addPartitionRootFs("C:", `C:\`) ++ ++ assert.True(t, ok) ++ assert.Len(t, agent.fsStats, 1) ++ stats, exists := agent.fsStats["C:"] ++ assert.True(t, exists) ++ assert.True(t, stats.Root) ++} diff --git a/tasks/henrygd__beszel-2419/solution/solve.sh b/tasks/henrygd__beszel-2419/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2419/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/henrygd__beszel-2419/task.toml b/tasks/henrygd__beszel-2419/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c31a5a6a3ee6e1c9122e1e7211617577e9cba4fc --- /dev/null +++ b/tasks/henrygd__beszel-2419/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2419" +description = "fix(agent): keep Windows volume names intact when matching I/O devices" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "c25408651f076c59c13f35f27016461ada8a9093" +reference = "https://github.com/henrygd/beszel/pull/2419" +source_access = "auto" +built_at = "2026-11-16T16:09:53.481647+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8fbede71aa71f6a87c41b32c5c626c93690fca22ca39139f791b6da275a76b52" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-25T17:09:11Z" +diff_format = "unified" +context_files = [ + "agent/disk.go", + "agent/disk_test.go", +] +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:00.822945+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0cb183576d68f7790e7e3c98a9fc8699ba597f6536eb549934208ab662043ee8" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2419/tests/capture.py b/tasks/henrygd__beszel-2419/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2419/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/henrygd__beszel-2419/tests/instruction.md b/tasks/henrygd__beszel-2419/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1a142b6bf4669877d47c4a1dde17529a78cfbfe1 --- /dev/null +++ b/tasks/henrygd__beszel-2419/tests/instruction.md @@ -0,0 +1,48 @@ +# Issue + +**Title:** fix(agent): keep Windows volume names intact when matching I/O devices + +## Description + +## 📃 Description + +`normalizeDeviceName` normalizes every device string with `filepath.Base`. That is +platform-dependent for a bare Windows volume name: on Windows, `Base` strips the +`"C:"` specifier and, finding no path element left, returns `"\".` So `C:`, `D:` +and `P:` all normalize to the same key. + +`findIoDevice` matches on `normalizeDeviceName(d.Name) == filesystem`, so with all +three keys collapsed its exact match returns whichever entry the `disk.IOCounters` +map happened to yield first. The root filesystem is then registered under a random +drive — which is why the root disk vanishes with `EXTRA_FILESYSTEMS=D:,P:` (its +key is already taken), and why without that variable the root can show up under +another drive's I/O device. + +Two changes: + +- `normalizeDeviceName` recognizes a bare volume specifier and returns it in a + canonical form, so `C:`, `C:\` and `C:/` all name the same drive. A + drive-relative path such as `C:data` is still treated as a path. +- `addPartitionRootFs` passes the device to `findIoDevice` unchanged. The + `filepath.Base` there mangled the value before `findIoDevice` could normalize + it, and `findIoDevice` normalizes internally anyway. `registerFilesystemStats` + already avoids this by only taking a base when the agent is not on Windows. + +The device→I/O mapping is a pure string comparison, so the regression tests run +on any host rather than only on Windows. + +## 🪵 Changelog + +### 🔧 Fixed + +- Windows: the root filesystem is matched to its own drive's I/O counters instead + of a random drive, so it no longer disappears when `EXTRA_FILESYSTEMS` is set + or gets registered under another drive's device. + +## 📷 Screenshots + +None — agent-side device matching only, no UI change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c25408651f07`. 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/henrygd__beszel-2419/tests/oracle.patch b/tasks/henrygd__beszel-2419/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9344240472d412fac7d6884474a47b64726d7aea --- /dev/null +++ b/tasks/henrygd__beszel-2419/tests/oracle.patch @@ -0,0 +1,138 @@ +diff --git a/agent/disk.go b/agent/disk.go +index 13bb1b1c..8574beff 100644 +--- a/agent/disk.go ++++ b/agent/disk.go +@@ -204,7 +204,10 @@ func isRootFallbackPartition(p disk.PartitionStat, rootMountPoint string) bool { + // partition looks like the active root mount but still needs translating to an + // I/O device key. + func (d *diskDiscovery) addPartitionRootFs(device, mountpoint string) bool { +- fs, match := findIoDevice(filepath.Base(device), d.ctx.diskIoCounters) ++ // device is passed through as-is: findIoDevice normalizes it, and ++ // filepath.Base would turn a Windows volume name such as "C:" into "\" ++ // on the way in (#2417). ++ fs, match := findIoDevice(device, d.ctx.diskIoCounters) + if !match { + return false + } +@@ -527,13 +530,45 @@ func filesystemMatchesPartitionSetting(filesystem string, p disk.PartitionStat) + + // normalizeDeviceName canonicalizes device strings for comparisons. + func normalizeDeviceName(value string) string { +- name := filepath.Base(strings.TrimSpace(value)) ++ name := strings.TrimSpace(value) ++ if volume, ok := windowsVolumeName(name); ok { ++ return volume ++ } ++ name = filepath.Base(name) + if name == "." { + return "" + } + return name + } + ++// windowsVolumeName returns the canonical form of a bare Windows volume ++// specifier, so that "C:", `C:\` and "C:/" all name the same drive. ++// ++// filepath.Base cannot do this. On Windows it treats "C:" as a volume name ++// with no path element to take the base of and returns "\", so every drive ++// letter normalizes to the same key. findIoDevice then returns whichever ++// counter the map happened to yield first, which registers the root ++// filesystem under a random drive (#2417). ++func windowsVolumeName(value string) (string, bool) { ++ if len(value) < 2 || value[1] != ':' { ++ return "", false ++ } ++ if c := value[0]; !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') { ++ return "", false ++ } ++ if len(value) == 2 { ++ return value, true ++ } ++ // Only separators may follow the specifier. "C:data" is a drive-relative ++ // path, not a volume. ++ for i := 2; i < len(value); i++ { ++ if value[i] != '\\' && value[i] != '/' { ++ return "", false ++ } ++ } ++ return value[:2], true ++} ++ + // Sets start values for disk I/O stats. + func (a *Agent) initializeDiskIoStats(diskIoCounters map[string]disk.IOCountersStat) { + a.fsNames = a.fsNames[:0] +diff --git a/agent/disk_test.go b/agent/disk_test.go +index 70fa2083..59f423bf 100644 +--- a/agent/disk_test.go ++++ b/agent/disk_test.go +@@ -1057,3 +1057,70 @@ func TestIoTimeDelta(t *testing.T) { + + assert.Equal(t, uint64(0), ioTimeDelta(200, math.MaxUint32+1000)) + } ++ ++func TestNormalizeDeviceName(t *testing.T) { ++ // A Windows volume name is not a path element, so every spelling of the ++ // same drive has to normalize to the same key. filepath.Base cannot do ++ // this: on Windows it strips the "C:" specifier and returns "\", which ++ // collapses every drive letter onto one key (#2417). ++ for _, spelling := range []string{"C:", `C:\`, "C:/", `C:\\`} { ++ assert.Equal(t, "C:", normalizeDeviceName(spelling), "spelling %q", spelling) ++ } ++ // Case is left to the caller, as it already is for Linux device names. ++ assert.Equal(t, "d:", normalizeDeviceName("d:")) ++ assert.Equal(t, "c:", normalizeDeviceName(" c: ")) ++ ++ // Non-volume inputs keep using filepath.Base. ++ assert.Equal(t, "sda1", normalizeDeviceName("/dev/sda1")) ++ assert.Equal(t, "sda1", normalizeDeviceName("/dev/sda1/")) ++ assert.Equal(t, "nvme0n1p2", normalizeDeviceName(" /dev/nvme0n1p2 ")) ++ assert.Equal(t, "", normalizeDeviceName(".")) ++ assert.Equal(t, "", normalizeDeviceName(" ")) ++ ++ // A drive-relative path is a path, not a volume. ++ assert.Equal(t, `C:data`, normalizeDeviceName(`C:data`)) ++} ++ ++func TestFindIoDeviceWindowsVolumeNames(t *testing.T) { ++ // Every drive normalizes to a distinct key, so the root drive resolves ++ // exactly instead of to whichever counter the map yielded first (#2417). ++ ioCounters := map[string]disk.IOCountersStat{ ++ "C:": {Name: "C:", ReadBytes: 10, WriteBytes: 10}, ++ "D:": {Name: "D:", ReadBytes: 20, WriteBytes: 20}, ++ "P:": {Name: "P:", ReadBytes: 30, WriteBytes: 30}, ++ } ++ ++ for i := 0; i < 32; i++ { ++ device, ok := findIoDevice("C:", ioCounters) ++ assert.True(t, ok) ++ assert.Equal(t, "C:", device) ++ } ++ ++ // The drive may arrive with a trailing separator, as a mount point does. ++ device, ok := findIoDevice(`C:\`, ioCounters) ++ assert.True(t, ok) ++ assert.Equal(t, "C:", device) ++} ++ ++func TestAddPartitionRootFsWindowsDrive(t *testing.T) { ++ agent := &Agent{fsStats: make(map[string]*system.FsStats)} ++ discovery := diskDiscovery{ ++ agent: agent, ++ ctx: fsRegistrationContext{ ++ isWindows: true, ++ diskIoCounters: map[string]disk.IOCountersStat{ ++ "C:": {Name: "C:"}, ++ "D:": {Name: "D:"}, ++ "P:": {Name: "P:"}, ++ }, ++ }, ++ } ++ ++ ok := discovery.addPartitionRootFs("C:", `C:\`) ++ ++ assert.True(t, ok) ++ assert.Len(t, agent.fsStats, 1) ++ stats, exists := agent.fsStats["C:"] ++ assert.True(t, exists) ++ assert.True(t, stats.Root) ++} diff --git a/tasks/henrygd__beszel-2419/tests/test.sh b/tasks/henrygd__beszel-2419/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b7f01e373e81647cb80855e404c94f8c6e6c4774 --- /dev/null +++ b/tasks/henrygd__beszel-2419/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 c25408651f076c59c13f35f27016461ada8a9093 > "$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/henrygd__beszel-2419/tests/verifier.py b/tasks/henrygd__beszel-2419/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2419/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/henrygd__beszel-2420/environment/Dockerfile b/tasks/henrygd__beszel-2420/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2ac745a0f250cd6b913aecb4fa8db67884fa005f --- /dev/null +++ b/tasks/henrygd__beszel-2420/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3fb97b800cdbb5985587df9644bc484c8ec1bbb9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3fb97b800cdbb5985587df9644bc484c8ec1bbb9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3fb97b800cdbb5985587df9644bc484c8ec1bbb9 \ + && 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/henrygd__beszel-2420/instruction.md b/tasks/henrygd__beszel-2420/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..723d171297ac49582c38ad0acffdfe3341f1551b --- /dev/null +++ b/tasks/henrygd__beszel-2420/instruction.md @@ -0,0 +1,73 @@ +# Issue + +**Title:** fix(agent): report disk I/O time metrics on the first sample of an interval + +## Description + +## 📃 Description + +When a cache interval calls `updateDiskIo` for the first time, it has no snapshot of its own in `diskPrev`. The seed takes the byte counters from `fsStats` (`TotalRead` and `TotalWrite` at `stats.Time`). The time counters and operation counts come from the current reading, because `fsStats` has no baseline for them. That sample measures throughput over the real interval, but each time metric has a delta of zero. All six values in `DiskIoStats` are 0: read time, write time, `Utilization`, `r_await`, `w_await` and weighted I/O. + +This happens once per interval and device in each agent run: + +- the first hub record after the agent starts, because `initializeDiskIoStats` sets `stats.Time` at startup +- the first point of each other interval, for example the realtime view + +A probe with real counters on macOS (`disk0`, 200 MB written with `fsync`, then `updateDiskIo(60000)`): + +| | write bytes/s | `DiskIoStats` | +|---|---|---| +| `main` (`d80a2f49`) | 187206060 | `[0 0 0 0 0 0]` | +| this branch | 185664000 | `[23.61 13.11 36.72 0.18 0.14 0]` | + +Weighted I/O stays 0 on macOS, because gopsutil does not fill `WeightedIO` there. + +The fix keeps the full counter snapshot of each device in `diskBaseline` on the agent. The agent writes it at the two places that already update the `fsStats` baseline: `initializeDiskIoStats` and the end of `updateDiskIo`. The seed reads from `diskBaseline` and falls back to the current reading, as before. + +I rejected two other fixes: + +- Seed from the current reading only. Then `msElapsed` is 0, `updateDiskIo` skips the sample, and the first throughput value is lost too. +- Add the counters to `system.FsStats`. The agent sends that struct to the hub, and these counters are internal to the agent. + +## 🪵 Changelog + +### 🔧 Fixed + +- The first disk I/O sample of an interval no longer reports 0 for all six disk I/O time metrics. + +## Verification + +`TestUpdateDiskIoFirstSampleOfInterval` writes a diskstats file through `HOST_PROC`. It calls `initializeDiskIoStats`, then `updateDiskIo` for interval 60000, then for interval 1000. The second interval must start from the counters of the first interval, not from the ones at start. With the wrong baseline, `r_await` is 20 and not 10. + +The test waits 150 ms between calls, because `updateDiskIo` skips samples less than 100 ms apart. The expected await values do not depend on the elapsed time. I ran it on Debian 13 (Linux 6.12.107, arm64), built with `GOOS=linux GOARCH=arm64 go test -c -tags='testing no_ui' ./agent`. + +Before the change (`d80a2f49`), shortened: + +``` +Error: Should not be zero, but was 0 +Messages: DiskIoStats[2] +Error: Max difference between 30 and 0 allowed is 0.01, but difference was 30 +Messages: r_await +Error: Max difference between 20 and 0 allowed is 0.01, but difference was 20 +Messages: w_await +Error: Should not be zero, but was 0 +Messages: weighted io +Error: Max difference between 10 and 0 allowed is 0.01, but difference was 10 +Messages: r_await +[...] +--- FAIL: TestUpdateDiskIoFirstSampleOfInterval (0.30s) +``` + +After the change, the test passes. + +- Full `./agent` test binary on the Debian host, two runs each. Before the change, only the new test fails. After the change, the package passes, with 361 of 361 top-level tests. +- I ran three mutations of the fix. Each one makes the test fail: + - no baseline in `initializeDiskIoStats`: zero bytes + - no baseline update at the end of `updateDiskIo`: `r_await` 20 instead of 10 + - seed ignores the baseline: zero bytes +- `go test -tags='testing no_ui' ./...` on macOS 26 arm64: 20 packages pass. `./agent` fails on `main` and on this branch. Two tests fail in each run (`TestSkipGpuShadowUsesSysSensorsRoot`, `TestNewSensorConfigSkipGpuWiresShadow`). The GPU tests with a fixed sleep fail in some runs. On Linux, all of them pass. +- `go vet -tags='testing no_ui' ./agent` for linux/arm64 and darwin/arm64, and `gofmt -l` on the changed files: clean. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3fb97b800cdb`. 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/henrygd__beszel-2420/solution/patch.diff b/tasks/henrygd__beszel-2420/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f4dc982e6beb8a9ed2b48e48ef30d612df901a39 --- /dev/null +++ b/tasks/henrygd__beszel-2420/solution/patch.diff @@ -0,0 +1,136 @@ +diff --git a/agent/agent.go b/agent/agent.go +index 998a32a7..810569fd 100644 +--- a/agent/agent.go ++++ b/agent/agent.go +@@ -29,6 +29,7 @@ type Agent struct { + fsNames []string // List of filesystem device names being monitored + fsStats map[string]*system.FsStats // Keeps track of disk stats for each filesystem + diskPrev map[uint16]map[string]prevDisk // Previous disk I/O counters per cache interval ++ diskBaseline map[string]prevDisk // Latest disk I/O counters of any interval, seeds a new interval + diskUsageCacheDuration time.Duration // How long to cache disk usage (to avoid waking sleeping disks) + lastDiskUsageUpdate time.Time // Last time disk usage was collected + netInterfaces map[string]struct{} // Stores all valid network interfaces +diff --git a/agent/disk.go b/agent/disk.go +index 13bb1b1c..e02b86c2 100644 +--- a/agent/disk.go ++++ b/agent/disk.go +@@ -558,6 +558,7 @@ func (a *Agent) initializeDiskIoStats(diskIoCounters map[string]disk.IOCountersS + stats.Time = now + stats.TotalRead = d.ReadBytes + stats.TotalWrite = d.WriteBytes ++ a.setDiskBaseline(device, prevDiskFromCounter(d, now)) + // add to list of valid io device names + a.fsNames = append(a.fsNames, device) + } +@@ -640,19 +641,9 @@ func (a *Agent) updateDiskIo(cacheTimeMs uint16, systemStats *system.Stats) { + // Previous snapshot for this interval and device + prev, hasPrev := a.diskPrev[cacheTimeMs][name] + if !hasPrev { +- // Seed from agent-level fsStats if present, else seed from current +- prev = prevDisk{ +- readBytes: stats.TotalRead, +- writeBytes: stats.TotalWrite, +- readTime: d.ReadTime, +- writeTime: d.WriteTime, +- ioTime: d.IoTime, +- weightedIO: d.WeightedIO, +- readCount: d.ReadCount, +- writeCount: d.WriteCount, +- at: stats.Time, +- } +- if prev.at.IsZero() { ++ // Seed from the latest counters of any interval, else seed from current ++ prev, hasPrev = a.diskBaseline[name] ++ if !hasPrev { + prev = prevDiskFromCounter(d, now) + } + } +@@ -711,6 +702,7 @@ func (a *Agent) updateDiskIo(cacheTimeMs uint16, systemStats *system.Stats) { + } + + // Update global fsStats baseline for cross-interval correctness ++ a.setDiskBaseline(name, prevDiskFromCounter(d, now)) + stats.Time = now + stats.TotalRead = d.ReadBytes + stats.TotalWrite = d.WriteBytes +@@ -743,6 +735,15 @@ func (a *Agent) updateDiskIo(cacheTimeMs uint16, systemStats *system.Stats) { + } + } + ++// setDiskBaseline stores the latest counters of a device. A cache interval ++// without its own snapshot measures its first sample from them. ++func (a *Agent) setDiskBaseline(name string, d prevDisk) { ++ if a.diskBaseline == nil { ++ a.diskBaseline = make(map[string]prevDisk) ++ } ++ a.diskBaseline[name] = d ++} ++ + // ioTimeDelta returns the increase of a cumulative millisecond counter from + // the disk I/O stats. Linux prints these fields of /proc/diskstats as 32-bit + // unsigned ints, so they wrap to zero at 2^32. A busy disk reaches that in +diff --git a/agent/disk_io_linux_test.go b/agent/disk_io_linux_test.go +index 90e462a0..546b6f12 100644 +--- a/agent/disk_io_linux_test.go ++++ b/agent/disk_io_linux_test.go +@@ -10,6 +10,7 @@ import ( + "time" + + "github.com/henrygd/beszel/internal/entities/system" ++ "github.com/shirou/gopsutil/v4/disk" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + ) +@@ -73,3 +74,52 @@ func TestUpdateDiskIoTimeCounterWrap(t *testing.T) { + }) + } + } ++ ++// The first sample of a cache interval has no snapshot of its own. It must ++// measure the time counters from the same baseline as the byte counters. ++func TestUpdateDiskIoFirstSampleOfInterval(t *testing.T) { ++ dir := t.TempDir() ++ t.Setenv("HOST_PROC", dir) ++ t.Setenv("HOST_SYS", dir) ++ t.Setenv("HOST_DEV", dir) ++ t.Setenv("HOST_RUN", dir) ++ writeDiskstats := func(line string) { ++ require.NoError(t, os.WriteFile(filepath.Join(dir, "diskstats"), []byte(line), 0o644)) ++ } ++ ++ writeDiskstats(" 8 0 sda 1000 0 20000 900 500 0 10000 700 0 400 0\n") ++ counters, err := disk.IOCounters("sda") ++ require.NoError(t, err) ++ ++ fs := &system.FsStats{Root: true} ++ a := &Agent{ ++ fsStats: map[string]*system.FsStats{"sda": fs}, ++ diskPrev: map[uint16]map[string]prevDisk{}, ++ } ++ a.initializeDiskIoStats(counters) ++ ++ // updateDiskIo skips samples less than 100ms apart. ++ time.Sleep(150 * time.Millisecond) ++ ++ // Deltas: read 300ms / 10 ops, write 400ms / 20 ops, io time 1200ms, weighted io 3000ms. ++ writeDiskstats(" 8 0 sda 1010 0 21200 1200 520 0 10400 1100 0 1600 3000\n") ++ var stats system.Stats ++ a.updateDiskIo(60000, &stats) ++ ++ require.NotZero(t, fs.DiskReadBytes, "bytes are measured from the baseline") ++ for i := range 3 { ++ assert.NotZero(t, fs.DiskIoStats[i], "DiskIoStats[%d]", i) ++ } ++ assert.InDelta(t, 30, fs.DiskIoStats[3], 0.01, "r_await") ++ assert.InDelta(t, 20, fs.DiskIoStats[4], 0.01, "w_await") ++ assert.NotZero(t, fs.DiskIoStats[5], "weighted io") ++ ++ // A second interval starts from the latest counters, not from the ones at start. ++ time.Sleep(150 * time.Millisecond) ++ // Deltas: read 100ms / 10 ops, write 100ms / 20 ops. ++ writeDiskstats(" 8 0 sda 1020 0 22400 1300 540 0 10800 1200 0 1800 3500\n") ++ a.updateDiskIo(1000, &stats) ++ ++ assert.InDelta(t, 10, fs.DiskIoStats[3], 0.01, "r_await") ++ assert.InDelta(t, 5, fs.DiskIoStats[4], 0.01, "w_await") ++} diff --git a/tasks/henrygd__beszel-2420/solution/solve.sh b/tasks/henrygd__beszel-2420/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2420/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/henrygd__beszel-2420/task.toml b/tasks/henrygd__beszel-2420/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1198d5a8f77b46c58a5b575203f611138b1dbb7c --- /dev/null +++ b/tasks/henrygd__beszel-2420/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2420" +description = "fix(agent): report disk I/O time metrics on the first sample of an interval" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "3fb97b800cdbb5985587df9644bc484c8ec1bbb9" +reference = "https://github.com/henrygd/beszel/pull/2420" +source_access = "auto" +built_at = "2026-11-16T16:09:53.479781+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:607263cee8ebf74715e33fc578f922224bd94c2b1f1b58cdf3fa32e85fcc95f3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-25T17:38:05Z" +diff_format = "unified" +context_files = [ + "agent/agent.go", + "agent/disk.go", + "agent/disk_io_linux_test.go", +] +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:00.823402+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:325e046fa3aa79fa1d08cca2c0a8cc8fc5457e2b35a3aff862f9b7570bf6f0d9" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2420/tests/capture.py b/tasks/henrygd__beszel-2420/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2420/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/henrygd__beszel-2420/tests/instruction.md b/tasks/henrygd__beszel-2420/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..723d171297ac49582c38ad0acffdfe3341f1551b --- /dev/null +++ b/tasks/henrygd__beszel-2420/tests/instruction.md @@ -0,0 +1,73 @@ +# Issue + +**Title:** fix(agent): report disk I/O time metrics on the first sample of an interval + +## Description + +## 📃 Description + +When a cache interval calls `updateDiskIo` for the first time, it has no snapshot of its own in `diskPrev`. The seed takes the byte counters from `fsStats` (`TotalRead` and `TotalWrite` at `stats.Time`). The time counters and operation counts come from the current reading, because `fsStats` has no baseline for them. That sample measures throughput over the real interval, but each time metric has a delta of zero. All six values in `DiskIoStats` are 0: read time, write time, `Utilization`, `r_await`, `w_await` and weighted I/O. + +This happens once per interval and device in each agent run: + +- the first hub record after the agent starts, because `initializeDiskIoStats` sets `stats.Time` at startup +- the first point of each other interval, for example the realtime view + +A probe with real counters on macOS (`disk0`, 200 MB written with `fsync`, then `updateDiskIo(60000)`): + +| | write bytes/s | `DiskIoStats` | +|---|---|---| +| `main` (`d80a2f49`) | 187206060 | `[0 0 0 0 0 0]` | +| this branch | 185664000 | `[23.61 13.11 36.72 0.18 0.14 0]` | + +Weighted I/O stays 0 on macOS, because gopsutil does not fill `WeightedIO` there. + +The fix keeps the full counter snapshot of each device in `diskBaseline` on the agent. The agent writes it at the two places that already update the `fsStats` baseline: `initializeDiskIoStats` and the end of `updateDiskIo`. The seed reads from `diskBaseline` and falls back to the current reading, as before. + +I rejected two other fixes: + +- Seed from the current reading only. Then `msElapsed` is 0, `updateDiskIo` skips the sample, and the first throughput value is lost too. +- Add the counters to `system.FsStats`. The agent sends that struct to the hub, and these counters are internal to the agent. + +## 🪵 Changelog + +### 🔧 Fixed + +- The first disk I/O sample of an interval no longer reports 0 for all six disk I/O time metrics. + +## Verification + +`TestUpdateDiskIoFirstSampleOfInterval` writes a diskstats file through `HOST_PROC`. It calls `initializeDiskIoStats`, then `updateDiskIo` for interval 60000, then for interval 1000. The second interval must start from the counters of the first interval, not from the ones at start. With the wrong baseline, `r_await` is 20 and not 10. + +The test waits 150 ms between calls, because `updateDiskIo` skips samples less than 100 ms apart. The expected await values do not depend on the elapsed time. I ran it on Debian 13 (Linux 6.12.107, arm64), built with `GOOS=linux GOARCH=arm64 go test -c -tags='testing no_ui' ./agent`. + +Before the change (`d80a2f49`), shortened: + +``` +Error: Should not be zero, but was 0 +Messages: DiskIoStats[2] +Error: Max difference between 30 and 0 allowed is 0.01, but difference was 30 +Messages: r_await +Error: Max difference between 20 and 0 allowed is 0.01, but difference was 20 +Messages: w_await +Error: Should not be zero, but was 0 +Messages: weighted io +Error: Max difference between 10 and 0 allowed is 0.01, but difference was 10 +Messages: r_await +[...] +--- FAIL: TestUpdateDiskIoFirstSampleOfInterval (0.30s) +``` + +After the change, the test passes. + +- Full `./agent` test binary on the Debian host, two runs each. Before the change, only the new test fails. After the change, the package passes, with 361 of 361 top-level tests. +- I ran three mutations of the fix. Each one makes the test fail: + - no baseline in `initializeDiskIoStats`: zero bytes + - no baseline update at the end of `updateDiskIo`: `r_await` 20 instead of 10 + - seed ignores the baseline: zero bytes +- `go test -tags='testing no_ui' ./...` on macOS 26 arm64: 20 packages pass. `./agent` fails on `main` and on this branch. Two tests fail in each run (`TestSkipGpuShadowUsesSysSensorsRoot`, `TestNewSensorConfigSkipGpuWiresShadow`). The GPU tests with a fixed sleep fail in some runs. On Linux, all of them pass. +- `go vet -tags='testing no_ui' ./agent` for linux/arm64 and darwin/arm64, and `gofmt -l` on the changed files: clean. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3fb97b800cdb`. 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/henrygd__beszel-2420/tests/oracle.patch b/tasks/henrygd__beszel-2420/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f4dc982e6beb8a9ed2b48e48ef30d612df901a39 --- /dev/null +++ b/tasks/henrygd__beszel-2420/tests/oracle.patch @@ -0,0 +1,136 @@ +diff --git a/agent/agent.go b/agent/agent.go +index 998a32a7..810569fd 100644 +--- a/agent/agent.go ++++ b/agent/agent.go +@@ -29,6 +29,7 @@ type Agent struct { + fsNames []string // List of filesystem device names being monitored + fsStats map[string]*system.FsStats // Keeps track of disk stats for each filesystem + diskPrev map[uint16]map[string]prevDisk // Previous disk I/O counters per cache interval ++ diskBaseline map[string]prevDisk // Latest disk I/O counters of any interval, seeds a new interval + diskUsageCacheDuration time.Duration // How long to cache disk usage (to avoid waking sleeping disks) + lastDiskUsageUpdate time.Time // Last time disk usage was collected + netInterfaces map[string]struct{} // Stores all valid network interfaces +diff --git a/agent/disk.go b/agent/disk.go +index 13bb1b1c..e02b86c2 100644 +--- a/agent/disk.go ++++ b/agent/disk.go +@@ -558,6 +558,7 @@ func (a *Agent) initializeDiskIoStats(diskIoCounters map[string]disk.IOCountersS + stats.Time = now + stats.TotalRead = d.ReadBytes + stats.TotalWrite = d.WriteBytes ++ a.setDiskBaseline(device, prevDiskFromCounter(d, now)) + // add to list of valid io device names + a.fsNames = append(a.fsNames, device) + } +@@ -640,19 +641,9 @@ func (a *Agent) updateDiskIo(cacheTimeMs uint16, systemStats *system.Stats) { + // Previous snapshot for this interval and device + prev, hasPrev := a.diskPrev[cacheTimeMs][name] + if !hasPrev { +- // Seed from agent-level fsStats if present, else seed from current +- prev = prevDisk{ +- readBytes: stats.TotalRead, +- writeBytes: stats.TotalWrite, +- readTime: d.ReadTime, +- writeTime: d.WriteTime, +- ioTime: d.IoTime, +- weightedIO: d.WeightedIO, +- readCount: d.ReadCount, +- writeCount: d.WriteCount, +- at: stats.Time, +- } +- if prev.at.IsZero() { ++ // Seed from the latest counters of any interval, else seed from current ++ prev, hasPrev = a.diskBaseline[name] ++ if !hasPrev { + prev = prevDiskFromCounter(d, now) + } + } +@@ -711,6 +702,7 @@ func (a *Agent) updateDiskIo(cacheTimeMs uint16, systemStats *system.Stats) { + } + + // Update global fsStats baseline for cross-interval correctness ++ a.setDiskBaseline(name, prevDiskFromCounter(d, now)) + stats.Time = now + stats.TotalRead = d.ReadBytes + stats.TotalWrite = d.WriteBytes +@@ -743,6 +735,15 @@ func (a *Agent) updateDiskIo(cacheTimeMs uint16, systemStats *system.Stats) { + } + } + ++// setDiskBaseline stores the latest counters of a device. A cache interval ++// without its own snapshot measures its first sample from them. ++func (a *Agent) setDiskBaseline(name string, d prevDisk) { ++ if a.diskBaseline == nil { ++ a.diskBaseline = make(map[string]prevDisk) ++ } ++ a.diskBaseline[name] = d ++} ++ + // ioTimeDelta returns the increase of a cumulative millisecond counter from + // the disk I/O stats. Linux prints these fields of /proc/diskstats as 32-bit + // unsigned ints, so they wrap to zero at 2^32. A busy disk reaches that in +diff --git a/agent/disk_io_linux_test.go b/agent/disk_io_linux_test.go +index 90e462a0..546b6f12 100644 +--- a/agent/disk_io_linux_test.go ++++ b/agent/disk_io_linux_test.go +@@ -10,6 +10,7 @@ import ( + "time" + + "github.com/henrygd/beszel/internal/entities/system" ++ "github.com/shirou/gopsutil/v4/disk" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + ) +@@ -73,3 +74,52 @@ func TestUpdateDiskIoTimeCounterWrap(t *testing.T) { + }) + } + } ++ ++// The first sample of a cache interval has no snapshot of its own. It must ++// measure the time counters from the same baseline as the byte counters. ++func TestUpdateDiskIoFirstSampleOfInterval(t *testing.T) { ++ dir := t.TempDir() ++ t.Setenv("HOST_PROC", dir) ++ t.Setenv("HOST_SYS", dir) ++ t.Setenv("HOST_DEV", dir) ++ t.Setenv("HOST_RUN", dir) ++ writeDiskstats := func(line string) { ++ require.NoError(t, os.WriteFile(filepath.Join(dir, "diskstats"), []byte(line), 0o644)) ++ } ++ ++ writeDiskstats(" 8 0 sda 1000 0 20000 900 500 0 10000 700 0 400 0\n") ++ counters, err := disk.IOCounters("sda") ++ require.NoError(t, err) ++ ++ fs := &system.FsStats{Root: true} ++ a := &Agent{ ++ fsStats: map[string]*system.FsStats{"sda": fs}, ++ diskPrev: map[uint16]map[string]prevDisk{}, ++ } ++ a.initializeDiskIoStats(counters) ++ ++ // updateDiskIo skips samples less than 100ms apart. ++ time.Sleep(150 * time.Millisecond) ++ ++ // Deltas: read 300ms / 10 ops, write 400ms / 20 ops, io time 1200ms, weighted io 3000ms. ++ writeDiskstats(" 8 0 sda 1010 0 21200 1200 520 0 10400 1100 0 1600 3000\n") ++ var stats system.Stats ++ a.updateDiskIo(60000, &stats) ++ ++ require.NotZero(t, fs.DiskReadBytes, "bytes are measured from the baseline") ++ for i := range 3 { ++ assert.NotZero(t, fs.DiskIoStats[i], "DiskIoStats[%d]", i) ++ } ++ assert.InDelta(t, 30, fs.DiskIoStats[3], 0.01, "r_await") ++ assert.InDelta(t, 20, fs.DiskIoStats[4], 0.01, "w_await") ++ assert.NotZero(t, fs.DiskIoStats[5], "weighted io") ++ ++ // A second interval starts from the latest counters, not from the ones at start. ++ time.Sleep(150 * time.Millisecond) ++ // Deltas: read 100ms / 10 ops, write 100ms / 20 ops. ++ writeDiskstats(" 8 0 sda 1020 0 22400 1300 540 0 10800 1200 0 1800 3500\n") ++ a.updateDiskIo(1000, &stats) ++ ++ assert.InDelta(t, 10, fs.DiskIoStats[3], 0.01, "r_await") ++ assert.InDelta(t, 5, fs.DiskIoStats[4], 0.01, "w_await") ++} diff --git a/tasks/henrygd__beszel-2420/tests/test.sh b/tasks/henrygd__beszel-2420/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7059d650cf14ccc38aac6471c1b9d75d52f899b8 --- /dev/null +++ b/tasks/henrygd__beszel-2420/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 3fb97b800cdbb5985587df9644bc484c8ec1bbb9 > "$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/henrygd__beszel-2420/tests/verifier.py b/tasks/henrygd__beszel-2420/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2420/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/henrygd__beszel-2426/environment/Dockerfile b/tasks/henrygd__beszel-2426/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..57e0ecf49ba0f7df5d2e75b6d8e89abcf21174fe --- /dev/null +++ b/tasks/henrygd__beszel-2426/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin fb4e93f09811f7efc442c4a1218736287767aa4a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard fb4e93f09811f7efc442c4a1218736287767aa4a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base fb4e93f09811f7efc442c4a1218736287767aa4a \ + && 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/henrygd__beszel-2426/instruction.md b/tasks/henrygd__beszel-2426/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fcbc0e34339b17ab65379ed2764d99475e3f743d --- /dev/null +++ b/tasks/henrygd__beszel-2426/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(site): avoid duplicate y-axis labels on network monitor response charts + +## Description + +### Summary + +. + +#### Root Cause +In \AvgMinMaxResponseChart\, the y-axis tick formatter uses \ ickFormatter={(value) => formatMicroseconds(value, false)}\. Previously, \ ormatMicroseconds\ passed \showDigits ? digits : 0\ to \decimalString(num, digits)\. When \digits === 0\, \decimalString\ executed \Math.ceil(num).toString()\. When Recharts generates intermediate fractional tick steps (e.g. \6.2ms\, \6.4ms\, \6.6ms\, \6.8ms\, \7.0ms\), \Math.ceil\ rounded every intermediate value up to \7ms\, displaying identical duplicated numbers on the y-axis. + +#### Fix +- In \ ormatMicroseconds\, when \showDigits === false\ (as used by chart axis ticks), format using \ oFixedFloat(value, digits)\ instead of \decimalString(value, 0)\. Whole numbers remain compact without trailing zeros (e.g. \6ms\, \1s\), while fractional intervals retain significant decimals (e.g. \6.2ms\, \6.5ms\), preventing duplicate tick marks. +- When \showDigits === true\ (used for table columns and tooltips), \decimalString\ is preserved to maintain fixed decimal alignment. +- Added unit tests in \internal/site/tests/format-microseconds.test.ts\ verifying tick formatting and absence of duplicate labels across tick intervals. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fb4e93f09811`. 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/henrygd__beszel-2426/solution/patch.diff b/tasks/henrygd__beszel-2426/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0874e7ffb333bc5d2ab4bb2398185dc962094fa6 --- /dev/null +++ b/tasks/henrygd__beszel-2426/solution/patch.diff @@ -0,0 +1,90 @@ +diff --git a/internal/site/src/lib/utils.ts b/internal/site/src/lib/utils.ts +index 69c6a1eb..f9050c4c 100644 +--- a/internal/site/src/lib/utils.ts ++++ b/internal/site/src/lib/utils.ts +@@ -199,7 +199,7 @@ export function decimalString(num: number, digits = 2) { + return formatter.format(num) + } + +-export function formatMicroseconds(microseconds: number, showDigits = true): string { ++export function formatMicroseconds(microseconds: number, fixedDigits = true): string { + if (!Number.isFinite(microseconds)) { + return "-" + } +@@ -208,15 +208,17 @@ export function formatMicroseconds(microseconds: number, showDigits = true): str + return `${microseconds}μs` + } + ++ const digitFormatter = fixedDigits ? decimalString : toFixedFloat ++ + if (microseconds < 1_000_000) { + const milliseconds = microseconds / 1000 + const digits = milliseconds >= 10 ? 1 : 2 +- return `${decimalString(milliseconds, showDigits ? digits : 0)}ms` ++ return `${digitFormatter(milliseconds, digits)}ms` + } + + const seconds = microseconds / 1_000_000 + const digits = seconds >= 10 ? 1 : 2 +- return `${decimalString(seconds, showDigits ? digits : 0)}s` ++ return `${digitFormatter(seconds, digits)}s` + } + + /** Get value from local or session storage */ +diff --git a/internal/site/tests/utils.test.ts b/internal/site/tests/utils.test.ts +new file mode 100644 +index 00000000..d8fcbcbf +--- /dev/null ++++ b/internal/site/tests/utils.test.ts +@@ -0,0 +1,51 @@ ++import { describe, expect, mock, test } from "bun:test" ++ ++mock.module("@lingui/core/macro", () => ({ ++ t: (strings: any) => (typeof strings === "string" ? strings : strings?.[0] ?? ""), ++ plural: (count: number, forms: any) => forms.other ?? "", ++})) ++ ++const { formatMicroseconds } = await import("../src/lib/utils") ++ ++describe("formatMicroseconds", () => { ++ test("formats with fixedDigits = true (default)", () => { ++ expect(formatMicroseconds(500)).toBe("500μs") ++ expect(formatMicroseconds(6000)).toBe("6.00ms") ++ expect(formatMicroseconds(6500)).toBe("6.50ms") ++ expect(formatMicroseconds(12000)).toBe("12.0ms") ++ expect(formatMicroseconds(12500)).toBe("12.5ms") ++ expect(formatMicroseconds(1_000_000)).toBe("1.00s") ++ expect(formatMicroseconds(1_500_000)).toBe("1.50s") ++ expect(formatMicroseconds(12_000_000)).toBe("12.0s") ++ }) ++ ++ test("formats with fixedDigits = false (used for chart y-axis ticks)", () => { ++ expect(formatMicroseconds(500, false)).toBe("500μs") ++ expect(formatMicroseconds(500.5, false)).toBe("500.5μs") ++ expect(formatMicroseconds(6000, false)).toBe("6ms") ++ expect(formatMicroseconds(6200, false)).toBe("6.2ms") ++ expect(formatMicroseconds(6500, false)).toBe("6.5ms") ++ expect(formatMicroseconds(6750, false)).toBe("6.75ms") ++ expect(formatMicroseconds(7000, false)).toBe("7ms") ++ expect(formatMicroseconds(12000, false)).toBe("12ms") ++ expect(formatMicroseconds(12500, false)).toBe("12.5ms") ++ expect(formatMicroseconds(1_000_000, false)).toBe("1s") ++ expect(formatMicroseconds(1_500_000, false)).toBe("1.5s") ++ expect(formatMicroseconds(12_000_000, false)).toBe("12s") ++ }) ++ ++ test("prevents duplicate tick values for intermediate intervals (#2373)", () => { ++ const tickInputs = [6000, 6200, 6400, 6600, 6800, 7000] ++ const formattedTicks = tickInputs.map((val) => formatMicroseconds(val, false)) ++ expect(formattedTicks).toEqual(["6ms", "6.2ms", "6.4ms", "6.6ms", "6.8ms", "7ms"]) ++ // Verify all formatted ticks are unique ++ const uniqueTicks = new Set(formattedTicks) ++ expect(uniqueTicks.size).toBe(tickInputs.length) ++ }) ++ ++ test("handles invalid / non-finite values", () => { ++ expect(formatMicroseconds(Number.NaN)).toBe("-") ++ expect(formatMicroseconds(Number.POSITIVE_INFINITY)).toBe("-") ++ expect(formatMicroseconds(Number.NEGATIVE_INFINITY)).toBe("-") ++ }) ++}) diff --git a/tasks/henrygd__beszel-2426/solution/solve.sh b/tasks/henrygd__beszel-2426/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2426/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/henrygd__beszel-2426/task.toml b/tasks/henrygd__beszel-2426/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..25e84894f66651dd129746fcb4934f589fcdcef7 --- /dev/null +++ b/tasks/henrygd__beszel-2426/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2426" +description = "fix(site): avoid duplicate y-axis labels on network monitor response charts" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "fb4e93f09811f7efc442c4a1218736287767aa4a" +reference = "https://github.com/henrygd/beszel/pull/2426" +source_access = "auto" +built_at = "2026-11-16T16:09:53.478004+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:adbc861c0e4ed05f77e07008724ce2b22586a05fe08a5bf007a781834e34173c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-26T16:37:12Z" +diff_format = "unified" +context_files = [ + "internal/site/src/lib/utils.ts", + "internal/site/tests/utils.test.ts", +] +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:00.823867+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6cbcafa41bce096d37903819836cb7af565928a2530827d9d1f8e44cacd2d290" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2426/tests/capture.py b/tasks/henrygd__beszel-2426/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2426/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/henrygd__beszel-2426/tests/instruction.md b/tasks/henrygd__beszel-2426/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fcbc0e34339b17ab65379ed2764d99475e3f743d --- /dev/null +++ b/tasks/henrygd__beszel-2426/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(site): avoid duplicate y-axis labels on network monitor response charts + +## Description + +### Summary + +. + +#### Root Cause +In \AvgMinMaxResponseChart\, the y-axis tick formatter uses \ ickFormatter={(value) => formatMicroseconds(value, false)}\. Previously, \ ormatMicroseconds\ passed \showDigits ? digits : 0\ to \decimalString(num, digits)\. When \digits === 0\, \decimalString\ executed \Math.ceil(num).toString()\. When Recharts generates intermediate fractional tick steps (e.g. \6.2ms\, \6.4ms\, \6.6ms\, \6.8ms\, \7.0ms\), \Math.ceil\ rounded every intermediate value up to \7ms\, displaying identical duplicated numbers on the y-axis. + +#### Fix +- In \ ormatMicroseconds\, when \showDigits === false\ (as used by chart axis ticks), format using \ oFixedFloat(value, digits)\ instead of \decimalString(value, 0)\. Whole numbers remain compact without trailing zeros (e.g. \6ms\, \1s\), while fractional intervals retain significant decimals (e.g. \6.2ms\, \6.5ms\), preventing duplicate tick marks. +- When \showDigits === true\ (used for table columns and tooltips), \decimalString\ is preserved to maintain fixed decimal alignment. +- Added unit tests in \internal/site/tests/format-microseconds.test.ts\ verifying tick formatting and absence of duplicate labels across tick intervals. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `fb4e93f09811`. 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/henrygd__beszel-2426/tests/oracle.patch b/tasks/henrygd__beszel-2426/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0874e7ffb333bc5d2ab4bb2398185dc962094fa6 --- /dev/null +++ b/tasks/henrygd__beszel-2426/tests/oracle.patch @@ -0,0 +1,90 @@ +diff --git a/internal/site/src/lib/utils.ts b/internal/site/src/lib/utils.ts +index 69c6a1eb..f9050c4c 100644 +--- a/internal/site/src/lib/utils.ts ++++ b/internal/site/src/lib/utils.ts +@@ -199,7 +199,7 @@ export function decimalString(num: number, digits = 2) { + return formatter.format(num) + } + +-export function formatMicroseconds(microseconds: number, showDigits = true): string { ++export function formatMicroseconds(microseconds: number, fixedDigits = true): string { + if (!Number.isFinite(microseconds)) { + return "-" + } +@@ -208,15 +208,17 @@ export function formatMicroseconds(microseconds: number, showDigits = true): str + return `${microseconds}μs` + } + ++ const digitFormatter = fixedDigits ? decimalString : toFixedFloat ++ + if (microseconds < 1_000_000) { + const milliseconds = microseconds / 1000 + const digits = milliseconds >= 10 ? 1 : 2 +- return `${decimalString(milliseconds, showDigits ? digits : 0)}ms` ++ return `${digitFormatter(milliseconds, digits)}ms` + } + + const seconds = microseconds / 1_000_000 + const digits = seconds >= 10 ? 1 : 2 +- return `${decimalString(seconds, showDigits ? digits : 0)}s` ++ return `${digitFormatter(seconds, digits)}s` + } + + /** Get value from local or session storage */ +diff --git a/internal/site/tests/utils.test.ts b/internal/site/tests/utils.test.ts +new file mode 100644 +index 00000000..d8fcbcbf +--- /dev/null ++++ b/internal/site/tests/utils.test.ts +@@ -0,0 +1,51 @@ ++import { describe, expect, mock, test } from "bun:test" ++ ++mock.module("@lingui/core/macro", () => ({ ++ t: (strings: any) => (typeof strings === "string" ? strings : strings?.[0] ?? ""), ++ plural: (count: number, forms: any) => forms.other ?? "", ++})) ++ ++const { formatMicroseconds } = await import("../src/lib/utils") ++ ++describe("formatMicroseconds", () => { ++ test("formats with fixedDigits = true (default)", () => { ++ expect(formatMicroseconds(500)).toBe("500μs") ++ expect(formatMicroseconds(6000)).toBe("6.00ms") ++ expect(formatMicroseconds(6500)).toBe("6.50ms") ++ expect(formatMicroseconds(12000)).toBe("12.0ms") ++ expect(formatMicroseconds(12500)).toBe("12.5ms") ++ expect(formatMicroseconds(1_000_000)).toBe("1.00s") ++ expect(formatMicroseconds(1_500_000)).toBe("1.50s") ++ expect(formatMicroseconds(12_000_000)).toBe("12.0s") ++ }) ++ ++ test("formats with fixedDigits = false (used for chart y-axis ticks)", () => { ++ expect(formatMicroseconds(500, false)).toBe("500μs") ++ expect(formatMicroseconds(500.5, false)).toBe("500.5μs") ++ expect(formatMicroseconds(6000, false)).toBe("6ms") ++ expect(formatMicroseconds(6200, false)).toBe("6.2ms") ++ expect(formatMicroseconds(6500, false)).toBe("6.5ms") ++ expect(formatMicroseconds(6750, false)).toBe("6.75ms") ++ expect(formatMicroseconds(7000, false)).toBe("7ms") ++ expect(formatMicroseconds(12000, false)).toBe("12ms") ++ expect(formatMicroseconds(12500, false)).toBe("12.5ms") ++ expect(formatMicroseconds(1_000_000, false)).toBe("1s") ++ expect(formatMicroseconds(1_500_000, false)).toBe("1.5s") ++ expect(formatMicroseconds(12_000_000, false)).toBe("12s") ++ }) ++ ++ test("prevents duplicate tick values for intermediate intervals (#2373)", () => { ++ const tickInputs = [6000, 6200, 6400, 6600, 6800, 7000] ++ const formattedTicks = tickInputs.map((val) => formatMicroseconds(val, false)) ++ expect(formattedTicks).toEqual(["6ms", "6.2ms", "6.4ms", "6.6ms", "6.8ms", "7ms"]) ++ // Verify all formatted ticks are unique ++ const uniqueTicks = new Set(formattedTicks) ++ expect(uniqueTicks.size).toBe(tickInputs.length) ++ }) ++ ++ test("handles invalid / non-finite values", () => { ++ expect(formatMicroseconds(Number.NaN)).toBe("-") ++ expect(formatMicroseconds(Number.POSITIVE_INFINITY)).toBe("-") ++ expect(formatMicroseconds(Number.NEGATIVE_INFINITY)).toBe("-") ++ }) ++}) diff --git a/tasks/henrygd__beszel-2426/tests/test.sh b/tasks/henrygd__beszel-2426/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ccc525a825710900e1dac569f01e9ea20b024e3 --- /dev/null +++ b/tasks/henrygd__beszel-2426/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 fb4e93f09811f7efc442c4a1218736287767aa4a > "$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/henrygd__beszel-2426/tests/verifier.py b/tasks/henrygd__beszel-2426/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2426/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/henrygd__beszel-2435/environment/Dockerfile b/tasks/henrygd__beszel-2435/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..452f9782d2e1978ab65c2a466cb7cdc2a28dbbdc --- /dev/null +++ b/tasks/henrygd__beszel-2435/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4fe1a0a7a42f655564e0b1577a2bc0dd74af8f58 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4fe1a0a7a42f655564e0b1577a2bc0dd74af8f58 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4fe1a0a7a42f655564e0b1577a2bc0dd74af8f58 \ + && 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/henrygd__beszel-2435/instruction.md b/tasks/henrygd__beszel-2435/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..24542e8f4a8f68578e2f6226e9b235169ec46da9 --- /dev/null +++ b/tasks/henrygd__beszel-2435/instruction.md @@ -0,0 +1,51 @@ +# Issue + +**Title:** fix(hub): ping a slow agent so its connection survives between polls + +## Description + +## 📃 Description + +. + +This is on top of 8bf6917f, not instead of it. That commit stops `fetchDataFromAgent` from *closing* the connection when the stats request times out. The connection still goes away, just later and by a different route: `ws.deadline` was 70s and only a message arriving **from** the agent pushes it out. + +| | | +|---|---| +| poll interval | 60s (`interval`) | +| data request timeout | 30s (`wsDataRequestTimeout`) | +| hub read deadline | 70s → 100s (`ws.deadline`) | + +Measured from a healthy poll at t=0, whose response is what last reset the deadline: + +1. t=60s the next poll sends its request, the agent is collecting and stays silent, +2. t=70s the read deadline expires and the hub closes the connection, 10s into the collection, +3. t=90s the fetch gives up. + +The agent reconnects, starts collecting slowly again, and the cycle repeats. + +Two changes, and both are needed: + +**`update()` pings the agent when a fetch fails** and the connection is still up. That is the same move `handlePaused` already makes for a paused system, and `Ping()` pushes the deadline out as it sends, so it works without an answer. The system is still reported down, because that comes from the error `update()` returns; only the connection survives, so recovery costs no reconnect. + +**The read deadline goes from 70s to 100s.** The ping only happens once the fetch gives up, at interval + request timeout = 90s, so the deadline has to outlast that or the ping never goes out. The deadline alone is not enough either: while fetches keep failing nothing resets it, and the connection would die 100s after the last message instead of 70s. With both, each failed poll re-arms the deadline. 100s keeps the same 10s margin the old 70s had over the poll interval. + +`deadline` became a `var` so the test can drive the schedule at a reduced scale. Only the testing-tagged helper writes it. + +One thing I did not touch: the agent handles hub requests on its read loop, so while it is collecting it cannot answer a ping at all. That is why the fix works from the hub's side without needing a reply. + +## 🪵 Changelog + +### 🔧 Fixed + +- Slow agents no longer get disconnected and reconnected in a loop when collection outlasts the hub's read deadline (#2294) + +## 🧪 Test plan + +`TestSlowAgentKeepsConnectionAcrossPolls` in `internal/hub/systems/ws_data_timeout_test.go` runs the real poll schedule at 1/100 against an agent that answers once, then goes silent and never answers a ping. It fails with either half reverted: with the deadline back at 70s, and with the ping removed from `update()`. Both checked. `TestUpdatePingsAgentAfterFailedFetch` covers the ping on a failed fetch directly. + +Rebased on `upstream/main` at e01e2a20. `make test` is green, `go vet` clean, and `internal/hub/systems` and `internal/hub/ws` also pass under `-race`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4fe1a0a7a42f`. 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/henrygd__beszel-2435/solution/patch.diff b/tasks/henrygd__beszel-2435/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3a545f8391dc237a1cd6367cea7949bfbe53c3dc --- /dev/null +++ b/tasks/henrygd__beszel-2435/solution/patch.diff @@ -0,0 +1,295 @@ +diff --git a/internal/hub/systems/system.go b/internal/hub/systems/system.go +index 0a292668..57d0f199 100644 +--- a/internal/hub/systems/system.go ++++ b/internal/hub/systems/system.go +@@ -174,6 +174,26 @@ func (sys *System) update() error { + + data, err := sys.fetchDataFromAgent(options) + if err != nil { ++ // Keep the WebSocket alive even though this fetch failed. ++ // ++ // Only a message from the agent resets the read deadline, and an agent ++ // still collecting sends nothing. Without this ping the deadline expires ++ // between polls, the hub closes the connection, the agent reconnects, ++ // collects slowly again, and the cycle repeats. Pinging here is the same ++ // move handlePaused already makes for a paused system, and Ping() pushes ++ // the deadline out as it sends, so it works without an answer, which ++ // matters because a collecting agent cannot answer. ++ // ++ // This is why the deadline has to exceed interval + wsDataRequestTimeout: ++ // the ping only happens once the fetch gives up. See ws.deadline. ++ // ++ // The system is still reported down: that comes from the error we ++ // return. Only the connection survives, so recovery costs no reconnect. ++ // A failed ping needs no handling either, since a connection that ++ // cannot be pinged runs into its deadline anyway. ++ if sys.WsConn != nil && sys.WsConn.IsConnected() { ++ _ = sys.WsConn.Ping() ++ } + return err + } + +diff --git a/internal/hub/systems/ws_data_timeout_test.go b/internal/hub/systems/ws_data_timeout_test.go +index ae6720fd..a8a019c4 100644 +--- a/internal/hub/systems/ws_data_timeout_test.go ++++ b/internal/hub/systems/ws_data_timeout_test.go +@@ -7,6 +7,7 @@ import ( + "net/http" + "net/http/httptest" + "strings" ++ "sync/atomic" + "testing" + "time" + +@@ -80,3 +81,180 @@ func TestFetchDataTimeoutKeepsWebSocketOpen(t *testing.T) { + _, err = sys.fetchDataFromAgent(common.DataRequestOptions{}) + require.NoError(t, err) + } ++ ++// pingCountingClient never answers GetData and records the pings it receives, ++// standing in for an agent whose collection outlasts the request timeout. ++type pingCountingClient struct { ++ gws.BuiltinEventHandler ++ pings chan struct{} ++} ++ ++func (c *pingCountingClient) OnPing(conn *gws.Conn, payload []byte) { ++ _ = conn.WritePong(payload) ++ select { ++ case c.pings <- struct{}{}: ++ default: ++ } ++} ++ ++func (c *pingCountingClient) OnMessage(conn *gws.Conn, message *gws.Message) { ++ // Swallow the request: this agent is still collecting. ++ message.Close() ++} ++ ++// A slow agent used to be disconnected between polls. The fetch gives up after ++// wsDataRequestTimeout, but the hub's read deadline is longer and only traffic ++// from the agent resets it, so nothing kept the connection alive in between. ++// update() now pings on a failed fetch, which is what breaks the reconnect ++// loop reported in #2294. ++func TestUpdatePingsAgentAfterFailedFetch(t *testing.T) { ++ originalTimeout := wsDataRequestTimeout ++ wsDataRequestTimeout = 50 * time.Millisecond ++ t.Cleanup(func() { wsDataRequestTimeout = originalTimeout }) ++ ++ connections := make(chan *ws.WsConn, 1) ++ upgrader := gws.NewUpgrader(&monitorSyncServer{}, nil) ++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ++ conn, err := upgrader.Upgrade(w, r) ++ if err != nil { ++ t.Error(err) ++ return ++ } ++ wsConn := ws.NewWsConnection(conn, semver.MustParse("0.20.0")) ++ conn.Session().Store("wsConn", wsConn) ++ connections <- wsConn ++ conn.ReadLoop() ++ })) ++ t.Cleanup(server.Close) ++ ++ client := &pingCountingClient{pings: make(chan struct{}, 4)} ++ conn, _, err := gws.NewClient(client, &gws.ClientOption{Addr: "ws" + strings.TrimPrefix(server.URL, "http")}) ++ require.NoError(t, err) ++ t.Cleanup(func() { _ = conn.NetConn().Close() }) ++ go conn.ReadLoop() ++ ++ var sys *System ++ select { ++ case wsConn := <-connections: ++ sys = &System{WsConn: wsConn} ++ case <-time.After(3 * time.Second): ++ t.Fatal("websocket connection was not established") ++ } ++ ++ err = sys.update() ++ require.ErrorIs(t, err, context.DeadlineExceeded, "the fetch is expected to time out") ++ ++ select { ++ case <-client.pings: ++ case <-time.After(3 * time.Second): ++ t.Fatal("a failed fetch must ping the agent to keep the connection alive") ++ } ++ ++ require.True(t, sys.WsConn.IsConnected(), "the connection must survive a failed fetch") ++} ++ ++// silentAfterFirstPollAgent answers the first GetData and then goes quiet, ++// modelling an agent whose collection outlasts the request timeout. It never ++// answers a ping, because a real agent serves hub requests on its read loop and ++// cannot reply while it is collecting. The fix therefore has to work without an ++// answer, which it does: Ping() pushes the deadline out as it sends. ++type silentAfterFirstPollAgent struct { ++ gws.BuiltinEventHandler ++ answered atomic.Bool ++} ++ ++func (c *silentAfterFirstPollAgent) OnPing(*gws.Conn, []byte) {} ++ ++func (c *silentAfterFirstPollAgent) OnMessage(conn *gws.Conn, message *gws.Message) { ++ defer message.Close() ++ var req common.HubRequest[cbor.RawMessage] ++ if err := cbor.Unmarshal(message.Bytes(), &req); err != nil || req.Action != common.GetData { ++ return ++ } ++ if c.answered.CompareAndSwap(false, true) { ++ response, _ := cbor.Marshal(common.AgentResponse{Id: req.Id, SystemData: &esystem.CombinedData{}}) ++ _ = conn.WriteMessage(gws.OpcodeBinary, response) ++ } ++} ++ ++// timelineScale shrinks the poll schedule so the test stays fast while keeping ++// the production ratio between poll interval, request timeout and read deadline. ++const timelineScale = 100 ++ ++// A slow agent must survive repeated failed polls. The ping in update() only ++// happens once the fetch gives up, which is interval + wsDataRequestTimeout into ++// the cycle, so the read deadline has to outlast that. With a deadline below ++// that sum the connection is already closed when the ping would go out, which is ++// the reconnect loop from #2294. ++func TestSlowAgentKeepsConnectionAcrossPolls(t *testing.T) { ++ tick := time.Duration(interval) * time.Millisecond / timelineScale ++ ++ tests := []struct { ++ name string ++ deadline time.Duration ++ wantConnected bool ++ }{ ++ {"production deadline outlasts a failed poll", ws.Deadline() / timelineScale, true}, ++ // 70s was the old value and sits below the 90s a failed poll needs. ++ {"deadline below interval plus request timeout", 70 * time.Second / timelineScale, false}, ++ } ++ ++ for _, tc := range tests { ++ t.Run(tc.name, func(t *testing.T) { ++ previousDeadline := ws.SetDeadline(tc.deadline) ++ t.Cleanup(func() { ws.SetDeadline(previousDeadline) }) ++ previousTimeout := wsDataRequestTimeout ++ wsDataRequestTimeout = 30 * time.Second / timelineScale ++ t.Cleanup(func() { wsDataRequestTimeout = previousTimeout }) ++ ++ connections := make(chan *ws.WsConn, 1) ++ // The real handler: OnClose has to run, or a dropped connection ++ // would still look connected. ++ upgrader := gws.NewUpgrader(&ws.Handler{}, &gws.ServerOption{}) ++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ++ conn, err := upgrader.Upgrade(w, r) ++ if err != nil { ++ t.Error(err) ++ return ++ } ++ wsConn := ws.NewWsConnection(conn, semver.MustParse("0.20.0")) ++ conn.Session().Store("wsConn", wsConn) ++ connections <- wsConn ++ conn.ReadLoop() ++ })) ++ t.Cleanup(server.Close) ++ ++ client := &silentAfterFirstPollAgent{} ++ conn, _, err := gws.NewClient(client, &gws.ClientOption{Addr: "ws" + strings.TrimPrefix(server.URL, "http")}) ++ require.NoError(t, err) ++ t.Cleanup(func() { _ = conn.NetConn().Close() }) ++ go conn.ReadLoop() ++ ++ var sys *System ++ select { ++ case wsConn := <-connections: ++ sys = &System{WsConn: wsConn} ++ case <-time.After(3 * time.Second): ++ t.Fatal("websocket connection was not established") ++ } ++ ++ // A healthy poll. Its response is what last resets the deadline, so ++ // it is the point the schedule below is measured from. ++ _, err = sys.fetchDataFromAgent(common.DataRequestOptions{}) ++ require.NoError(t, err, "the first poll must succeed") ++ pollZero := time.Now() ++ ++ // Two failed polls: the first shows the ping lands, the second shows ++ // the ping keeps re-arming the deadline. ++ for poll := 1; poll <= 2; poll++ { ++ time.Sleep(time.Until(pollZero.Add(time.Duration(poll) * tick))) ++ if !sys.WsConn.IsConnected() { ++ break ++ } ++ require.Error(t, sys.update(), "a silent agent must fail the poll") ++ } ++ ++ require.Equal(t, tc.wantConnected, sys.WsConn.IsConnected()) ++ }) ++ } ++} +diff --git a/internal/hub/ws/ws.go b/internal/hub/ws/ws.go +index 7d61e596..6b268a3b 100644 +--- a/internal/hub/ws/ws.go ++++ b/internal/hub/ws/ws.go +@@ -16,9 +16,14 @@ import ( + "github.com/lxzan/gws" + ) + +-const ( +- deadline = 70 * time.Second +-) ++// deadline bounds how long a connection may go without traffic from the agent. ++// ++// It has to outlast a whole failed poll: the updater polls every interval (60s) ++// and a fetch gives up after wsDataRequestTimeout (30s), so nothing can reset ++// the deadline before 90s into a stalled cycle. A shorter deadline expires ++// mid-collection, and by the time the failed fetch pings, the connection is ++// already closed. 100s keeps the same 10s margin the poll interval used to have. ++var deadline = 100 * time.Second + + // Handler implements the WebSocket event handler for agent connections. + type Handler struct { +diff --git a/internal/hub/ws/ws_test.go b/internal/hub/ws/ws_test.go +index 9970cf47..caa53b34 100644 +--- a/internal/hub/ws/ws_test.go ++++ b/internal/hub/ws/ws_test.go +@@ -170,9 +170,15 @@ func TestFingerprintRecord(t *testing.T) { + assert.Equal(t, "test-token", record.Token) + } + +-// TestDeadlineConstant tests that the deadline constant is reasonable ++// TestDeadlineConstant tests that the deadline is reasonable. ++// ++// It has to stay above the 90s a failed poll takes in the systems package (a ++// 60s poll interval plus a 30s request timeout), because the keepalive ping ++// only goes out once that fetch gives up. Lowering this reopens the reconnect ++// loop from #2294; TestSlowAgentKeepsConnectionAcrossPolls covers the effect. + func TestDeadlineConstant(t *testing.T) { +- assert.Equal(t, 70*time.Second, deadline, "Deadline should be 70 seconds") ++ assert.Equal(t, 100*time.Second, deadline, "Deadline should be 100 seconds") ++ assert.Greater(t, deadline, 90*time.Second, "Deadline must outlast a failed poll") + } + + // TestCommonActions tests that the common actions are properly defined +diff --git a/internal/hub/ws/ws_test_helpers.go b/internal/hub/ws/ws_test_helpers.go +index ac52c779..aaf49dc9 100644 +--- a/internal/hub/ws/ws_test_helpers.go ++++ b/internal/hub/ws/ws_test_helpers.go +@@ -2,9 +2,22 @@ + + package ws + ++import "time" ++ + // GetPendingCount returns the number of pending requests (for monitoring) + func (rm *RequestManager) GetPendingCount() int { + rm.RLock() + defer rm.RUnlock() + return len(rm.pendingReqs) + } ++ ++// TESTING ONLY: Deadline reports the connection read deadline. ++func Deadline() time.Duration { return deadline } ++ ++// TESTING ONLY: SetDeadline overrides the connection read deadline so tests can ++// drive the poll schedule at a reduced scale. It returns the previous value. ++func SetDeadline(d time.Duration) time.Duration { ++ previous := deadline ++ deadline = d ++ return previous ++} diff --git a/tasks/henrygd__beszel-2435/solution/solve.sh b/tasks/henrygd__beszel-2435/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2435/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/henrygd__beszel-2435/task.toml b/tasks/henrygd__beszel-2435/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..54442e90c11c9ce8aa5dc4b2fac551f4830a8e5d --- /dev/null +++ b/tasks/henrygd__beszel-2435/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2435" +description = "fix(hub): ping a slow agent so its connection survives between polls" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "4fe1a0a7a42f655564e0b1577a2bc0dd74af8f58" +reference = "https://github.com/henrygd/beszel/pull/2435" +source_access = "auto" +built_at = "2026-11-16T16:09:53.414491+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:22b421cd0e0040c00810a8044f5ee942606dd7affea9b21583f09054c1eb8adb" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-09T14:51:43Z" +diff_format = "unified" +context_files = [ + "internal/hub/systems/system.go", + "internal/hub/systems/ws_data_timeout_test.go", + "internal/hub/ws/ws.go", + "internal/hub/ws/ws_test.go", + "internal/hub/ws/ws_test_helpers.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 232 +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:00.824370+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:920a68c513c2578d7d3ea68ab663a2ba1a46b5627c9da73ff3368a10bda6ba35" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2435/tests/capture.py b/tasks/henrygd__beszel-2435/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2435/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/henrygd__beszel-2435/tests/instruction.md b/tasks/henrygd__beszel-2435/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..24542e8f4a8f68578e2f6226e9b235169ec46da9 --- /dev/null +++ b/tasks/henrygd__beszel-2435/tests/instruction.md @@ -0,0 +1,51 @@ +# Issue + +**Title:** fix(hub): ping a slow agent so its connection survives between polls + +## Description + +## 📃 Description + +. + +This is on top of 8bf6917f, not instead of it. That commit stops `fetchDataFromAgent` from *closing* the connection when the stats request times out. The connection still goes away, just later and by a different route: `ws.deadline` was 70s and only a message arriving **from** the agent pushes it out. + +| | | +|---|---| +| poll interval | 60s (`interval`) | +| data request timeout | 30s (`wsDataRequestTimeout`) | +| hub read deadline | 70s → 100s (`ws.deadline`) | + +Measured from a healthy poll at t=0, whose response is what last reset the deadline: + +1. t=60s the next poll sends its request, the agent is collecting and stays silent, +2. t=70s the read deadline expires and the hub closes the connection, 10s into the collection, +3. t=90s the fetch gives up. + +The agent reconnects, starts collecting slowly again, and the cycle repeats. + +Two changes, and both are needed: + +**`update()` pings the agent when a fetch fails** and the connection is still up. That is the same move `handlePaused` already makes for a paused system, and `Ping()` pushes the deadline out as it sends, so it works without an answer. The system is still reported down, because that comes from the error `update()` returns; only the connection survives, so recovery costs no reconnect. + +**The read deadline goes from 70s to 100s.** The ping only happens once the fetch gives up, at interval + request timeout = 90s, so the deadline has to outlast that or the ping never goes out. The deadline alone is not enough either: while fetches keep failing nothing resets it, and the connection would die 100s after the last message instead of 70s. With both, each failed poll re-arms the deadline. 100s keeps the same 10s margin the old 70s had over the poll interval. + +`deadline` became a `var` so the test can drive the schedule at a reduced scale. Only the testing-tagged helper writes it. + +One thing I did not touch: the agent handles hub requests on its read loop, so while it is collecting it cannot answer a ping at all. That is why the fix works from the hub's side without needing a reply. + +## 🪵 Changelog + +### 🔧 Fixed + +- Slow agents no longer get disconnected and reconnected in a loop when collection outlasts the hub's read deadline (#2294) + +## 🧪 Test plan + +`TestSlowAgentKeepsConnectionAcrossPolls` in `internal/hub/systems/ws_data_timeout_test.go` runs the real poll schedule at 1/100 against an agent that answers once, then goes silent and never answers a ping. It fails with either half reverted: with the deadline back at 70s, and with the ping removed from `update()`. Both checked. `TestUpdatePingsAgentAfterFailedFetch` covers the ping on a failed fetch directly. + +Rebased on `upstream/main` at e01e2a20. `make test` is green, `go vet` clean, and `internal/hub/systems` and `internal/hub/ws` also pass under `-race`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4fe1a0a7a42f`. 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/henrygd__beszel-2435/tests/oracle.patch b/tasks/henrygd__beszel-2435/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3a545f8391dc237a1cd6367cea7949bfbe53c3dc --- /dev/null +++ b/tasks/henrygd__beszel-2435/tests/oracle.patch @@ -0,0 +1,295 @@ +diff --git a/internal/hub/systems/system.go b/internal/hub/systems/system.go +index 0a292668..57d0f199 100644 +--- a/internal/hub/systems/system.go ++++ b/internal/hub/systems/system.go +@@ -174,6 +174,26 @@ func (sys *System) update() error { + + data, err := sys.fetchDataFromAgent(options) + if err != nil { ++ // Keep the WebSocket alive even though this fetch failed. ++ // ++ // Only a message from the agent resets the read deadline, and an agent ++ // still collecting sends nothing. Without this ping the deadline expires ++ // between polls, the hub closes the connection, the agent reconnects, ++ // collects slowly again, and the cycle repeats. Pinging here is the same ++ // move handlePaused already makes for a paused system, and Ping() pushes ++ // the deadline out as it sends, so it works without an answer, which ++ // matters because a collecting agent cannot answer. ++ // ++ // This is why the deadline has to exceed interval + wsDataRequestTimeout: ++ // the ping only happens once the fetch gives up. See ws.deadline. ++ // ++ // The system is still reported down: that comes from the error we ++ // return. Only the connection survives, so recovery costs no reconnect. ++ // A failed ping needs no handling either, since a connection that ++ // cannot be pinged runs into its deadline anyway. ++ if sys.WsConn != nil && sys.WsConn.IsConnected() { ++ _ = sys.WsConn.Ping() ++ } + return err + } + +diff --git a/internal/hub/systems/ws_data_timeout_test.go b/internal/hub/systems/ws_data_timeout_test.go +index ae6720fd..a8a019c4 100644 +--- a/internal/hub/systems/ws_data_timeout_test.go ++++ b/internal/hub/systems/ws_data_timeout_test.go +@@ -7,6 +7,7 @@ import ( + "net/http" + "net/http/httptest" + "strings" ++ "sync/atomic" + "testing" + "time" + +@@ -80,3 +81,180 @@ func TestFetchDataTimeoutKeepsWebSocketOpen(t *testing.T) { + _, err = sys.fetchDataFromAgent(common.DataRequestOptions{}) + require.NoError(t, err) + } ++ ++// pingCountingClient never answers GetData and records the pings it receives, ++// standing in for an agent whose collection outlasts the request timeout. ++type pingCountingClient struct { ++ gws.BuiltinEventHandler ++ pings chan struct{} ++} ++ ++func (c *pingCountingClient) OnPing(conn *gws.Conn, payload []byte) { ++ _ = conn.WritePong(payload) ++ select { ++ case c.pings <- struct{}{}: ++ default: ++ } ++} ++ ++func (c *pingCountingClient) OnMessage(conn *gws.Conn, message *gws.Message) { ++ // Swallow the request: this agent is still collecting. ++ message.Close() ++} ++ ++// A slow agent used to be disconnected between polls. The fetch gives up after ++// wsDataRequestTimeout, but the hub's read deadline is longer and only traffic ++// from the agent resets it, so nothing kept the connection alive in between. ++// update() now pings on a failed fetch, which is what breaks the reconnect ++// loop reported in #2294. ++func TestUpdatePingsAgentAfterFailedFetch(t *testing.T) { ++ originalTimeout := wsDataRequestTimeout ++ wsDataRequestTimeout = 50 * time.Millisecond ++ t.Cleanup(func() { wsDataRequestTimeout = originalTimeout }) ++ ++ connections := make(chan *ws.WsConn, 1) ++ upgrader := gws.NewUpgrader(&monitorSyncServer{}, nil) ++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ++ conn, err := upgrader.Upgrade(w, r) ++ if err != nil { ++ t.Error(err) ++ return ++ } ++ wsConn := ws.NewWsConnection(conn, semver.MustParse("0.20.0")) ++ conn.Session().Store("wsConn", wsConn) ++ connections <- wsConn ++ conn.ReadLoop() ++ })) ++ t.Cleanup(server.Close) ++ ++ client := &pingCountingClient{pings: make(chan struct{}, 4)} ++ conn, _, err := gws.NewClient(client, &gws.ClientOption{Addr: "ws" + strings.TrimPrefix(server.URL, "http")}) ++ require.NoError(t, err) ++ t.Cleanup(func() { _ = conn.NetConn().Close() }) ++ go conn.ReadLoop() ++ ++ var sys *System ++ select { ++ case wsConn := <-connections: ++ sys = &System{WsConn: wsConn} ++ case <-time.After(3 * time.Second): ++ t.Fatal("websocket connection was not established") ++ } ++ ++ err = sys.update() ++ require.ErrorIs(t, err, context.DeadlineExceeded, "the fetch is expected to time out") ++ ++ select { ++ case <-client.pings: ++ case <-time.After(3 * time.Second): ++ t.Fatal("a failed fetch must ping the agent to keep the connection alive") ++ } ++ ++ require.True(t, sys.WsConn.IsConnected(), "the connection must survive a failed fetch") ++} ++ ++// silentAfterFirstPollAgent answers the first GetData and then goes quiet, ++// modelling an agent whose collection outlasts the request timeout. It never ++// answers a ping, because a real agent serves hub requests on its read loop and ++// cannot reply while it is collecting. The fix therefore has to work without an ++// answer, which it does: Ping() pushes the deadline out as it sends. ++type silentAfterFirstPollAgent struct { ++ gws.BuiltinEventHandler ++ answered atomic.Bool ++} ++ ++func (c *silentAfterFirstPollAgent) OnPing(*gws.Conn, []byte) {} ++ ++func (c *silentAfterFirstPollAgent) OnMessage(conn *gws.Conn, message *gws.Message) { ++ defer message.Close() ++ var req common.HubRequest[cbor.RawMessage] ++ if err := cbor.Unmarshal(message.Bytes(), &req); err != nil || req.Action != common.GetData { ++ return ++ } ++ if c.answered.CompareAndSwap(false, true) { ++ response, _ := cbor.Marshal(common.AgentResponse{Id: req.Id, SystemData: &esystem.CombinedData{}}) ++ _ = conn.WriteMessage(gws.OpcodeBinary, response) ++ } ++} ++ ++// timelineScale shrinks the poll schedule so the test stays fast while keeping ++// the production ratio between poll interval, request timeout and read deadline. ++const timelineScale = 100 ++ ++// A slow agent must survive repeated failed polls. The ping in update() only ++// happens once the fetch gives up, which is interval + wsDataRequestTimeout into ++// the cycle, so the read deadline has to outlast that. With a deadline below ++// that sum the connection is already closed when the ping would go out, which is ++// the reconnect loop from #2294. ++func TestSlowAgentKeepsConnectionAcrossPolls(t *testing.T) { ++ tick := time.Duration(interval) * time.Millisecond / timelineScale ++ ++ tests := []struct { ++ name string ++ deadline time.Duration ++ wantConnected bool ++ }{ ++ {"production deadline outlasts a failed poll", ws.Deadline() / timelineScale, true}, ++ // 70s was the old value and sits below the 90s a failed poll needs. ++ {"deadline below interval plus request timeout", 70 * time.Second / timelineScale, false}, ++ } ++ ++ for _, tc := range tests { ++ t.Run(tc.name, func(t *testing.T) { ++ previousDeadline := ws.SetDeadline(tc.deadline) ++ t.Cleanup(func() { ws.SetDeadline(previousDeadline) }) ++ previousTimeout := wsDataRequestTimeout ++ wsDataRequestTimeout = 30 * time.Second / timelineScale ++ t.Cleanup(func() { wsDataRequestTimeout = previousTimeout }) ++ ++ connections := make(chan *ws.WsConn, 1) ++ // The real handler: OnClose has to run, or a dropped connection ++ // would still look connected. ++ upgrader := gws.NewUpgrader(&ws.Handler{}, &gws.ServerOption{}) ++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ++ conn, err := upgrader.Upgrade(w, r) ++ if err != nil { ++ t.Error(err) ++ return ++ } ++ wsConn := ws.NewWsConnection(conn, semver.MustParse("0.20.0")) ++ conn.Session().Store("wsConn", wsConn) ++ connections <- wsConn ++ conn.ReadLoop() ++ })) ++ t.Cleanup(server.Close) ++ ++ client := &silentAfterFirstPollAgent{} ++ conn, _, err := gws.NewClient(client, &gws.ClientOption{Addr: "ws" + strings.TrimPrefix(server.URL, "http")}) ++ require.NoError(t, err) ++ t.Cleanup(func() { _ = conn.NetConn().Close() }) ++ go conn.ReadLoop() ++ ++ var sys *System ++ select { ++ case wsConn := <-connections: ++ sys = &System{WsConn: wsConn} ++ case <-time.After(3 * time.Second): ++ t.Fatal("websocket connection was not established") ++ } ++ ++ // A healthy poll. Its response is what last resets the deadline, so ++ // it is the point the schedule below is measured from. ++ _, err = sys.fetchDataFromAgent(common.DataRequestOptions{}) ++ require.NoError(t, err, "the first poll must succeed") ++ pollZero := time.Now() ++ ++ // Two failed polls: the first shows the ping lands, the second shows ++ // the ping keeps re-arming the deadline. ++ for poll := 1; poll <= 2; poll++ { ++ time.Sleep(time.Until(pollZero.Add(time.Duration(poll) * tick))) ++ if !sys.WsConn.IsConnected() { ++ break ++ } ++ require.Error(t, sys.update(), "a silent agent must fail the poll") ++ } ++ ++ require.Equal(t, tc.wantConnected, sys.WsConn.IsConnected()) ++ }) ++ } ++} +diff --git a/internal/hub/ws/ws.go b/internal/hub/ws/ws.go +index 7d61e596..6b268a3b 100644 +--- a/internal/hub/ws/ws.go ++++ b/internal/hub/ws/ws.go +@@ -16,9 +16,14 @@ import ( + "github.com/lxzan/gws" + ) + +-const ( +- deadline = 70 * time.Second +-) ++// deadline bounds how long a connection may go without traffic from the agent. ++// ++// It has to outlast a whole failed poll: the updater polls every interval (60s) ++// and a fetch gives up after wsDataRequestTimeout (30s), so nothing can reset ++// the deadline before 90s into a stalled cycle. A shorter deadline expires ++// mid-collection, and by the time the failed fetch pings, the connection is ++// already closed. 100s keeps the same 10s margin the poll interval used to have. ++var deadline = 100 * time.Second + + // Handler implements the WebSocket event handler for agent connections. + type Handler struct { +diff --git a/internal/hub/ws/ws_test.go b/internal/hub/ws/ws_test.go +index 9970cf47..caa53b34 100644 +--- a/internal/hub/ws/ws_test.go ++++ b/internal/hub/ws/ws_test.go +@@ -170,9 +170,15 @@ func TestFingerprintRecord(t *testing.T) { + assert.Equal(t, "test-token", record.Token) + } + +-// TestDeadlineConstant tests that the deadline constant is reasonable ++// TestDeadlineConstant tests that the deadline is reasonable. ++// ++// It has to stay above the 90s a failed poll takes in the systems package (a ++// 60s poll interval plus a 30s request timeout), because the keepalive ping ++// only goes out once that fetch gives up. Lowering this reopens the reconnect ++// loop from #2294; TestSlowAgentKeepsConnectionAcrossPolls covers the effect. + func TestDeadlineConstant(t *testing.T) { +- assert.Equal(t, 70*time.Second, deadline, "Deadline should be 70 seconds") ++ assert.Equal(t, 100*time.Second, deadline, "Deadline should be 100 seconds") ++ assert.Greater(t, deadline, 90*time.Second, "Deadline must outlast a failed poll") + } + + // TestCommonActions tests that the common actions are properly defined +diff --git a/internal/hub/ws/ws_test_helpers.go b/internal/hub/ws/ws_test_helpers.go +index ac52c779..aaf49dc9 100644 +--- a/internal/hub/ws/ws_test_helpers.go ++++ b/internal/hub/ws/ws_test_helpers.go +@@ -2,9 +2,22 @@ + + package ws + ++import "time" ++ + // GetPendingCount returns the number of pending requests (for monitoring) + func (rm *RequestManager) GetPendingCount() int { + rm.RLock() + defer rm.RUnlock() + return len(rm.pendingReqs) + } ++ ++// TESTING ONLY: Deadline reports the connection read deadline. ++func Deadline() time.Duration { return deadline } ++ ++// TESTING ONLY: SetDeadline overrides the connection read deadline so tests can ++// drive the poll schedule at a reduced scale. It returns the previous value. ++func SetDeadline(d time.Duration) time.Duration { ++ previous := deadline ++ deadline = d ++ return previous ++} diff --git a/tasks/henrygd__beszel-2435/tests/test.sh b/tasks/henrygd__beszel-2435/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d5e0d4fd5aaaf40060961a37bdae5f6267fdb567 --- /dev/null +++ b/tasks/henrygd__beszel-2435/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 4fe1a0a7a42f655564e0b1577a2bc0dd74af8f58 > "$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/henrygd__beszel-2435/tests/verifier.py b/tasks/henrygd__beszel-2435/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2435/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/henrygd__beszel-2448/environment/Dockerfile b/tasks/henrygd__beszel-2448/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c491e76c3d2abae9cbf4a79251d72411731e0a75 --- /dev/null +++ b/tasks/henrygd__beszel-2448/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 65f00ae119269113613a39028b7a935693b860e6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 65f00ae119269113613a39028b7a935693b860e6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 65f00ae119269113613a39028b7a935693b860e6 \ + && 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/henrygd__beszel-2448/instruction.md b/tasks/henrygd__beszel-2448/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f2ae69c40d7de977a7ee18d0c768461ea605dfab --- /dev/null +++ b/tasks/henrygd__beszel-2448/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(hub): preserve custom DNS resolvers when syncing monitors + +## Description + +Full monitor synchronisation omitted the DNS `server` field, so an agent reconnect switched custom DNS checks back to its default resolver. Include the saved server in the query used by full synchronisation. + +Extend the SSH reconnect test to cover custom DNS, default DNS and TCP configurations through initial sync, reconnect and retry. The regression fails before the fix and passes afterwards. Focused race tests, the affected hub and records packages, `go vet` and the Makefile hub build pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `65f00ae11926`. 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/henrygd__beszel-2448/solution/patch.diff b/tasks/henrygd__beszel-2448/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0c933278963253ab93b3e56a09d964cca7d8d091 --- /dev/null +++ b/tasks/henrygd__beszel-2448/solution/patch.diff @@ -0,0 +1,83 @@ +diff --git a/internal/hub/systems/network_monitor_ssh_test.go b/internal/hub/systems/network_monitor_ssh_test.go +index b733daf7..c825c37d 100644 +--- a/internal/hub/systems/network_monitor_ssh_test.go ++++ b/internal/hub/systems/network_monitor_ssh_test.go +@@ -100,9 +100,23 @@ func TestSSHNetworkMonitorReconnectSync(t *testing.T) { + }() + collection, err := app.FindCachedCollectionByNameOrId("network_monitors") + require.NoError(t, err) +- probe := core.NewRecord(collection) +- probe.Load(map[string]any{"system": sys.Id, "target": "localhost", "protocol": "tcp", "port": 80, "interval": 60, "enabled": true}) +- require.NoError(t, app.SaveNoValidate(probe)) ++ configs := []monitor.Config{ ++ {Target: "localhost", Protocol: "tcp", Port: 80, Interval: 60}, ++ {Target: "localhost", Protocol: "dns", Interval: 60}, ++ {Target: "localhost", Protocol: "dns", Server: "127.0.0.1:5353", Interval: 60}, ++ } ++ var probes []*core.Record ++ for i := range configs { ++ cfg := &configs[i] ++ probe := core.NewRecord(collection) ++ probe.Load(map[string]any{ ++ "system": sys.Id, "target": cfg.Target, "protocol": cfg.Protocol, ++ "port": cfg.Port, "server": cfg.Server, "interval": cfg.Interval, "enabled": true, ++ }) ++ require.NoError(t, app.SaveNoValidate(probe)) ++ cfg.ID = probe.Id ++ probes = append(probes, probe) ++ } + fetch := func() { + t.Helper() + _, err := sys.fetchDataFromAgent(common.DataRequestOptions{}) +@@ -120,7 +134,7 @@ func TestSSHNetworkMonitorReconnectSync(t *testing.T) { + } + } + fetch() +- require.Equal(t, probe.Id, receive().Configs[0].ID) ++ require.ElementsMatch(t, configs, receive().Configs) + require.False(t, sys.monitorsNeedSync.Load()) + fetch() + require.Empty(t, requests, "steady-state fetch must not resync") +@@ -128,22 +142,24 @@ func TestSSHNetworkMonitorReconnectSync(t *testing.T) { + // Simulate loss of the agent process/connection and its in-memory monitors. + require.NoError(t, sys.client.Load().Close()) + fetch() +- require.Equal(t, probe.Id, receive().Configs[0].ID) ++ require.ElementsMatch(t, configs, receive().Configs) + require.False(t, sys.monitorsNeedSync.Load()) + + // Failed replacements are retried on the next successful stats fetch. + require.NoError(t, sys.client.Load().Close()) + failSync.Store(true) + fetch() +- receive() ++ require.ElementsMatch(t, configs, receive().Configs) + require.True(t, sys.monitorsNeedSync.Load()) + failSync.Store(false) + fetch() +- receive() ++ require.ElementsMatch(t, configs, receive().Configs) + require.False(t, sys.monitorsNeedSync.Load()) + +- probe.Set("enabled", false) +- require.NoError(t, app.SaveNoValidate(probe)) ++ for _, probe := range probes { ++ probe.Set("enabled", false) ++ require.NoError(t, app.SaveNoValidate(probe)) ++ } + require.NoError(t, sys.client.Load().Close()) + fetch() + require.Empty(t, receive().Configs, "empty replacement must clear stale monitors") +diff --git a/internal/hub/systems/system_manager.go b/internal/hub/systems/system_manager.go +index 642b5868..4e65ed55 100644 +--- a/internal/hub/systems/system_manager.go ++++ b/internal/hub/systems/system_manager.go +@@ -380,7 +380,7 @@ func (sm *SystemManager) resetFailedSmartFetchState(systemID string) { + func (sm *SystemManager) GetMonitorConfigsForSystem(systemID string) ([]monitor.Config, error) { + var configs []monitor.Config + err := sm.hub.DB(). +- NewQuery("SELECT id, target, protocol, port, interval FROM network_monitors WHERE system = {:system} AND enabled = true"). ++ NewQuery("SELECT id, target, protocol, port, interval, server FROM network_monitors WHERE system = {:system} AND enabled = true"). + Bind(dbx.Params{"system": systemID}). + All(&configs) + return configs, err diff --git a/tasks/henrygd__beszel-2448/solution/solve.sh b/tasks/henrygd__beszel-2448/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2448/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/henrygd__beszel-2448/task.toml b/tasks/henrygd__beszel-2448/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..49ad48428cde21f4a6567c1cc2267c017f56e827 --- /dev/null +++ b/tasks/henrygd__beszel-2448/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2448" +description = "fix(hub): preserve custom DNS resolvers when syncing monitors" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "65f00ae119269113613a39028b7a935693b860e6" +reference = "https://github.com/henrygd/beszel/pull/2448" +source_access = "auto" +built_at = "2026-11-16T16:09:53.474680+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7fbe76cff9185ea631628579221fe0ae52763b84e031524bb418ad12b9553176" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T22:49:44Z" +diff_format = "unified" +context_files = [ + "internal/hub/systems/network_monitor_ssh_test.go", + "internal/hub/systems/system_manager.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 36 +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:00.824868+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d6e5769e8c4318cc71a1c0fcd74d8f70f0d08689cfb4e5c6064eb2e21988f11f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2448/tests/capture.py b/tasks/henrygd__beszel-2448/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2448/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/henrygd__beszel-2448/tests/instruction.md b/tasks/henrygd__beszel-2448/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f2ae69c40d7de977a7ee18d0c768461ea605dfab --- /dev/null +++ b/tasks/henrygd__beszel-2448/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(hub): preserve custom DNS resolvers when syncing monitors + +## Description + +Full monitor synchronisation omitted the DNS `server` field, so an agent reconnect switched custom DNS checks back to its default resolver. Include the saved server in the query used by full synchronisation. + +Extend the SSH reconnect test to cover custom DNS, default DNS and TCP configurations through initial sync, reconnect and retry. The regression fails before the fix and passes afterwards. Focused race tests, the affected hub and records packages, `go vet` and the Makefile hub build pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `65f00ae11926`. 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/henrygd__beszel-2448/tests/oracle.patch b/tasks/henrygd__beszel-2448/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0c933278963253ab93b3e56a09d964cca7d8d091 --- /dev/null +++ b/tasks/henrygd__beszel-2448/tests/oracle.patch @@ -0,0 +1,83 @@ +diff --git a/internal/hub/systems/network_monitor_ssh_test.go b/internal/hub/systems/network_monitor_ssh_test.go +index b733daf7..c825c37d 100644 +--- a/internal/hub/systems/network_monitor_ssh_test.go ++++ b/internal/hub/systems/network_monitor_ssh_test.go +@@ -100,9 +100,23 @@ func TestSSHNetworkMonitorReconnectSync(t *testing.T) { + }() + collection, err := app.FindCachedCollectionByNameOrId("network_monitors") + require.NoError(t, err) +- probe := core.NewRecord(collection) +- probe.Load(map[string]any{"system": sys.Id, "target": "localhost", "protocol": "tcp", "port": 80, "interval": 60, "enabled": true}) +- require.NoError(t, app.SaveNoValidate(probe)) ++ configs := []monitor.Config{ ++ {Target: "localhost", Protocol: "tcp", Port: 80, Interval: 60}, ++ {Target: "localhost", Protocol: "dns", Interval: 60}, ++ {Target: "localhost", Protocol: "dns", Server: "127.0.0.1:5353", Interval: 60}, ++ } ++ var probes []*core.Record ++ for i := range configs { ++ cfg := &configs[i] ++ probe := core.NewRecord(collection) ++ probe.Load(map[string]any{ ++ "system": sys.Id, "target": cfg.Target, "protocol": cfg.Protocol, ++ "port": cfg.Port, "server": cfg.Server, "interval": cfg.Interval, "enabled": true, ++ }) ++ require.NoError(t, app.SaveNoValidate(probe)) ++ cfg.ID = probe.Id ++ probes = append(probes, probe) ++ } + fetch := func() { + t.Helper() + _, err := sys.fetchDataFromAgent(common.DataRequestOptions{}) +@@ -120,7 +134,7 @@ func TestSSHNetworkMonitorReconnectSync(t *testing.T) { + } + } + fetch() +- require.Equal(t, probe.Id, receive().Configs[0].ID) ++ require.ElementsMatch(t, configs, receive().Configs) + require.False(t, sys.monitorsNeedSync.Load()) + fetch() + require.Empty(t, requests, "steady-state fetch must not resync") +@@ -128,22 +142,24 @@ func TestSSHNetworkMonitorReconnectSync(t *testing.T) { + // Simulate loss of the agent process/connection and its in-memory monitors. + require.NoError(t, sys.client.Load().Close()) + fetch() +- require.Equal(t, probe.Id, receive().Configs[0].ID) ++ require.ElementsMatch(t, configs, receive().Configs) + require.False(t, sys.monitorsNeedSync.Load()) + + // Failed replacements are retried on the next successful stats fetch. + require.NoError(t, sys.client.Load().Close()) + failSync.Store(true) + fetch() +- receive() ++ require.ElementsMatch(t, configs, receive().Configs) + require.True(t, sys.monitorsNeedSync.Load()) + failSync.Store(false) + fetch() +- receive() ++ require.ElementsMatch(t, configs, receive().Configs) + require.False(t, sys.monitorsNeedSync.Load()) + +- probe.Set("enabled", false) +- require.NoError(t, app.SaveNoValidate(probe)) ++ for _, probe := range probes { ++ probe.Set("enabled", false) ++ require.NoError(t, app.SaveNoValidate(probe)) ++ } + require.NoError(t, sys.client.Load().Close()) + fetch() + require.Empty(t, receive().Configs, "empty replacement must clear stale monitors") +diff --git a/internal/hub/systems/system_manager.go b/internal/hub/systems/system_manager.go +index 642b5868..4e65ed55 100644 +--- a/internal/hub/systems/system_manager.go ++++ b/internal/hub/systems/system_manager.go +@@ -380,7 +380,7 @@ func (sm *SystemManager) resetFailedSmartFetchState(systemID string) { + func (sm *SystemManager) GetMonitorConfigsForSystem(systemID string) ([]monitor.Config, error) { + var configs []monitor.Config + err := sm.hub.DB(). +- NewQuery("SELECT id, target, protocol, port, interval FROM network_monitors WHERE system = {:system} AND enabled = true"). ++ NewQuery("SELECT id, target, protocol, port, interval, server FROM network_monitors WHERE system = {:system} AND enabled = true"). + Bind(dbx.Params{"system": systemID}). + All(&configs) + return configs, err diff --git a/tasks/henrygd__beszel-2448/tests/test.sh b/tasks/henrygd__beszel-2448/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..092b9ca2038eb748475172238eebac10a4bd623e --- /dev/null +++ b/tasks/henrygd__beszel-2448/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 65f00ae119269113613a39028b7a935693b860e6 > "$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/henrygd__beszel-2448/tests/verifier.py b/tasks/henrygd__beszel-2448/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2448/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/henrygd__beszel-2449/environment/Dockerfile b/tasks/henrygd__beszel-2449/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a4db6dd19bafe29c6c10abffcd8bc5c74f4c012b --- /dev/null +++ b/tasks/henrygd__beszel-2449/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1ab38e57c59c470ae579caa268b7d9dcdbda95ba 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1ab38e57c59c470ae579caa268b7d9dcdbda95ba \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1ab38e57c59c470ae579caa268b7d9dcdbda95ba \ + && 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/henrygd__beszel-2449/instruction.md b/tasks/henrygd__beszel-2449/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c21429d9fdcd576a17d2cc11fb8d76eb6340d089 --- /dev/null +++ b/tasks/henrygd__beszel-2449/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(hub): scope monitor result writes to the reporting system + +## Description + +Monitor results were written using agent-supplied IDs without checking their system, allowing a report to change another system's monitor and insert history with mismatched relations. Load the reporting system's monitor IDs inside the existing transaction and use that set for current results and history. Ignore foreign or removed IDs while preserving valid results in the same report. + +Two-system regressions cover PocketBase/realtime and direct SQL writes, certificates, nonexistent IDs, changed ownership, disabled owned monitors and rollback on lookup failure. They fail before the fix and pass afterwards. Focused race tests, the affected hub and records packages, `go vet` and the Makefile hub build pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1ab38e57c59c`. 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/henrygd__beszel-2449/solution/patch.diff b/tasks/henrygd__beszel-2449/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a8fc06d66eec3939532b8b06f0da67b3a58e4851 --- /dev/null +++ b/tasks/henrygd__beszel-2449/solution/patch.diff @@ -0,0 +1,222 @@ +diff --git a/internal/hub/systems/network_monitor_stats_test.go b/internal/hub/systems/network_monitor_stats_test.go +index f3b1572d..a7e8e6b7 100644 +--- a/internal/hub/systems/network_monitor_stats_test.go ++++ b/internal/hub/systems/network_monitor_stats_test.go +@@ -3,6 +3,7 @@ + package systems + + import ( ++ "encoding/json" + "fmt" + "testing" + "time" +@@ -16,6 +17,112 @@ import ( + "github.com/stretchr/testify/require" + ) + ++func TestNetworkMonitorResultOwnership(t *testing.T) { ++ for _, realtime := range []bool{false, true} { ++ t.Run(fmt.Sprintf("realtime=%t", realtime), func(t *testing.T) { ++ sys, app := newTestSystemWithHub(t) ++ if realtime { ++ client := subscriptions.NewDefaultClient() ++ client.Subscribe("network_monitors/*") ++ app.SubscriptionsBroker().Register(client) ++ t.Cleanup(func() { app.SubscriptionsBroker().Unregister(client.Id()) }) ++ } ++ systems, err := app.FindCachedCollectionByNameOrId("systems") ++ require.NoError(t, err) ++ foreignSystem := core.NewRecord(systems) ++ require.NoError(t, app.SaveNoValidate(foreignSystem)) ++ other := &System{Id: foreignSystem.Id, manager: sys.manager} ++ collection, err := app.FindCachedCollectionByNameOrId("network_monitors") ++ require.NoError(t, err) ++ for _, cfg := range []struct { ++ id, system string ++ enabled bool ++ }{ ++ {"owned", sys.Id, true}, ++ {"disabled", sys.Id, false}, ++ {"foreign", other.Id, true}, ++ } { ++ record := core.NewRecord(collection) ++ record.Id = cfg.id ++ record.Load(map[string]any{"system": cfg.system, "enabled": cfg.enabled}) ++ require.NoError(t, app.SaveNoValidate(record)) ++ } ++ // Establish a legitimate result and history for the other system. ++ _, err = other.createRecords(&system.CombinedData{Monitors: map[string]monitor.Result{ ++ "foreign": {LastProbeAt: 1000, AvgResponse: 77, TotalCount: 1, SuccessCount: 1, ResponseSum: 77}, ++ }}) ++ require.NoError(t, err) ++ snapshot := func(id string) []byte { ++ t.Helper() ++ record, err := app.FindRecordById("network_monitors", id) ++ require.NoError(t, err) ++ data, err := json.Marshal(record) ++ require.NoError(t, err) ++ return data ++ } ++ before := snapshot("foreign") ++ result := monitor.Result{ ++ LastProbeAt: 2000, AvgResponse: 22, AvgResponse1h: 33, ++ MinResponse1h: 11, MaxResponse1h: 44, PacketLoss1h: 50, ++ TotalCount: 2, SuccessCount: 1, ResponseSum: 22, ++ Cert: &monitor.CertInfo{Expires: 1_800_000_000_000, Issuer: "Test CA"}, ++ } ++ data := &system.CombinedData{Monitors: map[string]monitor.Result{ ++ "owned": result, "disabled": result, "foreign": result, "nonexistent": result, ++ }} ++ for range 2 { // Repeated results must remain deduplicated. ++ _, err = sys.createRecords(data) ++ require.NoError(t, err) ++ } ++ assert.JSONEq(t, string(before), string(snapshot("foreign"))) ++ assert.Equal(t, map[string]int64{"owned": 2000, "disabled": 2000}, sys.lastSavedMonitorProbe) ++ assert.Len(t, data.Monitors, 4, "ingestion must not mutate the shared telemetry payload") ++ for _, id := range []string{"owned", "disabled"} { ++ record, err := app.FindRecordById("network_monitors", id) ++ require.NoError(t, err) ++ assert.EqualValues(t, result.AvgResponse, record.GetInt("res")) ++ assert.EqualValues(t, result.AvgResponse1h, record.GetInt("resAvg1h")) ++ var cert monitor.CertInfo ++ require.NoError(t, record.UnmarshalJSONField("certInfo", &cert)) ++ assert.Equal(t, *result.Cert, cert) ++ } ++ stats, err := app.FindAllRecords("network_monitor_stats") ++ require.NoError(t, err) ++ assert.Len(t, stats, 3) ++ for _, stat := range stats { ++ record, err := app.FindRecordById("network_monitors", stat.GetString("monitor")) ++ require.NoError(t, err) ++ assert.Equal(t, record.GetString("system"), stat.GetString("system")) ++ if record.Id == "foreign" { ++ assert.Equal(t, 77, stat.GetInt("res_sum")) ++ } else { ++ assert.Equal(t, 22, stat.GetInt("res_sum")) ++ } ++ } ++ ++ // Ownership must be read afresh, even for IDs with saved probe markers. ++ moved, err := app.FindRecordById("network_monitors", "owned") ++ require.NoError(t, err) ++ moved.Set("system", other.Id) ++ require.NoError(t, app.SaveNoValidate(moved)) ++ movedBefore := snapshot("owned") ++ for id, result := range data.Monitors { ++ result.LastProbeAt = 3000 ++ result.AvgResponse = 999 ++ data.Monitors[id] = result ++ } ++ _, err = sys.createRecords(data) ++ require.NoError(t, err) ++ assert.JSONEq(t, string(movedBefore), string(snapshot("owned"))) ++ assert.JSONEq(t, string(before), string(snapshot("foreign"))) ++ count, err := app.CountRecords("network_monitor_stats") ++ require.NoError(t, err) ++ assert.EqualValues(t, 4, count, "only the still-owned disabled monitor gets another sample") ++ assert.Equal(t, map[string]int64{"owned": 2000, "disabled": 3000}, sys.lastSavedMonitorProbe) ++ }) ++ } ++} ++ + func TestNetworkMonitorProbePruning(t *testing.T) { + for _, tc := range []struct { + name string +diff --git a/internal/hub/systems/system.go b/internal/hub/systems/system.go +index 49d1f5d6..55a5878f 100644 +--- a/internal/hub/systems/system.go ++++ b/internal/hub/systems/system.go +@@ -2,6 +2,7 @@ package systems + + import ( + "context" ++ "database/sql" + "encoding/json" + "errors" + "fmt" +@@ -433,7 +434,6 @@ func (sys *System) updateNetworkMonitorsRecords(app core.App, monitorResults map + if len(monitorResults) == 0 { + return nil + } +- var err error + systemId := sys.Id + const monitorCollectionName = "network_monitors" + +@@ -457,14 +457,19 @@ func (sys *System) updateNetworkMonitorsRecords(app core.App, monitorResults map + } + // Results omit certInfo unless it changed, so keep the stored value. + setClauses = append(setClauses, "certInfo=COALESCE({:certInfo}, certInfo)") +- queryString := fmt.Sprintf("UPDATE %s SET %s WHERE id={:id}", monitorCollectionName, strings.Join(setClauses, ", ")) ++ queryString := fmt.Sprintf("UPDATE %s SET %s WHERE id={:id} AND system={:system}", monitorCollectionName, strings.Join(setClauses, ", ")) + updateQuery = db.NewQuery(queryString) + } + ++ // Results are keyed by agent-supplied IDs. Record history only for monitors ++ // this system owns, as confirmed by the update below ++ owned := make(map[string]struct{}, len(monitorResults)) ++ + // update network_monitors records + for id, result := range monitorResults { + monitorData := map[string]any{ + "id": id, ++ "system": systemId, + "res": result.AvgResponse, + "resAvg1h": result.AvgResponse1h, + "resMin1h": result.MinResponse1h, +@@ -472,11 +477,15 @@ func (sys *System) updateNetworkMonitorsRecords(app core.App, monitorResults map + "loss1h": result.PacketLoss1h, + "updated": nowString, + } ++ var err error + switch realtimeActive { + case true: + var record *core.Record + record, err = app.FindRecordById(monitorCollectionName, id) + if err == nil { ++ if record.GetString("system") != systemId { ++ continue ++ } + if result.Cert != nil { + monitorData["certInfo"] = result.Cert + } +@@ -492,12 +501,20 @@ func (sys *System) updateNetworkMonitorsRecords(app core.App, monitorResults map + } + } + if err == nil { +- _, err = updateQuery.Bind(dbx.Params(monitorData)).Execute() ++ var res sql.Result ++ // Zero rows means the monitor is foreign or no longer exists. ++ if res, err = updateQuery.Bind(dbx.Params(monitorData)).Execute(); err == nil { ++ if n, _ := res.RowsAffected(); n == 0 { ++ continue ++ } ++ } + } + } + if err != nil { + app.Logger().Warn("Failed to update monitor", "system", systemId, "monitor", id, "err", err) ++ continue + } ++ owned[id] = struct{}{} + } + + // handle stats collection — one record per monitor +@@ -509,6 +526,9 @@ func (sys *System) updateNetworkMonitorsRecords(app core.App, monitorResults map + } + + for monitorId, result := range monitorResults { ++ if _, ok := owned[monitorId]; !ok { ++ continue ++ } + // Compare identity, not ordering, so agent clock changes don't stall writes. + if result.LastProbeAt == sys.lastSavedMonitorProbe[monitorId] { + continue +@@ -524,6 +544,7 @@ func (sys *System) updateNetworkMonitorsRecords(app core.App, monitorResults map + "success_count": result.SuccessCount, + "res_sum": result.ResponseSum, + } ++ var err error + switch realtimeActive { + case true: + record := core.NewRecord(statsCollection) diff --git a/tasks/henrygd__beszel-2449/solution/solve.sh b/tasks/henrygd__beszel-2449/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2449/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/henrygd__beszel-2449/task.toml b/tasks/henrygd__beszel-2449/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6650b3eb8db1c7db6255377d56418427abff5def --- /dev/null +++ b/tasks/henrygd__beszel-2449/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2449" +description = "fix(hub): scope monitor result writes to the reporting system" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "1ab38e57c59c470ae579caa268b7d9dcdbda95ba" +reference = "https://github.com/henrygd/beszel/pull/2449" +source_access = "auto" +built_at = "2026-11-16T16:09:53.462824+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f22e4535c0211f36fb4bfaf3489706f983ef40289c2a01558ca889a677d7d41e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-29T13:41:50Z" +diff_format = "unified" +context_files = [ + "internal/hub/systems/network_monitor_stats_test.go", + "internal/hub/systems/system.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 134 +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:00.825348+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:13f7015466a6465ad748a566baf4624c32299576ff1f1b0696cf3c1c5d3979da" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2449/tests/capture.py b/tasks/henrygd__beszel-2449/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2449/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/henrygd__beszel-2449/tests/instruction.md b/tasks/henrygd__beszel-2449/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c21429d9fdcd576a17d2cc11fb8d76eb6340d089 --- /dev/null +++ b/tasks/henrygd__beszel-2449/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(hub): scope monitor result writes to the reporting system + +## Description + +Monitor results were written using agent-supplied IDs without checking their system, allowing a report to change another system's monitor and insert history with mismatched relations. Load the reporting system's monitor IDs inside the existing transaction and use that set for current results and history. Ignore foreign or removed IDs while preserving valid results in the same report. + +Two-system regressions cover PocketBase/realtime and direct SQL writes, certificates, nonexistent IDs, changed ownership, disabled owned monitors and rollback on lookup failure. They fail before the fix and pass afterwards. Focused race tests, the affected hub and records packages, `go vet` and the Makefile hub build pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1ab38e57c59c`. 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/henrygd__beszel-2449/tests/oracle.patch b/tasks/henrygd__beszel-2449/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a8fc06d66eec3939532b8b06f0da67b3a58e4851 --- /dev/null +++ b/tasks/henrygd__beszel-2449/tests/oracle.patch @@ -0,0 +1,222 @@ +diff --git a/internal/hub/systems/network_monitor_stats_test.go b/internal/hub/systems/network_monitor_stats_test.go +index f3b1572d..a7e8e6b7 100644 +--- a/internal/hub/systems/network_monitor_stats_test.go ++++ b/internal/hub/systems/network_monitor_stats_test.go +@@ -3,6 +3,7 @@ + package systems + + import ( ++ "encoding/json" + "fmt" + "testing" + "time" +@@ -16,6 +17,112 @@ import ( + "github.com/stretchr/testify/require" + ) + ++func TestNetworkMonitorResultOwnership(t *testing.T) { ++ for _, realtime := range []bool{false, true} { ++ t.Run(fmt.Sprintf("realtime=%t", realtime), func(t *testing.T) { ++ sys, app := newTestSystemWithHub(t) ++ if realtime { ++ client := subscriptions.NewDefaultClient() ++ client.Subscribe("network_monitors/*") ++ app.SubscriptionsBroker().Register(client) ++ t.Cleanup(func() { app.SubscriptionsBroker().Unregister(client.Id()) }) ++ } ++ systems, err := app.FindCachedCollectionByNameOrId("systems") ++ require.NoError(t, err) ++ foreignSystem := core.NewRecord(systems) ++ require.NoError(t, app.SaveNoValidate(foreignSystem)) ++ other := &System{Id: foreignSystem.Id, manager: sys.manager} ++ collection, err := app.FindCachedCollectionByNameOrId("network_monitors") ++ require.NoError(t, err) ++ for _, cfg := range []struct { ++ id, system string ++ enabled bool ++ }{ ++ {"owned", sys.Id, true}, ++ {"disabled", sys.Id, false}, ++ {"foreign", other.Id, true}, ++ } { ++ record := core.NewRecord(collection) ++ record.Id = cfg.id ++ record.Load(map[string]any{"system": cfg.system, "enabled": cfg.enabled}) ++ require.NoError(t, app.SaveNoValidate(record)) ++ } ++ // Establish a legitimate result and history for the other system. ++ _, err = other.createRecords(&system.CombinedData{Monitors: map[string]monitor.Result{ ++ "foreign": {LastProbeAt: 1000, AvgResponse: 77, TotalCount: 1, SuccessCount: 1, ResponseSum: 77}, ++ }}) ++ require.NoError(t, err) ++ snapshot := func(id string) []byte { ++ t.Helper() ++ record, err := app.FindRecordById("network_monitors", id) ++ require.NoError(t, err) ++ data, err := json.Marshal(record) ++ require.NoError(t, err) ++ return data ++ } ++ before := snapshot("foreign") ++ result := monitor.Result{ ++ LastProbeAt: 2000, AvgResponse: 22, AvgResponse1h: 33, ++ MinResponse1h: 11, MaxResponse1h: 44, PacketLoss1h: 50, ++ TotalCount: 2, SuccessCount: 1, ResponseSum: 22, ++ Cert: &monitor.CertInfo{Expires: 1_800_000_000_000, Issuer: "Test CA"}, ++ } ++ data := &system.CombinedData{Monitors: map[string]monitor.Result{ ++ "owned": result, "disabled": result, "foreign": result, "nonexistent": result, ++ }} ++ for range 2 { // Repeated results must remain deduplicated. ++ _, err = sys.createRecords(data) ++ require.NoError(t, err) ++ } ++ assert.JSONEq(t, string(before), string(snapshot("foreign"))) ++ assert.Equal(t, map[string]int64{"owned": 2000, "disabled": 2000}, sys.lastSavedMonitorProbe) ++ assert.Len(t, data.Monitors, 4, "ingestion must not mutate the shared telemetry payload") ++ for _, id := range []string{"owned", "disabled"} { ++ record, err := app.FindRecordById("network_monitors", id) ++ require.NoError(t, err) ++ assert.EqualValues(t, result.AvgResponse, record.GetInt("res")) ++ assert.EqualValues(t, result.AvgResponse1h, record.GetInt("resAvg1h")) ++ var cert monitor.CertInfo ++ require.NoError(t, record.UnmarshalJSONField("certInfo", &cert)) ++ assert.Equal(t, *result.Cert, cert) ++ } ++ stats, err := app.FindAllRecords("network_monitor_stats") ++ require.NoError(t, err) ++ assert.Len(t, stats, 3) ++ for _, stat := range stats { ++ record, err := app.FindRecordById("network_monitors", stat.GetString("monitor")) ++ require.NoError(t, err) ++ assert.Equal(t, record.GetString("system"), stat.GetString("system")) ++ if record.Id == "foreign" { ++ assert.Equal(t, 77, stat.GetInt("res_sum")) ++ } else { ++ assert.Equal(t, 22, stat.GetInt("res_sum")) ++ } ++ } ++ ++ // Ownership must be read afresh, even for IDs with saved probe markers. ++ moved, err := app.FindRecordById("network_monitors", "owned") ++ require.NoError(t, err) ++ moved.Set("system", other.Id) ++ require.NoError(t, app.SaveNoValidate(moved)) ++ movedBefore := snapshot("owned") ++ for id, result := range data.Monitors { ++ result.LastProbeAt = 3000 ++ result.AvgResponse = 999 ++ data.Monitors[id] = result ++ } ++ _, err = sys.createRecords(data) ++ require.NoError(t, err) ++ assert.JSONEq(t, string(movedBefore), string(snapshot("owned"))) ++ assert.JSONEq(t, string(before), string(snapshot("foreign"))) ++ count, err := app.CountRecords("network_monitor_stats") ++ require.NoError(t, err) ++ assert.EqualValues(t, 4, count, "only the still-owned disabled monitor gets another sample") ++ assert.Equal(t, map[string]int64{"owned": 2000, "disabled": 3000}, sys.lastSavedMonitorProbe) ++ }) ++ } ++} ++ + func TestNetworkMonitorProbePruning(t *testing.T) { + for _, tc := range []struct { + name string +diff --git a/internal/hub/systems/system.go b/internal/hub/systems/system.go +index 49d1f5d6..55a5878f 100644 +--- a/internal/hub/systems/system.go ++++ b/internal/hub/systems/system.go +@@ -2,6 +2,7 @@ package systems + + import ( + "context" ++ "database/sql" + "encoding/json" + "errors" + "fmt" +@@ -433,7 +434,6 @@ func (sys *System) updateNetworkMonitorsRecords(app core.App, monitorResults map + if len(monitorResults) == 0 { + return nil + } +- var err error + systemId := sys.Id + const monitorCollectionName = "network_monitors" + +@@ -457,14 +457,19 @@ func (sys *System) updateNetworkMonitorsRecords(app core.App, monitorResults map + } + // Results omit certInfo unless it changed, so keep the stored value. + setClauses = append(setClauses, "certInfo=COALESCE({:certInfo}, certInfo)") +- queryString := fmt.Sprintf("UPDATE %s SET %s WHERE id={:id}", monitorCollectionName, strings.Join(setClauses, ", ")) ++ queryString := fmt.Sprintf("UPDATE %s SET %s WHERE id={:id} AND system={:system}", monitorCollectionName, strings.Join(setClauses, ", ")) + updateQuery = db.NewQuery(queryString) + } + ++ // Results are keyed by agent-supplied IDs. Record history only for monitors ++ // this system owns, as confirmed by the update below ++ owned := make(map[string]struct{}, len(monitorResults)) ++ + // update network_monitors records + for id, result := range monitorResults { + monitorData := map[string]any{ + "id": id, ++ "system": systemId, + "res": result.AvgResponse, + "resAvg1h": result.AvgResponse1h, + "resMin1h": result.MinResponse1h, +@@ -472,11 +477,15 @@ func (sys *System) updateNetworkMonitorsRecords(app core.App, monitorResults map + "loss1h": result.PacketLoss1h, + "updated": nowString, + } ++ var err error + switch realtimeActive { + case true: + var record *core.Record + record, err = app.FindRecordById(monitorCollectionName, id) + if err == nil { ++ if record.GetString("system") != systemId { ++ continue ++ } + if result.Cert != nil { + monitorData["certInfo"] = result.Cert + } +@@ -492,12 +501,20 @@ func (sys *System) updateNetworkMonitorsRecords(app core.App, monitorResults map + } + } + if err == nil { +- _, err = updateQuery.Bind(dbx.Params(monitorData)).Execute() ++ var res sql.Result ++ // Zero rows means the monitor is foreign or no longer exists. ++ if res, err = updateQuery.Bind(dbx.Params(monitorData)).Execute(); err == nil { ++ if n, _ := res.RowsAffected(); n == 0 { ++ continue ++ } ++ } + } + } + if err != nil { + app.Logger().Warn("Failed to update monitor", "system", systemId, "monitor", id, "err", err) ++ continue + } ++ owned[id] = struct{}{} + } + + // handle stats collection — one record per monitor +@@ -509,6 +526,9 @@ func (sys *System) updateNetworkMonitorsRecords(app core.App, monitorResults map + } + + for monitorId, result := range monitorResults { ++ if _, ok := owned[monitorId]; !ok { ++ continue ++ } + // Compare identity, not ordering, so agent clock changes don't stall writes. + if result.LastProbeAt == sys.lastSavedMonitorProbe[monitorId] { + continue +@@ -524,6 +544,7 @@ func (sys *System) updateNetworkMonitorsRecords(app core.App, monitorResults map + "success_count": result.SuccessCount, + "res_sum": result.ResponseSum, + } ++ var err error + switch realtimeActive { + case true: + record := core.NewRecord(statsCollection) diff --git a/tasks/henrygd__beszel-2449/tests/test.sh b/tasks/henrygd__beszel-2449/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..879a0928bac3d35fea4570224c28b75fd66d907c --- /dev/null +++ b/tasks/henrygd__beszel-2449/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 1ab38e57c59c470ae579caa268b7d9dcdbda95ba > "$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/henrygd__beszel-2449/tests/verifier.py b/tasks/henrygd__beszel-2449/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2449/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/henrygd__beszel-2450/environment/Dockerfile b/tasks/henrygd__beszel-2450/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f5036d8ef1971162ff18ad1ee131b9e5ce256f7e --- /dev/null +++ b/tasks/henrygd__beszel-2450/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 24881fbfdf3feba4567e41dc011ea283716873ee 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 24881fbfdf3feba4567e41dc011ea283716873ee \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 24881fbfdf3feba4567e41dc011ea283716873ee \ + && 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/henrygd__beszel-2450/instruction.md b/tasks/henrygd__beszel-2450/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c750d302189b6b6f581ebe82f570f9b619bea624 --- /dev/null +++ b/tasks/henrygd__beszel-2450/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** fix(hub): honour SSH request cancellation + +## Description + +SSH detail and monitor-sync requests can remain blocked after their caller's context expires. The existing timeout covers opening a session, but not the handshake, shell acknowledgement, request write, response read or exit wait. + +Use context-aware dialling and close the captured connection on cancellation so blocked operations unwind and return the context error. Synchronise client access and remove only the failed connection, preserving a replacement created by another request. Cancelling also closes other sessions on that connection; subsequent requests can reconnect. Closing only the session cannot reliably unblock an unresponsive peer. + +Loopback tests cover deadlines and cancellation at each SSH phase, concurrent requests, cleanup and reconnection. Later-phase deadline tests establish SSH first; handshake cancellation is covered separately. The transport package passes under the race detector on Linux AMD64 and ARM64, including three repetitions on ARM64. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `24881fbfdf3f`. 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/henrygd__beszel-2450/solution/patch.diff b/tasks/henrygd__beszel-2450/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..281a31a1fb30fd723a88206b4fe0760e097db410 --- /dev/null +++ b/tasks/henrygd__beszel-2450/solution/patch.diff @@ -0,0 +1,545 @@ +diff --git a/internal/hub/transport/ssh.go b/internal/hub/transport/ssh.go +index 840c5564..1a2491ae 100644 +--- a/internal/hub/transport/ssh.go ++++ b/internal/hub/transport/ssh.go +@@ -7,6 +7,7 @@ import ( + "io" + "net" + "strings" ++ "sync" + "time" + + "github.com/blang/semver" +@@ -17,6 +18,7 @@ import ( + + // SSHTransport implements Transport over SSH connections. + type SSHTransport struct { ++ mu sync.Mutex + client *ssh.Client + config *ssh.ClientConfig + host string +@@ -51,33 +53,57 @@ func NewSSHTransport(cfg SSHTransportConfig) *SSHTransport { + + // SetClient sets the SSH client for reuse across requests. + func (t *SSHTransport) SetClient(client *ssh.Client) { ++ t.mu.Lock() ++ defer t.mu.Unlock() + t.client = client + } + + // SetAgentVersion sets the agent version (extracted from SSH handshake). + func (t *SSHTransport) SetAgentVersion(version semver.Version) { ++ t.mu.Lock() ++ defer t.mu.Unlock() + t.agentVersion = version + } + + // GetClient returns the current SSH client (for connection management). + func (t *SSHTransport) GetClient() *ssh.Client { ++ t.mu.Lock() ++ defer t.mu.Unlock() + return t.client + } + + // GetAgentVersion returns the agent version. + func (t *SSHTransport) GetAgentVersion() semver.Version { ++ t.mu.Lock() ++ defer t.mu.Unlock() + return t.agentVersion + } + + // Request sends a request to the agent via SSH and unmarshals the response. +-func (t *SSHTransport) Request(ctx context.Context, action common.WebSocketAction, req any, dest any) error { +- if t.client == nil { +- if err := t.connect(); err != nil { +- return err +- } ++func (t *SSHTransport) Request(ctx context.Context, action common.WebSocketAction, req any, dest any) (err error) { ++ if err := ctx.Err(); err != nil { ++ return err ++ } ++ client, err := t.connect(ctx) ++ if err != nil { ++ return err + } + +- session, err := t.createSessionWithTimeout(ctx) ++ // Closing only the session still depends on the peer processing SSH packets. ++ // Close the captured connection to release every blocked read/write, including ++ // concurrent sessions; subsequent requests can reconnect. ++ stop := closeOnCancellation(ctx, func() { t.closeClient(client) }) ++ defer func() { ++ stop() ++ if err != nil && ctx.Err() != nil { ++ err = ctx.Err() ++ } ++ if isConnectionError(err) { ++ t.closeClient(client) ++ } ++ }() ++ ++ session, err := t.createSessionWithTimeout(ctx, client) + if err != nil { + return err + } +@@ -121,21 +147,48 @@ func (t *SSHTransport) Request(ctx context.Context, action common.WebSocketActio + + // IsConnected returns true if the SSH connection is active. + func (t *SSHTransport) IsConnected() bool { +- return t.client != nil ++ return t.GetClient() != nil + } + + // Close terminates the SSH connection. + func (t *SSHTransport) Close() { +- if t.client != nil { +- t.client.Close() ++ t.closeClient(t.GetClient()) ++} ++ ++// closeClient removes only the connection owned by the completed request. ++func (t *SSHTransport) closeClient(client *ssh.Client) { ++ t.mu.Lock() ++ if t.client == client { + t.client = nil + } ++ t.mu.Unlock() ++ if client != nil { ++ client.Close() ++ } ++} ++ ++// closeOnCancellation stops I/O when ctx is cancelled. The returned function ++// waits for any in-progress close so it cannot outlive the operation. ++func closeOnCancellation(ctx context.Context, closeConn func()) func() { ++ done := make(chan struct{}) ++ stop := context.AfterFunc(ctx, func() { ++ closeConn() ++ close(done) ++ }) ++ return func() { ++ if !stop() { ++ <-done ++ } ++ } + } + +-// connect establishes a new SSH connection. +-func (t *SSHTransport) connect() error { ++// connect reuses the current client or establishes a cancellable SSH connection. ++func (t *SSHTransport) connect(ctx context.Context) (*ssh.Client, error) { ++ if client := t.GetClient(); client != nil { ++ return client, nil ++ } + if t.config == nil { +- return errors.New("SSH config not set") ++ return nil, errors.New("SSH config not set") + } + + network := "tcp" +@@ -146,46 +199,50 @@ func (t *SSHTransport) connect() error { + host = net.JoinHostPort(host, t.port) + } + +- client, err := ssh.Dial(network, host, t.config) ++ dialer := net.Dialer{Timeout: t.config.Timeout} ++ conn, err := dialer.DialContext(ctx, network, host) + if err != nil { +- return err ++ return nil, err + } +- t.client = client ++ stop := closeOnCancellation(ctx, func() { conn.Close() }) ++ sshConn, chans, reqs, err := ssh.NewClientConn(conn, host, t.config) ++ stop() ++ if ctx.Err() != nil { ++ conn.Close() ++ return nil, ctx.Err() ++ } ++ if err != nil { ++ conn.Close() ++ return nil, err ++ } ++ client := ssh.NewClient(sshConn, chans, reqs) + +- // Extract agent version from server version string ++ t.mu.Lock() ++ if existing := t.client; existing != nil { ++ t.mu.Unlock() ++ client.Close() ++ return existing, nil ++ } ++ t.client = client + t.agentVersion, _ = extractAgentVersion(string(client.Conn.ServerVersion())) +- return nil ++ t.mu.Unlock() ++ return client, nil + } + +-// createSessionWithTimeout creates a new SSH session with a timeout. +-func (t *SSHTransport) createSessionWithTimeout(ctx context.Context) (*ssh.Session, error) { +- if t.client == nil { +- return nil, errors.New("client not initialized") +- } +- ++// createSessionWithTimeout bounds session creation independently of the request. ++func (t *SSHTransport) createSessionWithTimeout(ctx context.Context, client *ssh.Client) (*ssh.Session, error) { + ctx, cancel := context.WithTimeout(ctx, t.timeout) + defer cancel() +- +- sessionChan := make(chan *ssh.Session, 1) +- errChan := make(chan error, 1) +- +- go func() { +- session, err := t.client.NewSession() +- if err != nil { +- errChan <- err +- } else { +- sessionChan <- session ++ stop := closeOnCancellation(ctx, func() { t.closeClient(client) }) ++ session, err := client.NewSession() ++ stop() ++ if ctx.Err() != nil { ++ if session != nil { ++ session.Close() + } +- }() +- +- select { +- case session := <-sessionChan: +- return session, nil +- case err := <-errChan: +- return nil, err +- case <-ctx.Done(): +- return nil, errors.New("timeout creating session") ++ return nil, ctx.Err() + } ++ return session, err + } + + // extractAgentVersion extracts the beszel version from SSH server version string. +@@ -206,7 +263,6 @@ func (t *SSHTransport) RequestWithRetry(ctx context.Context, action common.WebSo + + // Check if it's a connection error that warrants a retry + if isConnectionError(err) && attempt < retries { +- t.Close() + continue + } + return err +diff --git a/internal/hub/transport/ssh_test.go b/internal/hub/transport/ssh_test.go +new file mode 100644 +index 00000000..98be4c2d +--- /dev/null ++++ b/internal/hub/transport/ssh_test.go +@@ -0,0 +1,311 @@ ++package transport ++ ++import ( ++ "context" ++ "crypto/ed25519" ++ "crypto/rand" ++ "io" ++ "net" ++ "strings" ++ "sync" ++ "sync/atomic" ++ "testing" ++ "time" ++ ++ "github.com/fxamacker/cbor/v2" ++ "github.com/henrygd/beszel/internal/common" ++ "github.com/stretchr/testify/require" ++ "golang.org/x/crypto/ssh" ++) ++ ++// newSSHTestTransport starts a loopback SSH server that stalls the first ++// connection at the given stage; later connections behave normally so tests ++// can verify reconnection. ++func newSSHTestTransport(t *testing.T, stage string) (*SSHTransport, <-chan struct{}, <-chan struct{}) { ++ t.Helper() ++ _, key, err := ed25519.GenerateKey(rand.Reader) ++ require.NoError(t, err) ++ signer, err := ssh.NewSignerFromKey(key) ++ require.NoError(t, err) ++ config := &ssh.ServerConfig{NoClientAuth: true, ServerVersion: "SSH-2.0-beszel_0.20.0"} ++ config.AddHostKey(signer) ++ listener, err := net.Listen("tcp", "127.0.0.1:0") ++ require.NoError(t, err) ++ host, port, err := net.SplitHostPort(listener.Addr().String()) ++ require.NoError(t, err) ++ transport := NewSSHTransport(SSHTransportConfig{ ++ Host: host, Port: port, Timeout: 2 * time.Second, ++ Config: &ssh.ClientConfig{User: "test", HostKeyCallback: ssh.FixedHostKey(signer.PublicKey()), Timeout: time.Second}, ++ }) ++ reached, closed := make(chan struct{}), make(chan struct{}) ++ var once sync.Once ++ var connections atomic.Int32 ++ var mu sync.Mutex ++ conns := map[net.Conn]bool{} ++ var wg sync.WaitGroup ++ wg.Add(1) ++ go func() { ++ defer wg.Done() ++ for { ++ conn, err := listener.Accept() ++ if err != nil { ++ return ++ } ++ mu.Lock() ++ conns[conn] = true ++ mu.Unlock() ++ first := connections.Add(1) == 1 ++ wg.Add(1) ++ go func() { ++ defer wg.Done() ++ defer conn.Close() ++ if first { ++ defer close(closed) ++ } ++ if first && stage == "handshake" { ++ close(reached) ++ _, _ = io.Copy(io.Discard, conn) ++ return ++ } ++ server, channels, requests, err := ssh.NewServerConn(conn, config) ++ if err != nil { ++ return ++ } ++ defer server.Close() ++ go ssh.DiscardRequests(requests) ++ disconnected := make(chan struct{}) ++ go func() { _ = server.Wait(); close(disconnected) }() ++ for channel := range channels { ++ wg.Add(1) ++ go func() { ++ defer wg.Done() ++ stall := func(at string) bool { ++ if !first || stage != at { ++ return false ++ } ++ once.Do(func() { close(reached) }) ++ <-disconnected ++ return true ++ } ++ if stall("session") { ++ return ++ } ++ ch, requests, err := channel.Accept() ++ if err != nil { ++ return ++ } ++ defer ch.Close() ++ for request := range requests { ++ if request.Type != "shell" { ++ _ = request.Reply(false, nil) ++ continue ++ } ++ if stall("shell") { ++ return ++ } ++ _ = request.Reply(true, nil) ++ if stall("write") { ++ return ++ } ++ var req common.HubRequest[cbor.RawMessage] ++ if cbor.NewDecoder(ch).Decode(&req) != nil || stall("response") { ++ return ++ } ++ if stage == "slow-response" { ++ select { ++ case <-time.After(250 * time.Millisecond): ++ case <-disconnected: ++ return ++ } ++ } ++ data, _ := cbor.Marshal("control response") ++ if cbor.NewEncoder(ch).Encode(common.AgentResponse{Data: data}) != nil || stall("exit") { ++ return ++ } ++ _, _ = ch.SendRequest("exit-status", false, ssh.Marshal(struct{ Status uint32 }{0})) ++ return ++ } ++ }() ++ } ++ }() ++ } ++ }() ++ t.Cleanup(func() { ++ listener.Close() ++ transport.Close() ++ mu.Lock() ++ for conn := range conns { ++ conn.Close() ++ } ++ mu.Unlock() ++ done := make(chan struct{}) ++ go func() { wg.Wait(); close(done) }() ++ select { ++ case <-done: ++ case <-time.After(3 * time.Second): ++ t.Error("SSH server did not stop") ++ } ++ }) ++ return transport, reached, closed ++} ++ ++func TestSSHRequestCancellation(t *testing.T) { ++ for _, stage := range []string{"handshake", "session", "shell", "write", "response", "exit"} { ++ for _, cancellation := range []string{"deadline", "cancel"} { ++ t.Run(stage+"/"+cancellation, func(t *testing.T) { ++ transport, reached, closed := newSSHTestTransport(t, stage) ++ var req any ++ if stage == "write" { ++ // Larger than the SSH receive window, so an unread write blocks. ++ req = strings.Repeat("x", 4<<20) ++ } ++ ctx, cancel := context.WithCancel(t.Context()) ++ if cancellation == "deadline" { ++ cancel() ++ // Handshake has its own deadline case. Complete it before ++ // timing the later SSH phases on slower hosts. ++ if stage != "handshake" { ++ setupCtx, stopSetup := context.WithTimeout(t.Context(), 2*time.Second) ++ _, err := transport.connect(setupCtx) ++ stopSetup() ++ require.NoError(t, err) ++ } ++ ctx, cancel = context.WithTimeout(t.Context(), 250*time.Millisecond) ++ } ++ defer cancel() ++ done := make(chan error, 1) ++ result := "unchanged" ++ go func() { done <- transport.RequestWithRetry(ctx, common.GetContainerLogs, req, &result, 1) }() ++ select { ++ case <-reached: ++ case <-time.After(2 * time.Second): ++ t.Fatal("request did not reach stalled phase") ++ } ++ want := context.DeadlineExceeded ++ if cancellation == "cancel" { ++ want = context.Canceled ++ cancel() ++ } ++ select { ++ case err := <-done: ++ require.ErrorIs(t, err, want) ++ case <-time.After(2 * time.Second): ++ t.Fatal("request ignored cancellation") ++ } ++ require.Equal(t, "unchanged", result) ++ require.False(t, transport.IsConnected()) ++ select { ++ case <-closed: ++ case <-time.After(time.Second): ++ t.Fatal("cancelled request left its connection open") ++ } ++ require.NoError(t, transport.Request(t.Context(), common.GetContainerLogs, nil, &result)) ++ require.Equal(t, "control response", result) ++ }) ++ } ++ } ++} ++ ++func TestSSHSessionTimeout(t *testing.T) { ++ transport, _, _ := newSSHTestTransport(t, "session") ++ transport.timeout = 50 * time.Millisecond ++ ctx, cancel := context.WithTimeout(t.Context(), time.Second) ++ defer cancel() ++ var result string ++ require.ErrorIs(t, transport.Request(ctx, common.GetContainerLogs, nil, &result), context.DeadlineExceeded) ++ require.NoError(t, ctx.Err(), "the session timeout must fire before the caller's deadline") ++ require.False(t, transport.IsConnected()) ++} ++ ++func TestSSHRequestAlreadyCancelled(t *testing.T) { ++ transport := NewSSHTransport(SSHTransportConfig{}) ++ ctx, cancel := context.WithCancel(t.Context()) ++ cancel() ++ var result string ++ require.ErrorIs(t, transport.Request(ctx, common.GetContainerLogs, nil, &result), context.Canceled) ++} ++ ++func TestSSHSlowResponse(t *testing.T) { ++ transport, _, _ := newSSHTestTransport(t, "slow-response") ++ transport.timeout = 100 * time.Millisecond ++ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) ++ defer cancel() ++ var result string ++ require.NoError(t, transport.Request(ctx, common.GetContainerLogs, nil, &result)) ++ require.Equal(t, "control response", result, "session timeout must not shorten the request deadline") ++} ++ ++func TestSSHConcurrentRequests(t *testing.T) { ++ transport, _, _ := newSSHTestTransport(t, "") ++ var wg sync.WaitGroup ++ for range 10 { ++ wg.Go(func() { ++ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) ++ defer cancel() ++ var result string ++ if err := transport.Request(ctx, common.GetContainerLogs, nil, &result); err != nil { ++ t.Error(err) ++ } else if result != "control response" { ++ t.Errorf("unexpected response %q", result) ++ } ++ }) ++ } ++ wg.Wait() ++ client := transport.GetClient() ++ require.NotNil(t, client) ++ ctx, cancel := context.WithCancel(t.Context()) ++ var result string ++ require.NoError(t, transport.Request(ctx, common.GetContainerLogs, nil, &result)) ++ cancel() ++ // Cancelling a completed request must not close the reused connection. ++ require.NoError(t, transport.Request(t.Context(), common.GetContainerLogs, nil, &result)) ++ require.Same(t, client, transport.GetClient()) ++ // The existing retry contract still replaces an unusable connection. ++ require.NoError(t, client.Close()) ++ require.NoError(t, transport.RequestWithRetry(t.Context(), common.GetContainerLogs, nil, &result, 1)) ++ require.NotSame(t, client, transport.GetClient()) ++} ++ ++func TestSSHCancelledSharedConnection(t *testing.T) { ++ transport, reached, _ := newSSHTestTransport(t, "response") ++ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) ++ defer cancel() ++ client, err := transport.connect(ctx) ++ require.NoError(t, err) ++ // Keep another session on the shared connection waiting for an exit. ++ session, err := client.NewSession() ++ require.NoError(t, err) ++ require.NoError(t, session.Shell()) ++ waiting := make(chan error, 1) ++ go func() { waiting <- session.Wait() }() ++ requestCtx, cancelRequest := context.WithCancel(ctx) ++ defer cancelRequest() ++ done := make(chan error, 1) ++ var result string ++ go func() { done <- transport.Request(requestCtx, common.GetContainerLogs, nil, &result) }() ++ select { ++ case <-reached: ++ case <-ctx.Done(): ++ t.Fatal("request did not reach the response read") ++ } ++ cancelRequest() ++ select { ++ case err := <-done: ++ require.ErrorIs(t, err, context.Canceled) ++ case <-ctx.Done(): ++ t.Fatal("request ignored cancellation") ++ } ++ select { ++ case err := <-waiting: ++ require.Error(t, err, "closing the shared client must release other sessions") ++ case <-ctx.Done(): ++ t.Fatal("concurrent session remained blocked") ++ } ++ require.NoError(t, transport.Request(ctx, common.GetContainerLogs, nil, &result)) ++ replacement := transport.GetClient() ++ require.NotSame(t, client, replacement) ++ // Late cleanup of the old connection must not discard its replacement. ++ transport.closeClient(client) ++ require.Same(t, replacement, transport.GetClient()) ++ require.NoError(t, transport.Request(ctx, common.GetContainerLogs, nil, &result)) ++} diff --git a/tasks/henrygd__beszel-2450/solution/solve.sh b/tasks/henrygd__beszel-2450/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2450/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/henrygd__beszel-2450/task.toml b/tasks/henrygd__beszel-2450/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..63d4361d60a5da47671a9d8f5762583a4ff7693b --- /dev/null +++ b/tasks/henrygd__beszel-2450/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2450" +description = "fix(hub): honour SSH request cancellation" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "24881fbfdf3feba4567e41dc011ea283716873ee" +reference = "https://github.com/henrygd/beszel/pull/2450" +source_access = "auto" +built_at = "2026-11-16T16:09:53.464785+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:da443b4afad3aa6b03b1f51548542db027f9502f2da8853339d7786731bba2f2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-29T15:22:18Z" +diff_format = "unified" +context_files = [ + "internal/hub/transport/ssh.go", + "internal/hub/transport/ssh_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 453 +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:00.825796+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:024a134f08d598cb7d2c5f7e1227f04b41c1534f76eb68228ef851d5249bfbba" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2450/tests/capture.py b/tasks/henrygd__beszel-2450/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2450/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/henrygd__beszel-2450/tests/instruction.md b/tasks/henrygd__beszel-2450/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c750d302189b6b6f581ebe82f570f9b619bea624 --- /dev/null +++ b/tasks/henrygd__beszel-2450/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** fix(hub): honour SSH request cancellation + +## Description + +SSH detail and monitor-sync requests can remain blocked after their caller's context expires. The existing timeout covers opening a session, but not the handshake, shell acknowledgement, request write, response read or exit wait. + +Use context-aware dialling and close the captured connection on cancellation so blocked operations unwind and return the context error. Synchronise client access and remove only the failed connection, preserving a replacement created by another request. Cancelling also closes other sessions on that connection; subsequent requests can reconnect. Closing only the session cannot reliably unblock an unresponsive peer. + +Loopback tests cover deadlines and cancellation at each SSH phase, concurrent requests, cleanup and reconnection. Later-phase deadline tests establish SSH first; handshake cancellation is covered separately. The transport package passes under the race detector on Linux AMD64 and ARM64, including three repetitions on ARM64. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `24881fbfdf3f`. 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/henrygd__beszel-2450/tests/oracle.patch b/tasks/henrygd__beszel-2450/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..281a31a1fb30fd723a88206b4fe0760e097db410 --- /dev/null +++ b/tasks/henrygd__beszel-2450/tests/oracle.patch @@ -0,0 +1,545 @@ +diff --git a/internal/hub/transport/ssh.go b/internal/hub/transport/ssh.go +index 840c5564..1a2491ae 100644 +--- a/internal/hub/transport/ssh.go ++++ b/internal/hub/transport/ssh.go +@@ -7,6 +7,7 @@ import ( + "io" + "net" + "strings" ++ "sync" + "time" + + "github.com/blang/semver" +@@ -17,6 +18,7 @@ import ( + + // SSHTransport implements Transport over SSH connections. + type SSHTransport struct { ++ mu sync.Mutex + client *ssh.Client + config *ssh.ClientConfig + host string +@@ -51,33 +53,57 @@ func NewSSHTransport(cfg SSHTransportConfig) *SSHTransport { + + // SetClient sets the SSH client for reuse across requests. + func (t *SSHTransport) SetClient(client *ssh.Client) { ++ t.mu.Lock() ++ defer t.mu.Unlock() + t.client = client + } + + // SetAgentVersion sets the agent version (extracted from SSH handshake). + func (t *SSHTransport) SetAgentVersion(version semver.Version) { ++ t.mu.Lock() ++ defer t.mu.Unlock() + t.agentVersion = version + } + + // GetClient returns the current SSH client (for connection management). + func (t *SSHTransport) GetClient() *ssh.Client { ++ t.mu.Lock() ++ defer t.mu.Unlock() + return t.client + } + + // GetAgentVersion returns the agent version. + func (t *SSHTransport) GetAgentVersion() semver.Version { ++ t.mu.Lock() ++ defer t.mu.Unlock() + return t.agentVersion + } + + // Request sends a request to the agent via SSH and unmarshals the response. +-func (t *SSHTransport) Request(ctx context.Context, action common.WebSocketAction, req any, dest any) error { +- if t.client == nil { +- if err := t.connect(); err != nil { +- return err +- } ++func (t *SSHTransport) Request(ctx context.Context, action common.WebSocketAction, req any, dest any) (err error) { ++ if err := ctx.Err(); err != nil { ++ return err ++ } ++ client, err := t.connect(ctx) ++ if err != nil { ++ return err + } + +- session, err := t.createSessionWithTimeout(ctx) ++ // Closing only the session still depends on the peer processing SSH packets. ++ // Close the captured connection to release every blocked read/write, including ++ // concurrent sessions; subsequent requests can reconnect. ++ stop := closeOnCancellation(ctx, func() { t.closeClient(client) }) ++ defer func() { ++ stop() ++ if err != nil && ctx.Err() != nil { ++ err = ctx.Err() ++ } ++ if isConnectionError(err) { ++ t.closeClient(client) ++ } ++ }() ++ ++ session, err := t.createSessionWithTimeout(ctx, client) + if err != nil { + return err + } +@@ -121,21 +147,48 @@ func (t *SSHTransport) Request(ctx context.Context, action common.WebSocketActio + + // IsConnected returns true if the SSH connection is active. + func (t *SSHTransport) IsConnected() bool { +- return t.client != nil ++ return t.GetClient() != nil + } + + // Close terminates the SSH connection. + func (t *SSHTransport) Close() { +- if t.client != nil { +- t.client.Close() ++ t.closeClient(t.GetClient()) ++} ++ ++// closeClient removes only the connection owned by the completed request. ++func (t *SSHTransport) closeClient(client *ssh.Client) { ++ t.mu.Lock() ++ if t.client == client { + t.client = nil + } ++ t.mu.Unlock() ++ if client != nil { ++ client.Close() ++ } ++} ++ ++// closeOnCancellation stops I/O when ctx is cancelled. The returned function ++// waits for any in-progress close so it cannot outlive the operation. ++func closeOnCancellation(ctx context.Context, closeConn func()) func() { ++ done := make(chan struct{}) ++ stop := context.AfterFunc(ctx, func() { ++ closeConn() ++ close(done) ++ }) ++ return func() { ++ if !stop() { ++ <-done ++ } ++ } + } + +-// connect establishes a new SSH connection. +-func (t *SSHTransport) connect() error { ++// connect reuses the current client or establishes a cancellable SSH connection. ++func (t *SSHTransport) connect(ctx context.Context) (*ssh.Client, error) { ++ if client := t.GetClient(); client != nil { ++ return client, nil ++ } + if t.config == nil { +- return errors.New("SSH config not set") ++ return nil, errors.New("SSH config not set") + } + + network := "tcp" +@@ -146,46 +199,50 @@ func (t *SSHTransport) connect() error { + host = net.JoinHostPort(host, t.port) + } + +- client, err := ssh.Dial(network, host, t.config) ++ dialer := net.Dialer{Timeout: t.config.Timeout} ++ conn, err := dialer.DialContext(ctx, network, host) + if err != nil { +- return err ++ return nil, err + } +- t.client = client ++ stop := closeOnCancellation(ctx, func() { conn.Close() }) ++ sshConn, chans, reqs, err := ssh.NewClientConn(conn, host, t.config) ++ stop() ++ if ctx.Err() != nil { ++ conn.Close() ++ return nil, ctx.Err() ++ } ++ if err != nil { ++ conn.Close() ++ return nil, err ++ } ++ client := ssh.NewClient(sshConn, chans, reqs) + +- // Extract agent version from server version string ++ t.mu.Lock() ++ if existing := t.client; existing != nil { ++ t.mu.Unlock() ++ client.Close() ++ return existing, nil ++ } ++ t.client = client + t.agentVersion, _ = extractAgentVersion(string(client.Conn.ServerVersion())) +- return nil ++ t.mu.Unlock() ++ return client, nil + } + +-// createSessionWithTimeout creates a new SSH session with a timeout. +-func (t *SSHTransport) createSessionWithTimeout(ctx context.Context) (*ssh.Session, error) { +- if t.client == nil { +- return nil, errors.New("client not initialized") +- } +- ++// createSessionWithTimeout bounds session creation independently of the request. ++func (t *SSHTransport) createSessionWithTimeout(ctx context.Context, client *ssh.Client) (*ssh.Session, error) { + ctx, cancel := context.WithTimeout(ctx, t.timeout) + defer cancel() +- +- sessionChan := make(chan *ssh.Session, 1) +- errChan := make(chan error, 1) +- +- go func() { +- session, err := t.client.NewSession() +- if err != nil { +- errChan <- err +- } else { +- sessionChan <- session ++ stop := closeOnCancellation(ctx, func() { t.closeClient(client) }) ++ session, err := client.NewSession() ++ stop() ++ if ctx.Err() != nil { ++ if session != nil { ++ session.Close() + } +- }() +- +- select { +- case session := <-sessionChan: +- return session, nil +- case err := <-errChan: +- return nil, err +- case <-ctx.Done(): +- return nil, errors.New("timeout creating session") ++ return nil, ctx.Err() + } ++ return session, err + } + + // extractAgentVersion extracts the beszel version from SSH server version string. +@@ -206,7 +263,6 @@ func (t *SSHTransport) RequestWithRetry(ctx context.Context, action common.WebSo + + // Check if it's a connection error that warrants a retry + if isConnectionError(err) && attempt < retries { +- t.Close() + continue + } + return err +diff --git a/internal/hub/transport/ssh_test.go b/internal/hub/transport/ssh_test.go +new file mode 100644 +index 00000000..98be4c2d +--- /dev/null ++++ b/internal/hub/transport/ssh_test.go +@@ -0,0 +1,311 @@ ++package transport ++ ++import ( ++ "context" ++ "crypto/ed25519" ++ "crypto/rand" ++ "io" ++ "net" ++ "strings" ++ "sync" ++ "sync/atomic" ++ "testing" ++ "time" ++ ++ "github.com/fxamacker/cbor/v2" ++ "github.com/henrygd/beszel/internal/common" ++ "github.com/stretchr/testify/require" ++ "golang.org/x/crypto/ssh" ++) ++ ++// newSSHTestTransport starts a loopback SSH server that stalls the first ++// connection at the given stage; later connections behave normally so tests ++// can verify reconnection. ++func newSSHTestTransport(t *testing.T, stage string) (*SSHTransport, <-chan struct{}, <-chan struct{}) { ++ t.Helper() ++ _, key, err := ed25519.GenerateKey(rand.Reader) ++ require.NoError(t, err) ++ signer, err := ssh.NewSignerFromKey(key) ++ require.NoError(t, err) ++ config := &ssh.ServerConfig{NoClientAuth: true, ServerVersion: "SSH-2.0-beszel_0.20.0"} ++ config.AddHostKey(signer) ++ listener, err := net.Listen("tcp", "127.0.0.1:0") ++ require.NoError(t, err) ++ host, port, err := net.SplitHostPort(listener.Addr().String()) ++ require.NoError(t, err) ++ transport := NewSSHTransport(SSHTransportConfig{ ++ Host: host, Port: port, Timeout: 2 * time.Second, ++ Config: &ssh.ClientConfig{User: "test", HostKeyCallback: ssh.FixedHostKey(signer.PublicKey()), Timeout: time.Second}, ++ }) ++ reached, closed := make(chan struct{}), make(chan struct{}) ++ var once sync.Once ++ var connections atomic.Int32 ++ var mu sync.Mutex ++ conns := map[net.Conn]bool{} ++ var wg sync.WaitGroup ++ wg.Add(1) ++ go func() { ++ defer wg.Done() ++ for { ++ conn, err := listener.Accept() ++ if err != nil { ++ return ++ } ++ mu.Lock() ++ conns[conn] = true ++ mu.Unlock() ++ first := connections.Add(1) == 1 ++ wg.Add(1) ++ go func() { ++ defer wg.Done() ++ defer conn.Close() ++ if first { ++ defer close(closed) ++ } ++ if first && stage == "handshake" { ++ close(reached) ++ _, _ = io.Copy(io.Discard, conn) ++ return ++ } ++ server, channels, requests, err := ssh.NewServerConn(conn, config) ++ if err != nil { ++ return ++ } ++ defer server.Close() ++ go ssh.DiscardRequests(requests) ++ disconnected := make(chan struct{}) ++ go func() { _ = server.Wait(); close(disconnected) }() ++ for channel := range channels { ++ wg.Add(1) ++ go func() { ++ defer wg.Done() ++ stall := func(at string) bool { ++ if !first || stage != at { ++ return false ++ } ++ once.Do(func() { close(reached) }) ++ <-disconnected ++ return true ++ } ++ if stall("session") { ++ return ++ } ++ ch, requests, err := channel.Accept() ++ if err != nil { ++ return ++ } ++ defer ch.Close() ++ for request := range requests { ++ if request.Type != "shell" { ++ _ = request.Reply(false, nil) ++ continue ++ } ++ if stall("shell") { ++ return ++ } ++ _ = request.Reply(true, nil) ++ if stall("write") { ++ return ++ } ++ var req common.HubRequest[cbor.RawMessage] ++ if cbor.NewDecoder(ch).Decode(&req) != nil || stall("response") { ++ return ++ } ++ if stage == "slow-response" { ++ select { ++ case <-time.After(250 * time.Millisecond): ++ case <-disconnected: ++ return ++ } ++ } ++ data, _ := cbor.Marshal("control response") ++ if cbor.NewEncoder(ch).Encode(common.AgentResponse{Data: data}) != nil || stall("exit") { ++ return ++ } ++ _, _ = ch.SendRequest("exit-status", false, ssh.Marshal(struct{ Status uint32 }{0})) ++ return ++ } ++ }() ++ } ++ }() ++ } ++ }() ++ t.Cleanup(func() { ++ listener.Close() ++ transport.Close() ++ mu.Lock() ++ for conn := range conns { ++ conn.Close() ++ } ++ mu.Unlock() ++ done := make(chan struct{}) ++ go func() { wg.Wait(); close(done) }() ++ select { ++ case <-done: ++ case <-time.After(3 * time.Second): ++ t.Error("SSH server did not stop") ++ } ++ }) ++ return transport, reached, closed ++} ++ ++func TestSSHRequestCancellation(t *testing.T) { ++ for _, stage := range []string{"handshake", "session", "shell", "write", "response", "exit"} { ++ for _, cancellation := range []string{"deadline", "cancel"} { ++ t.Run(stage+"/"+cancellation, func(t *testing.T) { ++ transport, reached, closed := newSSHTestTransport(t, stage) ++ var req any ++ if stage == "write" { ++ // Larger than the SSH receive window, so an unread write blocks. ++ req = strings.Repeat("x", 4<<20) ++ } ++ ctx, cancel := context.WithCancel(t.Context()) ++ if cancellation == "deadline" { ++ cancel() ++ // Handshake has its own deadline case. Complete it before ++ // timing the later SSH phases on slower hosts. ++ if stage != "handshake" { ++ setupCtx, stopSetup := context.WithTimeout(t.Context(), 2*time.Second) ++ _, err := transport.connect(setupCtx) ++ stopSetup() ++ require.NoError(t, err) ++ } ++ ctx, cancel = context.WithTimeout(t.Context(), 250*time.Millisecond) ++ } ++ defer cancel() ++ done := make(chan error, 1) ++ result := "unchanged" ++ go func() { done <- transport.RequestWithRetry(ctx, common.GetContainerLogs, req, &result, 1) }() ++ select { ++ case <-reached: ++ case <-time.After(2 * time.Second): ++ t.Fatal("request did not reach stalled phase") ++ } ++ want := context.DeadlineExceeded ++ if cancellation == "cancel" { ++ want = context.Canceled ++ cancel() ++ } ++ select { ++ case err := <-done: ++ require.ErrorIs(t, err, want) ++ case <-time.After(2 * time.Second): ++ t.Fatal("request ignored cancellation") ++ } ++ require.Equal(t, "unchanged", result) ++ require.False(t, transport.IsConnected()) ++ select { ++ case <-closed: ++ case <-time.After(time.Second): ++ t.Fatal("cancelled request left its connection open") ++ } ++ require.NoError(t, transport.Request(t.Context(), common.GetContainerLogs, nil, &result)) ++ require.Equal(t, "control response", result) ++ }) ++ } ++ } ++} ++ ++func TestSSHSessionTimeout(t *testing.T) { ++ transport, _, _ := newSSHTestTransport(t, "session") ++ transport.timeout = 50 * time.Millisecond ++ ctx, cancel := context.WithTimeout(t.Context(), time.Second) ++ defer cancel() ++ var result string ++ require.ErrorIs(t, transport.Request(ctx, common.GetContainerLogs, nil, &result), context.DeadlineExceeded) ++ require.NoError(t, ctx.Err(), "the session timeout must fire before the caller's deadline") ++ require.False(t, transport.IsConnected()) ++} ++ ++func TestSSHRequestAlreadyCancelled(t *testing.T) { ++ transport := NewSSHTransport(SSHTransportConfig{}) ++ ctx, cancel := context.WithCancel(t.Context()) ++ cancel() ++ var result string ++ require.ErrorIs(t, transport.Request(ctx, common.GetContainerLogs, nil, &result), context.Canceled) ++} ++ ++func TestSSHSlowResponse(t *testing.T) { ++ transport, _, _ := newSSHTestTransport(t, "slow-response") ++ transport.timeout = 100 * time.Millisecond ++ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) ++ defer cancel() ++ var result string ++ require.NoError(t, transport.Request(ctx, common.GetContainerLogs, nil, &result)) ++ require.Equal(t, "control response", result, "session timeout must not shorten the request deadline") ++} ++ ++func TestSSHConcurrentRequests(t *testing.T) { ++ transport, _, _ := newSSHTestTransport(t, "") ++ var wg sync.WaitGroup ++ for range 10 { ++ wg.Go(func() { ++ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) ++ defer cancel() ++ var result string ++ if err := transport.Request(ctx, common.GetContainerLogs, nil, &result); err != nil { ++ t.Error(err) ++ } else if result != "control response" { ++ t.Errorf("unexpected response %q", result) ++ } ++ }) ++ } ++ wg.Wait() ++ client := transport.GetClient() ++ require.NotNil(t, client) ++ ctx, cancel := context.WithCancel(t.Context()) ++ var result string ++ require.NoError(t, transport.Request(ctx, common.GetContainerLogs, nil, &result)) ++ cancel() ++ // Cancelling a completed request must not close the reused connection. ++ require.NoError(t, transport.Request(t.Context(), common.GetContainerLogs, nil, &result)) ++ require.Same(t, client, transport.GetClient()) ++ // The existing retry contract still replaces an unusable connection. ++ require.NoError(t, client.Close()) ++ require.NoError(t, transport.RequestWithRetry(t.Context(), common.GetContainerLogs, nil, &result, 1)) ++ require.NotSame(t, client, transport.GetClient()) ++} ++ ++func TestSSHCancelledSharedConnection(t *testing.T) { ++ transport, reached, _ := newSSHTestTransport(t, "response") ++ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) ++ defer cancel() ++ client, err := transport.connect(ctx) ++ require.NoError(t, err) ++ // Keep another session on the shared connection waiting for an exit. ++ session, err := client.NewSession() ++ require.NoError(t, err) ++ require.NoError(t, session.Shell()) ++ waiting := make(chan error, 1) ++ go func() { waiting <- session.Wait() }() ++ requestCtx, cancelRequest := context.WithCancel(ctx) ++ defer cancelRequest() ++ done := make(chan error, 1) ++ var result string ++ go func() { done <- transport.Request(requestCtx, common.GetContainerLogs, nil, &result) }() ++ select { ++ case <-reached: ++ case <-ctx.Done(): ++ t.Fatal("request did not reach the response read") ++ } ++ cancelRequest() ++ select { ++ case err := <-done: ++ require.ErrorIs(t, err, context.Canceled) ++ case <-ctx.Done(): ++ t.Fatal("request ignored cancellation") ++ } ++ select { ++ case err := <-waiting: ++ require.Error(t, err, "closing the shared client must release other sessions") ++ case <-ctx.Done(): ++ t.Fatal("concurrent session remained blocked") ++ } ++ require.NoError(t, transport.Request(ctx, common.GetContainerLogs, nil, &result)) ++ replacement := transport.GetClient() ++ require.NotSame(t, client, replacement) ++ // Late cleanup of the old connection must not discard its replacement. ++ transport.closeClient(client) ++ require.Same(t, replacement, transport.GetClient()) ++ require.NoError(t, transport.Request(ctx, common.GetContainerLogs, nil, &result)) ++} diff --git a/tasks/henrygd__beszel-2450/tests/test.sh b/tasks/henrygd__beszel-2450/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..83048c07804c66f1816c50e6e83a5c54d66be611 --- /dev/null +++ b/tasks/henrygd__beszel-2450/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 24881fbfdf3feba4567e41dc011ea283716873ee > "$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/henrygd__beszel-2450/tests/verifier.py b/tasks/henrygd__beszel-2450/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2450/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/henrygd__beszel-2451/environment/Dockerfile b/tasks/henrygd__beszel-2451/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..73c60683dc4670666ae2ba71ef137a96b07458ac --- /dev/null +++ b/tasks/henrygd__beszel-2451/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 921ded1af0f955ddaba1dabafe0d361f1d12fb7d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 921ded1af0f955ddaba1dabafe0d361f1d12fb7d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 921ded1af0f955ddaba1dabafe0d361f1d12fb7d \ + && 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/henrygd__beszel-2451/instruction.md b/tasks/henrygd__beszel-2451/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ffb3ac22c18c0b97505744ebc1c6310ef5ce9f5d --- /dev/null +++ b/tasks/henrygd__beszel-2451/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(agent): create SSH server configuration per connection + +## Description + +The agent returns the same SSH server config for every connection. Gliderlabs adds host keys and connection-specific callbacks to that config, so simultaneous handshakes race while modifying and reading it. + +Return a fresh config for each connection with the existing server version and algorithm allowlists. A synchronised two-client loopback regression checks distinct configs, successful handshakes and unchanged configuration values. It reproduces the races before the change and passes under the race detector afterwards, including with this patch alone on the base revision. Agent vet passes; the regression also passes three race runs on macOS ARM64. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `921ded1af0f9`. 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/henrygd__beszel-2451/solution/patch.diff b/tasks/henrygd__beszel-2451/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..24c114388f8a0b3afac1f58962def304d148949a --- /dev/null +++ b/tasks/henrygd__beszel-2451/solution/patch.diff @@ -0,0 +1,164 @@ +diff --git a/agent/server.go b/agent/server.go +index 2c209fa0..2fde95ed 100644 +--- a/agent/server.go ++++ b/agent/server.go +@@ -57,21 +57,11 @@ func (a *Agent) StartServer(opts ServerOptions) error { + } + defer ln.Close() + +- // base config (limit to allowed algorithms) +- config := &gossh.ServerConfig{ +- ServerVersion: fmt.Sprintf("SSH-2.0-%s_%s", beszel.AppName, beszel.Version), +- } +- config.KeyExchanges = common.DefaultKeyExchanges +- config.MACs = common.DefaultMACs +- config.Ciphers = common.DefaultCiphers +- + // set default handler + ssh.Handle(a.handleSession) + + a.server = &ssh.Server{ +- ServerConfigCallback: func(ctx ssh.Context) *gossh.ServerConfig { +- return config +- }, ++ ServerConfigCallback: newSSHServerConfig, + // check public key(s) + PublicKeyHandler: func(ctx ssh.Context, key ssh.PublicKey) bool { + remoteAddr := ctx.RemoteAddr() +@@ -96,6 +86,19 @@ func (a *Agent) StartServer(opts ServerOptions) error { + return a.server.Serve(ln) + } + ++// newSSHServerConfig returns a separate config for each connection because ++// gliderlabs adds host keys and connection-specific callbacks to it. ++func newSSHServerConfig(ssh.Context) *gossh.ServerConfig { ++ return &gossh.ServerConfig{ ++ Config: gossh.Config{ ++ KeyExchanges: common.DefaultKeyExchanges, ++ MACs: common.DefaultMACs, ++ Ciphers: common.DefaultCiphers, ++ }, ++ ServerVersion: fmt.Sprintf("SSH-2.0-%s_%s", beszel.AppName, beszel.Version), ++ } ++} ++ + // getHubVersion extracts the hub version from the SSH client version string + // for a given session. Returns a zero version if parsing fails. + func (a *Agent) getHubVersion(sessionCtx ssh.Context) semver.Version { +diff --git a/agent/server_config_test.go b/agent/server_config_test.go +new file mode 100644 +index 00000000..acfe9682 +--- /dev/null ++++ b/agent/server_config_test.go +@@ -0,0 +1,111 @@ ++//go:build testing ++ ++package agent ++ ++import ( ++ "crypto/ed25519" ++ "fmt" ++ "net" ++ "sync" ++ "testing" ++ "time" ++ ++ "github.com/henrygd/beszel" ++ "github.com/henrygd/beszel/internal/common" ++ ++ "github.com/gliderlabs/ssh" ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/require" ++ gossh "golang.org/x/crypto/ssh" ++) ++ ++func TestSSHServerConfigConcurrentConnections(t *testing.T) { ++ _, key, err := ed25519.GenerateKey(nil) ++ require.NoError(t, err) ++ signer, err := gossh.NewSignerFromKey(key) ++ require.NoError(t, err) ++ listener, err := net.Listen("tcp", "127.0.0.1:0") ++ require.NoError(t, err) ++ ++ const connections = 2 ++ configs := make(chan *gossh.ServerConfig, connections) ++ release := make(chan struct{}) ++ var releaseOnce sync.Once ++ unblock := func() { releaseOnce.Do(func() { close(release) }) } ++ server := &ssh.Server{ ++ HostSigners: []ssh.Signer{signer}, ++ ServerConfigCallback: func(ctx ssh.Context) *gossh.ServerConfig { ++ config := newSSHServerConfig(ctx) ++ configs <- config ++ // Both connections must obtain their configuration before either ++ // lets gliderlabs add host keys and connection-specific callbacks. ++ <-release ++ return config ++ }, ++ PublicKeyHandler: func(_ ssh.Context, key ssh.PublicKey) bool { ++ return ssh.KeysEqual(key, signer.PublicKey()) ++ }, ++ Handler: func(session ssh.Session) { _ = session.Exit(0) }, ++ } ++ served := make(chan error, 1) ++ go func() { served <- server.Serve(listener) }() ++ t.Cleanup(func() { ++ unblock() ++ _ = listener.Close() ++ _ = server.Close() ++ select { ++ case <-served: ++ case <-time.After(5 * time.Second): ++ t.Error("SSH test server did not stop") ++ } ++ }) ++ ++ results := make(chan error, connections) ++ for range connections { ++ go func() { ++ conn, err := net.DialTimeout("tcp", listener.Addr().String(), 5*time.Second) ++ if err != nil { ++ results <- err ++ return ++ } ++ defer conn.Close() ++ _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) ++ client, _, _, err := gossh.NewClientConn(conn, listener.Addr().String(), &gossh.ClientConfig{ ++ User: "test", ++ Auth: []gossh.AuthMethod{gossh.PublicKeys(signer)}, ++ HostKeyCallback: gossh.FixedHostKey(signer.PublicKey()), ++ }) ++ if err == nil { ++ err = client.Close() ++ } ++ results <- err ++ }() ++ } ++ ++ var first *gossh.ServerConfig ++ for range connections { ++ select { ++ case config := <-configs: ++ assert.Equal(t, fmt.Sprintf("SSH-2.0-%s_%s", beszel.AppName, beszel.Version), config.ServerVersion) ++ assert.Equal(t, common.DefaultKeyExchanges, config.KeyExchanges) ++ assert.Equal(t, common.DefaultMACs, config.MACs) ++ assert.Equal(t, common.DefaultCiphers, config.Ciphers) ++ if first == nil { ++ first = config ++ } else { ++ assert.NotSame(t, first, config, "SSH connections must not share mutable configuration") ++ } ++ case <-time.After(5 * time.Second): ++ t.Fatal("SSH connections did not reach their config callbacks") ++ } ++ } ++ unblock() ++ for range connections { ++ select { ++ case err := <-results: ++ require.NoError(t, err) ++ case <-time.After(5 * time.Second): ++ t.Fatal("SSH handshake did not finish") ++ } ++ } ++} diff --git a/tasks/henrygd__beszel-2451/solution/solve.sh b/tasks/henrygd__beszel-2451/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2451/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/henrygd__beszel-2451/task.toml b/tasks/henrygd__beszel-2451/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e8a80a7b1c6d026cab4f0440d4c23853f519c4f8 --- /dev/null +++ b/tasks/henrygd__beszel-2451/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2451" +description = "fix(agent): create SSH server configuration per connection" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "921ded1af0f955ddaba1dabafe0d361f1d12fb7d" +reference = "https://github.com/henrygd/beszel/pull/2451" +source_access = "auto" +built_at = "2026-11-16T16:09:53.470194+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:aa7febae8fa0d5fccc9f5ef53b874e7f63b95c6b177fa9b27560a1df2735b638" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T23:22:49Z" +diff_format = "unified" +context_files = [ + "agent/server.go", + "agent/server_config_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 136 +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:00.826239+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:550b1e9111eb9e285fce9000af993a9c7c2bb107c221a131e55a148668f1dd25" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2451/tests/capture.py b/tasks/henrygd__beszel-2451/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2451/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/henrygd__beszel-2451/tests/instruction.md b/tasks/henrygd__beszel-2451/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ffb3ac22c18c0b97505744ebc1c6310ef5ce9f5d --- /dev/null +++ b/tasks/henrygd__beszel-2451/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(agent): create SSH server configuration per connection + +## Description + +The agent returns the same SSH server config for every connection. Gliderlabs adds host keys and connection-specific callbacks to that config, so simultaneous handshakes race while modifying and reading it. + +Return a fresh config for each connection with the existing server version and algorithm allowlists. A synchronised two-client loopback regression checks distinct configs, successful handshakes and unchanged configuration values. It reproduces the races before the change and passes under the race detector afterwards, including with this patch alone on the base revision. Agent vet passes; the regression also passes three race runs on macOS ARM64. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `921ded1af0f9`. 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/henrygd__beszel-2451/tests/oracle.patch b/tasks/henrygd__beszel-2451/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..24c114388f8a0b3afac1f58962def304d148949a --- /dev/null +++ b/tasks/henrygd__beszel-2451/tests/oracle.patch @@ -0,0 +1,164 @@ +diff --git a/agent/server.go b/agent/server.go +index 2c209fa0..2fde95ed 100644 +--- a/agent/server.go ++++ b/agent/server.go +@@ -57,21 +57,11 @@ func (a *Agent) StartServer(opts ServerOptions) error { + } + defer ln.Close() + +- // base config (limit to allowed algorithms) +- config := &gossh.ServerConfig{ +- ServerVersion: fmt.Sprintf("SSH-2.0-%s_%s", beszel.AppName, beszel.Version), +- } +- config.KeyExchanges = common.DefaultKeyExchanges +- config.MACs = common.DefaultMACs +- config.Ciphers = common.DefaultCiphers +- + // set default handler + ssh.Handle(a.handleSession) + + a.server = &ssh.Server{ +- ServerConfigCallback: func(ctx ssh.Context) *gossh.ServerConfig { +- return config +- }, ++ ServerConfigCallback: newSSHServerConfig, + // check public key(s) + PublicKeyHandler: func(ctx ssh.Context, key ssh.PublicKey) bool { + remoteAddr := ctx.RemoteAddr() +@@ -96,6 +86,19 @@ func (a *Agent) StartServer(opts ServerOptions) error { + return a.server.Serve(ln) + } + ++// newSSHServerConfig returns a separate config for each connection because ++// gliderlabs adds host keys and connection-specific callbacks to it. ++func newSSHServerConfig(ssh.Context) *gossh.ServerConfig { ++ return &gossh.ServerConfig{ ++ Config: gossh.Config{ ++ KeyExchanges: common.DefaultKeyExchanges, ++ MACs: common.DefaultMACs, ++ Ciphers: common.DefaultCiphers, ++ }, ++ ServerVersion: fmt.Sprintf("SSH-2.0-%s_%s", beszel.AppName, beszel.Version), ++ } ++} ++ + // getHubVersion extracts the hub version from the SSH client version string + // for a given session. Returns a zero version if parsing fails. + func (a *Agent) getHubVersion(sessionCtx ssh.Context) semver.Version { +diff --git a/agent/server_config_test.go b/agent/server_config_test.go +new file mode 100644 +index 00000000..acfe9682 +--- /dev/null ++++ b/agent/server_config_test.go +@@ -0,0 +1,111 @@ ++//go:build testing ++ ++package agent ++ ++import ( ++ "crypto/ed25519" ++ "fmt" ++ "net" ++ "sync" ++ "testing" ++ "time" ++ ++ "github.com/henrygd/beszel" ++ "github.com/henrygd/beszel/internal/common" ++ ++ "github.com/gliderlabs/ssh" ++ "github.com/stretchr/testify/assert" ++ "github.com/stretchr/testify/require" ++ gossh "golang.org/x/crypto/ssh" ++) ++ ++func TestSSHServerConfigConcurrentConnections(t *testing.T) { ++ _, key, err := ed25519.GenerateKey(nil) ++ require.NoError(t, err) ++ signer, err := gossh.NewSignerFromKey(key) ++ require.NoError(t, err) ++ listener, err := net.Listen("tcp", "127.0.0.1:0") ++ require.NoError(t, err) ++ ++ const connections = 2 ++ configs := make(chan *gossh.ServerConfig, connections) ++ release := make(chan struct{}) ++ var releaseOnce sync.Once ++ unblock := func() { releaseOnce.Do(func() { close(release) }) } ++ server := &ssh.Server{ ++ HostSigners: []ssh.Signer{signer}, ++ ServerConfigCallback: func(ctx ssh.Context) *gossh.ServerConfig { ++ config := newSSHServerConfig(ctx) ++ configs <- config ++ // Both connections must obtain their configuration before either ++ // lets gliderlabs add host keys and connection-specific callbacks. ++ <-release ++ return config ++ }, ++ PublicKeyHandler: func(_ ssh.Context, key ssh.PublicKey) bool { ++ return ssh.KeysEqual(key, signer.PublicKey()) ++ }, ++ Handler: func(session ssh.Session) { _ = session.Exit(0) }, ++ } ++ served := make(chan error, 1) ++ go func() { served <- server.Serve(listener) }() ++ t.Cleanup(func() { ++ unblock() ++ _ = listener.Close() ++ _ = server.Close() ++ select { ++ case <-served: ++ case <-time.After(5 * time.Second): ++ t.Error("SSH test server did not stop") ++ } ++ }) ++ ++ results := make(chan error, connections) ++ for range connections { ++ go func() { ++ conn, err := net.DialTimeout("tcp", listener.Addr().String(), 5*time.Second) ++ if err != nil { ++ results <- err ++ return ++ } ++ defer conn.Close() ++ _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) ++ client, _, _, err := gossh.NewClientConn(conn, listener.Addr().String(), &gossh.ClientConfig{ ++ User: "test", ++ Auth: []gossh.AuthMethod{gossh.PublicKeys(signer)}, ++ HostKeyCallback: gossh.FixedHostKey(signer.PublicKey()), ++ }) ++ if err == nil { ++ err = client.Close() ++ } ++ results <- err ++ }() ++ } ++ ++ var first *gossh.ServerConfig ++ for range connections { ++ select { ++ case config := <-configs: ++ assert.Equal(t, fmt.Sprintf("SSH-2.0-%s_%s", beszel.AppName, beszel.Version), config.ServerVersion) ++ assert.Equal(t, common.DefaultKeyExchanges, config.KeyExchanges) ++ assert.Equal(t, common.DefaultMACs, config.MACs) ++ assert.Equal(t, common.DefaultCiphers, config.Ciphers) ++ if first == nil { ++ first = config ++ } else { ++ assert.NotSame(t, first, config, "SSH connections must not share mutable configuration") ++ } ++ case <-time.After(5 * time.Second): ++ t.Fatal("SSH connections did not reach their config callbacks") ++ } ++ } ++ unblock() ++ for range connections { ++ select { ++ case err := <-results: ++ require.NoError(t, err) ++ case <-time.After(5 * time.Second): ++ t.Fatal("SSH handshake did not finish") ++ } ++ } ++} diff --git a/tasks/henrygd__beszel-2451/tests/test.sh b/tasks/henrygd__beszel-2451/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4f5817976cbdbe2163323a35ee9a64033e22f362 --- /dev/null +++ b/tasks/henrygd__beszel-2451/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 921ded1af0f955ddaba1dabafe0d361f1d12fb7d > "$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/henrygd__beszel-2451/tests/verifier.py b/tasks/henrygd__beszel-2451/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2451/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/henrygd__beszel-2452/environment/Dockerfile b/tasks/henrygd__beszel-2452/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a228f6d475218179bd472c5ff46ffe11a3948509 --- /dev/null +++ b/tasks/henrygd__beszel-2452/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 083b28a1fc5fdf198ef36ac6b4e64dcc1cf98747 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 083b28a1fc5fdf198ef36ac6b4e64dcc1cf98747 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 083b28a1fc5fdf198ef36ac6b4e64dcc1cf98747 \ + && 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/henrygd__beszel-2452/instruction.md b/tasks/henrygd__beszel-2452/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9c5a082a1d8222d7bbee57f22f97d7d4686bf3d1 --- /dev/null +++ b/tasks/henrygd__beszel-2452/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(hub): synchronise system status access + +## Description + +The systems record hook can write a system's status while its updater and monitor hooks read it. Protect those accesses with a per-system mutex and exchange the previous/new status together for alert transitions. + +`TestStatusAlerts` reproduced the race before the change and passes three race runs afterwards. The status-alert family and pause, recovery and cancellation controls pass under the race detector. `go vet` and the Makefile hub build pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `083b28a1fc5f`. 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/henrygd__beszel-2452/solution/patch.diff b/tasks/henrygd__beszel-2452/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4009401d329c38ba59dbd84130e988ba12f8d8fb --- /dev/null +++ b/tasks/henrygd__beszel-2452/solution/patch.diff @@ -0,0 +1,122 @@ +diff --git a/internal/hub/network_monitors.go b/internal/hub/network_monitors.go +index 98e9e0e8..9fcc8640 100644 +--- a/internal/hub/network_monitors.go ++++ b/internal/hub/network_monitors.go +@@ -47,7 +47,7 @@ func bindNetworkMonitorsEvents(hub *Hub) { + // If connected, run the monitor immediately. Paused systems may be absent + // from the manager; their monitors will sync when they reconnect. + system, err := hub.sm.GetSystem(e.Record.GetString("system")) +- if err == nil && system.Status == "up" { ++ if err == nil && system.GetStatus() == "up" { + go hub.upsertNetworkMonitor(e.Record, true) + } + return nil +diff --git a/internal/hub/systems/system.go b/internal/hub/systems/system.go +index 349304e2..49d1f5d6 100644 +--- a/internal/hub/systems/system.go ++++ b/internal/hub/systems/system.go +@@ -41,7 +41,8 @@ type System struct { + Id string `db:"id"` + Host string `db:"host"` + Port string `db:"port"` +- Status string `db:"status"` ++ Status string `db:"status"` // Use GetStatus/swapStatus after publishing the system. ++ statusMu sync.RWMutex // Protects Status and exchanges used by alert transitions. + manager *SystemManager // Manager that this system belongs to + client atomic.Pointer[ssh.Client] // SSH client for fetching data + sshTransport *transport.SSHTransport // SSH transport for requests +@@ -65,6 +66,22 @@ type System struct { + lastSavedMonitorProbe map[string]int64 + } + ++// GetStatus returns the current monitoring status. ++func (sys *System) GetStatus() string { ++ sys.statusMu.RLock() ++ defer sys.statusMu.RUnlock() ++ return sys.Status ++} ++ ++// swapStatus updates the status and returns the previous value as one operation. ++func (sys *System) swapStatus(status string) string { ++ sys.statusMu.Lock() ++ defer sys.statusMu.Unlock() ++ previous := sys.Status ++ sys.Status = status ++ return previous ++} ++ + func (sm *SystemManager) NewSystem(systemId string) *System { + system := &System{ + Id: systemId, +@@ -101,7 +118,7 @@ func (sys *System) StartUpdater() { + + // update immediately if system is not paused (only for ws connections) + // we'll wait a minute before connecting via SSH to prioritize ws connections +- if sys.Status != paused && sys.ctx.Err() == nil { ++ if sys.GetStatus() != paused && sys.ctx.Err() == nil { + if err := sys.update(); err != nil { + _ = sys.setDown(err) + } +@@ -134,7 +151,7 @@ func (sys *System) StartUpdater() { + + // update updates the system data and records. + func (sys *System) update() error { +- if sys.Status == paused { ++ if sys.GetStatus() == paused { + sys.handlePaused() + return nil + } +@@ -603,7 +620,7 @@ func (sys *System) HasUser(app core.App, user *core.Record) bool { + // encountered during the process of updating the system status. + // It is a no-op if the system's context has been cancelled. + func (sys *System) setDown(originalError error) error { +- if sys.Status == down || sys.Status == paused { ++ if status := sys.GetStatus(); status == down || status == paused { + return nil + } + // the updater can race shutdown, and the app may already be disposed by the +@@ -885,7 +902,7 @@ func (sys *System) fetchDataViaSSH(options common.DataRequestOptions) (*system.C + // The operation can request a retry by returning true as the first return value. + func (sys *System) runSSHOperation(timeout time.Duration, retries int, operation func(*ssh.Session) (bool, error)) error { + for attempt := 0; attempt <= retries; attempt++ { +- if sys.client.Load() == nil || sys.Status == down { ++ if sys.client.Load() == nil || sys.GetStatus() == down { + if err := sys.createSSHClient(); err != nil { + return err + } +diff --git a/internal/hub/systems/system_manager.go b/internal/hub/systems/system_manager.go +index 4e65ed55..6c14b8d9 100644 +--- a/internal/hub/systems/system_manager.go ++++ b/internal/hub/systems/system_manager.go +@@ -209,8 +209,7 @@ func (sm *SystemManager) onRecordAfterUpdateSuccess(e *core.RecordEvent) error { + prevStatus := pending + system, ok := sm.systems.GetOk(e.Record.Id) + if ok { +- prevStatus = system.Status +- system.Status = newStatus ++ prevStatus = system.swapStatus(newStatus) + } + + switch newStatus { +@@ -335,7 +334,7 @@ func (sm *SystemManager) AddRecord(record *core.Record, system *System) (err err + } + + // Populate system from record +- system.Status = record.GetString("status") ++ system.swapStatus(record.GetString("status")) + system.Host = record.GetString("host") + system.Port = record.GetString("port") + +diff --git a/internal/hub/systems/systems_test_helpers.go b/internal/hub/systems/systems_test_helpers.go +index ca61895f..9e6c4860 100644 +--- a/internal/hub/systems/systems_test_helpers.go ++++ b/internal/hub/systems/systems_test_helpers.go +@@ -38,7 +38,7 @@ func (sm *SystemManager) GetSystemStatusFromStore(systemID string) string { + if !ok { + return "" + } +- return sys.Status ++ return sys.GetStatus() + } + + // TESTING ONLY: GetSystemContextFromStore returns the context and cancel function for a system diff --git a/tasks/henrygd__beszel-2452/solution/solve.sh b/tasks/henrygd__beszel-2452/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2452/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/henrygd__beszel-2452/task.toml b/tasks/henrygd__beszel-2452/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2640e8398ab74582051f9617c1d884c32fffbd4b --- /dev/null +++ b/tasks/henrygd__beszel-2452/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2452" +description = "fix(hub): synchronise system status access" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "083b28a1fc5fdf198ef36ac6b4e64dcc1cf98747" +reference = "https://github.com/henrygd/beszel/pull/2452" +source_access = "auto" +built_at = "2026-11-16T16:09:53.473243+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5470d956f56c8dd6d26e4e827ac174f2f8d562adfb786c93bf7c87f56107a0f9" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T22:58:46Z" +diff_format = "unified" +context_files = [ + "internal/hub/network_monitors.go", + "internal/hub/systems/system.go", + "internal/hub/systems/system_manager.go", + "internal/hub/systems/systems_test_helpers.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 36 +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:00.826707+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:101effd5f1c8ed4716448e194665e7e1565b2361182cb584622c5f187d75a09e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2452/tests/capture.py b/tasks/henrygd__beszel-2452/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2452/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/henrygd__beszel-2452/tests/instruction.md b/tasks/henrygd__beszel-2452/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9c5a082a1d8222d7bbee57f22f97d7d4686bf3d1 --- /dev/null +++ b/tasks/henrygd__beszel-2452/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(hub): synchronise system status access + +## Description + +The systems record hook can write a system's status while its updater and monitor hooks read it. Protect those accesses with a per-system mutex and exchange the previous/new status together for alert transitions. + +`TestStatusAlerts` reproduced the race before the change and passes three race runs afterwards. The status-alert family and pause, recovery and cancellation controls pass under the race detector. `go vet` and the Makefile hub build pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `083b28a1fc5f`. 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/henrygd__beszel-2452/tests/oracle.patch b/tasks/henrygd__beszel-2452/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4009401d329c38ba59dbd84130e988ba12f8d8fb --- /dev/null +++ b/tasks/henrygd__beszel-2452/tests/oracle.patch @@ -0,0 +1,122 @@ +diff --git a/internal/hub/network_monitors.go b/internal/hub/network_monitors.go +index 98e9e0e8..9fcc8640 100644 +--- a/internal/hub/network_monitors.go ++++ b/internal/hub/network_monitors.go +@@ -47,7 +47,7 @@ func bindNetworkMonitorsEvents(hub *Hub) { + // If connected, run the monitor immediately. Paused systems may be absent + // from the manager; their monitors will sync when they reconnect. + system, err := hub.sm.GetSystem(e.Record.GetString("system")) +- if err == nil && system.Status == "up" { ++ if err == nil && system.GetStatus() == "up" { + go hub.upsertNetworkMonitor(e.Record, true) + } + return nil +diff --git a/internal/hub/systems/system.go b/internal/hub/systems/system.go +index 349304e2..49d1f5d6 100644 +--- a/internal/hub/systems/system.go ++++ b/internal/hub/systems/system.go +@@ -41,7 +41,8 @@ type System struct { + Id string `db:"id"` + Host string `db:"host"` + Port string `db:"port"` +- Status string `db:"status"` ++ Status string `db:"status"` // Use GetStatus/swapStatus after publishing the system. ++ statusMu sync.RWMutex // Protects Status and exchanges used by alert transitions. + manager *SystemManager // Manager that this system belongs to + client atomic.Pointer[ssh.Client] // SSH client for fetching data + sshTransport *transport.SSHTransport // SSH transport for requests +@@ -65,6 +66,22 @@ type System struct { + lastSavedMonitorProbe map[string]int64 + } + ++// GetStatus returns the current monitoring status. ++func (sys *System) GetStatus() string { ++ sys.statusMu.RLock() ++ defer sys.statusMu.RUnlock() ++ return sys.Status ++} ++ ++// swapStatus updates the status and returns the previous value as one operation. ++func (sys *System) swapStatus(status string) string { ++ sys.statusMu.Lock() ++ defer sys.statusMu.Unlock() ++ previous := sys.Status ++ sys.Status = status ++ return previous ++} ++ + func (sm *SystemManager) NewSystem(systemId string) *System { + system := &System{ + Id: systemId, +@@ -101,7 +118,7 @@ func (sys *System) StartUpdater() { + + // update immediately if system is not paused (only for ws connections) + // we'll wait a minute before connecting via SSH to prioritize ws connections +- if sys.Status != paused && sys.ctx.Err() == nil { ++ if sys.GetStatus() != paused && sys.ctx.Err() == nil { + if err := sys.update(); err != nil { + _ = sys.setDown(err) + } +@@ -134,7 +151,7 @@ func (sys *System) StartUpdater() { + + // update updates the system data and records. + func (sys *System) update() error { +- if sys.Status == paused { ++ if sys.GetStatus() == paused { + sys.handlePaused() + return nil + } +@@ -603,7 +620,7 @@ func (sys *System) HasUser(app core.App, user *core.Record) bool { + // encountered during the process of updating the system status. + // It is a no-op if the system's context has been cancelled. + func (sys *System) setDown(originalError error) error { +- if sys.Status == down || sys.Status == paused { ++ if status := sys.GetStatus(); status == down || status == paused { + return nil + } + // the updater can race shutdown, and the app may already be disposed by the +@@ -885,7 +902,7 @@ func (sys *System) fetchDataViaSSH(options common.DataRequestOptions) (*system.C + // The operation can request a retry by returning true as the first return value. + func (sys *System) runSSHOperation(timeout time.Duration, retries int, operation func(*ssh.Session) (bool, error)) error { + for attempt := 0; attempt <= retries; attempt++ { +- if sys.client.Load() == nil || sys.Status == down { ++ if sys.client.Load() == nil || sys.GetStatus() == down { + if err := sys.createSSHClient(); err != nil { + return err + } +diff --git a/internal/hub/systems/system_manager.go b/internal/hub/systems/system_manager.go +index 4e65ed55..6c14b8d9 100644 +--- a/internal/hub/systems/system_manager.go ++++ b/internal/hub/systems/system_manager.go +@@ -209,8 +209,7 @@ func (sm *SystemManager) onRecordAfterUpdateSuccess(e *core.RecordEvent) error { + prevStatus := pending + system, ok := sm.systems.GetOk(e.Record.Id) + if ok { +- prevStatus = system.Status +- system.Status = newStatus ++ prevStatus = system.swapStatus(newStatus) + } + + switch newStatus { +@@ -335,7 +334,7 @@ func (sm *SystemManager) AddRecord(record *core.Record, system *System) (err err + } + + // Populate system from record +- system.Status = record.GetString("status") ++ system.swapStatus(record.GetString("status")) + system.Host = record.GetString("host") + system.Port = record.GetString("port") + +diff --git a/internal/hub/systems/systems_test_helpers.go b/internal/hub/systems/systems_test_helpers.go +index ca61895f..9e6c4860 100644 +--- a/internal/hub/systems/systems_test_helpers.go ++++ b/internal/hub/systems/systems_test_helpers.go +@@ -38,7 +38,7 @@ func (sm *SystemManager) GetSystemStatusFromStore(systemID string) string { + if !ok { + return "" + } +- return sys.Status ++ return sys.GetStatus() + } + + // TESTING ONLY: GetSystemContextFromStore returns the context and cancel function for a system diff --git a/tasks/henrygd__beszel-2452/tests/test.sh b/tasks/henrygd__beszel-2452/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5cbf80035654bd90bb7832d6b1f3bb49653fbfb5 --- /dev/null +++ b/tasks/henrygd__beszel-2452/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 083b28a1fc5fdf198ef36ac6b4e64dcc1cf98747 > "$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/henrygd__beszel-2452/tests/verifier.py b/tasks/henrygd__beszel-2452/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2452/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/henrygd__beszel-2453/environment/Dockerfile b/tasks/henrygd__beszel-2453/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c491e76c3d2abae9cbf4a79251d72411731e0a75 --- /dev/null +++ b/tasks/henrygd__beszel-2453/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 65f00ae119269113613a39028b7a935693b860e6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 65f00ae119269113613a39028b7a935693b860e6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 65f00ae119269113613a39028b7a935693b860e6 \ + && 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/henrygd__beszel-2453/instruction.md b/tasks/henrygd__beszel-2453/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d3042b9983b4bf405cf1eb9d789fdf8a7d4bbf7a --- /dev/null +++ b/tasks/henrygd__beszel-2453/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(hub): synchronise WebSocket connection access + +## Description + +The WebSocket close callback can clear the connection while the updater checks or uses it. Store the pointer atomically and load it once per operation so ping, close and legacy requests use a consistent reference. + +The new loopback regression reproduces the race before the change. The full WebSocket package passes ten race runs on Linux and macOS, and passes with this patch alone on the base revision. `go vet` and the hub build pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `65f00ae11926`. 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/henrygd__beszel-2453/solution/patch.diff b/tasks/henrygd__beszel-2453/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3915634b5119647932c3d0822527f427162949c0 --- /dev/null +++ b/tasks/henrygd__beszel-2453/solution/patch.diff @@ -0,0 +1,181 @@ +diff --git a/internal/hub/ws/ws.go b/internal/hub/ws/ws.go +index def433a2..7d61e596 100644 +--- a/internal/hub/ws/ws.go ++++ b/internal/hub/ws/ws.go +@@ -3,6 +3,7 @@ package ws + import ( + "context" + "errors" ++ "sync/atomic" + "time" + "weak" + +@@ -26,7 +27,7 @@ type Handler struct { + + // WsConn represents a WebSocket connection to an agent. + type WsConn struct { +- conn *gws.Conn ++ conn atomic.Pointer[gws.Conn] + requestManager *RequestManager + DownChan chan struct{} + agentVersion semver.Version +@@ -54,12 +55,13 @@ func GetUpgrader() *gws.Upgrader { + + // NewWsConnection creates a new WebSocket connection wrapper with agent version. + func NewWsConnection(conn *gws.Conn, agentVersion semver.Version) *WsConn { +- return &WsConn{ +- conn: conn, ++ ws := &WsConn{ + requestManager: NewRequestManager(conn), + DownChan: make(chan struct{}, 1), + agentVersion: agentVersion, + } ++ ws.conn.Store(conn) ++ return ws + } + + // OnOpen sets a deadline for the WebSocket connection and extracts agent version. +@@ -87,7 +89,7 @@ func (h *Handler) OnClose(conn *gws.Conn, err error) { + if !ok { + return + } +- wsConn.(*WsConn).conn = nil ++ wsConn.(*WsConn).conn.Store(nil) + // wait 5 seconds to allow reconnection before setting system down + // use a weak pointer to avoid keeping references if the system is removed + go func(downChan weak.Pointer[chan struct{}]) { +@@ -101,8 +103,8 @@ func (h *Handler) OnClose(conn *gws.Conn, err error) { + + // Close terminates the WebSocket connection gracefully. + func (ws *WsConn) Close(msg []byte) { +- if ws.IsConnected() { +- ws.conn.WriteClose(1000, msg) ++ if conn := ws.conn.Load(); conn != nil { ++ conn.WriteClose(1000, msg) + } + if ws.requestManager != nil { + ws.requestManager.Close() +@@ -111,24 +113,26 @@ func (ws *WsConn) Close(msg []byte) { + + // Ping sends a ping frame to keep the connection alive. + func (ws *WsConn) Ping() error { +- if ws.conn == nil { ++ conn := ws.conn.Load() ++ if conn == nil { + return gws.ErrConnClosed + } +- ws.conn.SetDeadline(time.Now().Add(deadline)) +- return ws.conn.WritePing(nil) ++ conn.SetDeadline(time.Now().Add(deadline)) ++ return conn.WritePing(nil) + } + + // sendMessage encodes data to CBOR and sends it as a binary message to the agent. + // This is kept for backwards compatibility but new actions should use RequestManager. + func (ws *WsConn) sendMessage(data common.HubRequest[any]) error { +- if ws.conn == nil { ++ conn := ws.conn.Load() ++ if conn == nil { + return gws.ErrConnClosed + } + bytes, err := cbor.Marshal(data) + if err != nil { + return err + } +- return ws.conn.WriteMessage(gws.OpcodeBinary, bytes) ++ return conn.WriteMessage(gws.OpcodeBinary, bytes) + } + + // handleAgentRequest processes a request to the agent, handling both legacy and new formats. +@@ -163,7 +167,7 @@ func (ws *WsConn) handleAgentRequest(req *PendingRequest, handler ResponseHandle + + // IsConnected returns true if the WebSocket connection is active. + func (ws *WsConn) IsConnected() bool { +- return ws.conn != nil ++ return ws.conn.Load() != nil + } + + // AgentVersion returns the connected agent's version (as reported during handshake). +diff --git a/internal/hub/ws/ws_lifecycle_test.go b/internal/hub/ws/ws_lifecycle_test.go +new file mode 100644 +index 00000000..abcdc076 +--- /dev/null ++++ b/internal/hub/ws/ws_lifecycle_test.go +@@ -0,0 +1,64 @@ ++//go:build testing ++ ++package ws ++ ++import ( ++ "net/http" ++ "net/http/httptest" ++ "strings" ++ "testing" ++ ++ "github.com/blang/semver" ++ "github.com/henrygd/beszel/internal/common" ++ "github.com/lxzan/gws" ++ "github.com/stretchr/testify/require" ++) ++ ++func TestWsConnConcurrentClose(t *testing.T) { ++ connections := make(chan *WsConn, 1) ++ serverDone := make(chan struct{}) ++ upgrader := gws.NewUpgrader(&Handler{}, &gws.ServerOption{}) ++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ++ defer close(serverDone) ++ conn, err := upgrader.Upgrade(w, r) ++ if err != nil { ++ t.Error(err) ++ return ++ } ++ ws := NewWsConnection(conn, semver.MustParse("0.12.10")) ++ conn.Session().Store("wsConn", ws) ++ connections <- ws ++ conn.ReadLoop() ++ })) ++ defer server.Close() ++ client, _, err := gws.NewClient(&gws.BuiltinEventHandler{}, &gws.ClientOption{ ++ Addr: "ws" + strings.TrimPrefix(server.URL, "http"), ++ }) ++ require.NoError(t, err) ++ defer client.WriteClose(1000, nil) ++ ws := <-connections ++ require.True(t, ws.IsConnected()) ++ ++ readerReady := make(chan struct{}) ++ readerDone := make(chan struct{}) ++ go func() { ++ defer close(readerDone) ++ close(readerReady) ++ for { ++ select { ++ case <-serverDone: ++ return ++ default: ++ ws.IsConnected() ++ } ++ } ++ }() ++ <-readerReady ++ require.NoError(t, client.WriteClose(1000, nil)) ++ <-readerDone ++ ++ require.False(t, ws.IsConnected()) ++ require.ErrorIs(t, ws.Ping(), gws.ErrConnClosed) ++ require.ErrorIs(t, ws.sendMessage(common.HubRequest[any]{}), gws.ErrConnClosed) ++ ws.Close(nil) ++} +diff --git a/internal/hub/ws/ws_test.go b/internal/hub/ws/ws_test.go +index bdbc4cb2..9970cf47 100644 +--- a/internal/hub/ws/ws_test.go ++++ b/internal/hub/ws/ws_test.go +@@ -39,7 +39,7 @@ func TestNewWsConnection(t *testing.T) { + wsConn := NewWsConnection(nil, semver.MustParse("0.12.10")) + + assert.NotNil(t, wsConn, "WebSocket connection should not be nil") +- assert.Nil(t, wsConn.conn, "Connection should be nil as passed") ++ assert.Nil(t, wsConn.conn.Load(), "Connection should be nil as passed") + assert.NotNil(t, wsConn.requestManager, "Request manager should be initialized") + assert.NotNil(t, wsConn.DownChan, "Down channel should be initialized") + assert.Equal(t, 1, cap(wsConn.DownChan), "Down channel should have capacity of 1") diff --git a/tasks/henrygd__beszel-2453/solution/solve.sh b/tasks/henrygd__beszel-2453/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2453/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/henrygd__beszel-2453/task.toml b/tasks/henrygd__beszel-2453/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8de2748e03f16e0951d16ccececd9eeed841fb3a --- /dev/null +++ b/tasks/henrygd__beszel-2453/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2453" +description = "fix(hub): synchronise WebSocket connection access" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "65f00ae119269113613a39028b7a935693b860e6" +reference = "https://github.com/henrygd/beszel/pull/2453" +source_access = "auto" +built_at = "2026-11-16T16:09:53.471758+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e06a8b772c759b3189d5f34391b697b48df6506b2c3e14672ce1ca3b8a259ed5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T23:12:01Z" +diff_format = "unified" +context_files = [ + "internal/hub/ws/ws.go", + "internal/hub/ws/ws_lifecycle_test.go", + "internal/hub/ws/ws_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 94 +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:00.827161+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d6e5769e8c4318cc71a1c0fcd74d8f70f0d08689cfb4e5c6064eb2e21988f11f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2453/tests/capture.py b/tasks/henrygd__beszel-2453/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2453/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/henrygd__beszel-2453/tests/instruction.md b/tasks/henrygd__beszel-2453/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d3042b9983b4bf405cf1eb9d789fdf8a7d4bbf7a --- /dev/null +++ b/tasks/henrygd__beszel-2453/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(hub): synchronise WebSocket connection access + +## Description + +The WebSocket close callback can clear the connection while the updater checks or uses it. Store the pointer atomically and load it once per operation so ping, close and legacy requests use a consistent reference. + +The new loopback regression reproduces the race before the change. The full WebSocket package passes ten race runs on Linux and macOS, and passes with this patch alone on the base revision. `go vet` and the hub build pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `65f00ae11926`. 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/henrygd__beszel-2453/tests/oracle.patch b/tasks/henrygd__beszel-2453/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3915634b5119647932c3d0822527f427162949c0 --- /dev/null +++ b/tasks/henrygd__beszel-2453/tests/oracle.patch @@ -0,0 +1,181 @@ +diff --git a/internal/hub/ws/ws.go b/internal/hub/ws/ws.go +index def433a2..7d61e596 100644 +--- a/internal/hub/ws/ws.go ++++ b/internal/hub/ws/ws.go +@@ -3,6 +3,7 @@ package ws + import ( + "context" + "errors" ++ "sync/atomic" + "time" + "weak" + +@@ -26,7 +27,7 @@ type Handler struct { + + // WsConn represents a WebSocket connection to an agent. + type WsConn struct { +- conn *gws.Conn ++ conn atomic.Pointer[gws.Conn] + requestManager *RequestManager + DownChan chan struct{} + agentVersion semver.Version +@@ -54,12 +55,13 @@ func GetUpgrader() *gws.Upgrader { + + // NewWsConnection creates a new WebSocket connection wrapper with agent version. + func NewWsConnection(conn *gws.Conn, agentVersion semver.Version) *WsConn { +- return &WsConn{ +- conn: conn, ++ ws := &WsConn{ + requestManager: NewRequestManager(conn), + DownChan: make(chan struct{}, 1), + agentVersion: agentVersion, + } ++ ws.conn.Store(conn) ++ return ws + } + + // OnOpen sets a deadline for the WebSocket connection and extracts agent version. +@@ -87,7 +89,7 @@ func (h *Handler) OnClose(conn *gws.Conn, err error) { + if !ok { + return + } +- wsConn.(*WsConn).conn = nil ++ wsConn.(*WsConn).conn.Store(nil) + // wait 5 seconds to allow reconnection before setting system down + // use a weak pointer to avoid keeping references if the system is removed + go func(downChan weak.Pointer[chan struct{}]) { +@@ -101,8 +103,8 @@ func (h *Handler) OnClose(conn *gws.Conn, err error) { + + // Close terminates the WebSocket connection gracefully. + func (ws *WsConn) Close(msg []byte) { +- if ws.IsConnected() { +- ws.conn.WriteClose(1000, msg) ++ if conn := ws.conn.Load(); conn != nil { ++ conn.WriteClose(1000, msg) + } + if ws.requestManager != nil { + ws.requestManager.Close() +@@ -111,24 +113,26 @@ func (ws *WsConn) Close(msg []byte) { + + // Ping sends a ping frame to keep the connection alive. + func (ws *WsConn) Ping() error { +- if ws.conn == nil { ++ conn := ws.conn.Load() ++ if conn == nil { + return gws.ErrConnClosed + } +- ws.conn.SetDeadline(time.Now().Add(deadline)) +- return ws.conn.WritePing(nil) ++ conn.SetDeadline(time.Now().Add(deadline)) ++ return conn.WritePing(nil) + } + + // sendMessage encodes data to CBOR and sends it as a binary message to the agent. + // This is kept for backwards compatibility but new actions should use RequestManager. + func (ws *WsConn) sendMessage(data common.HubRequest[any]) error { +- if ws.conn == nil { ++ conn := ws.conn.Load() ++ if conn == nil { + return gws.ErrConnClosed + } + bytes, err := cbor.Marshal(data) + if err != nil { + return err + } +- return ws.conn.WriteMessage(gws.OpcodeBinary, bytes) ++ return conn.WriteMessage(gws.OpcodeBinary, bytes) + } + + // handleAgentRequest processes a request to the agent, handling both legacy and new formats. +@@ -163,7 +167,7 @@ func (ws *WsConn) handleAgentRequest(req *PendingRequest, handler ResponseHandle + + // IsConnected returns true if the WebSocket connection is active. + func (ws *WsConn) IsConnected() bool { +- return ws.conn != nil ++ return ws.conn.Load() != nil + } + + // AgentVersion returns the connected agent's version (as reported during handshake). +diff --git a/internal/hub/ws/ws_lifecycle_test.go b/internal/hub/ws/ws_lifecycle_test.go +new file mode 100644 +index 00000000..abcdc076 +--- /dev/null ++++ b/internal/hub/ws/ws_lifecycle_test.go +@@ -0,0 +1,64 @@ ++//go:build testing ++ ++package ws ++ ++import ( ++ "net/http" ++ "net/http/httptest" ++ "strings" ++ "testing" ++ ++ "github.com/blang/semver" ++ "github.com/henrygd/beszel/internal/common" ++ "github.com/lxzan/gws" ++ "github.com/stretchr/testify/require" ++) ++ ++func TestWsConnConcurrentClose(t *testing.T) { ++ connections := make(chan *WsConn, 1) ++ serverDone := make(chan struct{}) ++ upgrader := gws.NewUpgrader(&Handler{}, &gws.ServerOption{}) ++ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ++ defer close(serverDone) ++ conn, err := upgrader.Upgrade(w, r) ++ if err != nil { ++ t.Error(err) ++ return ++ } ++ ws := NewWsConnection(conn, semver.MustParse("0.12.10")) ++ conn.Session().Store("wsConn", ws) ++ connections <- ws ++ conn.ReadLoop() ++ })) ++ defer server.Close() ++ client, _, err := gws.NewClient(&gws.BuiltinEventHandler{}, &gws.ClientOption{ ++ Addr: "ws" + strings.TrimPrefix(server.URL, "http"), ++ }) ++ require.NoError(t, err) ++ defer client.WriteClose(1000, nil) ++ ws := <-connections ++ require.True(t, ws.IsConnected()) ++ ++ readerReady := make(chan struct{}) ++ readerDone := make(chan struct{}) ++ go func() { ++ defer close(readerDone) ++ close(readerReady) ++ for { ++ select { ++ case <-serverDone: ++ return ++ default: ++ ws.IsConnected() ++ } ++ } ++ }() ++ <-readerReady ++ require.NoError(t, client.WriteClose(1000, nil)) ++ <-readerDone ++ ++ require.False(t, ws.IsConnected()) ++ require.ErrorIs(t, ws.Ping(), gws.ErrConnClosed) ++ require.ErrorIs(t, ws.sendMessage(common.HubRequest[any]{}), gws.ErrConnClosed) ++ ws.Close(nil) ++} +diff --git a/internal/hub/ws/ws_test.go b/internal/hub/ws/ws_test.go +index bdbc4cb2..9970cf47 100644 +--- a/internal/hub/ws/ws_test.go ++++ b/internal/hub/ws/ws_test.go +@@ -39,7 +39,7 @@ func TestNewWsConnection(t *testing.T) { + wsConn := NewWsConnection(nil, semver.MustParse("0.12.10")) + + assert.NotNil(t, wsConn, "WebSocket connection should not be nil") +- assert.Nil(t, wsConn.conn, "Connection should be nil as passed") ++ assert.Nil(t, wsConn.conn.Load(), "Connection should be nil as passed") + assert.NotNil(t, wsConn.requestManager, "Request manager should be initialized") + assert.NotNil(t, wsConn.DownChan, "Down channel should be initialized") + assert.Equal(t, 1, cap(wsConn.DownChan), "Down channel should have capacity of 1") diff --git a/tasks/henrygd__beszel-2453/tests/test.sh b/tasks/henrygd__beszel-2453/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..092b9ca2038eb748475172238eebac10a4bd623e --- /dev/null +++ b/tasks/henrygd__beszel-2453/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 65f00ae119269113613a39028b7a935693b860e6 > "$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/henrygd__beszel-2453/tests/verifier.py b/tasks/henrygd__beszel-2453/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2453/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/henrygd__beszel-2454/environment/Dockerfile b/tasks/henrygd__beszel-2454/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c491e76c3d2abae9cbf4a79251d72411731e0a75 --- /dev/null +++ b/tasks/henrygd__beszel-2454/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 65f00ae119269113613a39028b7a935693b860e6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 65f00ae119269113613a39028b7a935693b860e6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 65f00ae119269113613a39028b7a935693b860e6 \ + && 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/henrygd__beszel-2454/instruction.md b/tasks/henrygd__beszel-2454/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5bcd159d1afab6621fb4799ba823a238924f84d1 --- /dev/null +++ b/tasks/henrygd__beszel-2454/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(hub): pad short monitor IDs to the schema minimum + +## Description + +Some monitor configurations produce a hash shorter than the record schema's six-character minimum, causing creation or configuration updates to fail validation. Pad only those short monitor IDs, preserving existing valid IDs and the shared hash used by other records. + +The regression reproduces HTTP 400 for authenticated creation and configuration updates before the fix, then reads back the corrected record afterwards. Existing ID and batch-creation controls pass under the race detector. The same patch passes its focused race checks on the base revision without other changes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `65f00ae11926`. 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/henrygd__beszel-2454/solution/patch.diff b/tasks/henrygd__beszel-2454/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3f64f5f0b46ac5e7aa46c614cdad5515828f2f27 --- /dev/null +++ b/tasks/henrygd__beszel-2454/solution/patch.diff @@ -0,0 +1,105 @@ +diff --git a/internal/hub/network_monitors.go b/internal/hub/network_monitors.go +index 98e9e0e8..89415bf8 100644 +--- a/internal/hub/network_monitors.go ++++ b/internal/hub/network_monitors.go +@@ -1,6 +1,7 @@ + package hub + + import ( ++ "fmt" + "strconv" + "time" + +@@ -21,7 +22,8 @@ func generateMonitorID(systemId string, config monitor.Config) string { + if config.Protocol == "dns" { + args = append(args, config.Server) + } +- return systems.MakeStableHashId(args...) ++ // Meet the record ID minimum without changing existing IDs of six or more characters. ++ return fmt.Sprintf("%06s", systems.MakeStableHashId(args...)) + } + + // bindNetworkMonitorsEvents keeps monitor records and agent monitor state in sync. +diff --git a/internal/hub/network_monitors_test.go b/internal/hub/network_monitors_test.go +index c0d60b3d..71dd4b82 100644 +--- a/internal/hub/network_monitors_test.go ++++ b/internal/hub/network_monitors_test.go +@@ -87,6 +87,18 @@ func TestGenerateMonitorID(t *testing.T) { + config monitor.Config + expected string + }{ ++ { ++ name: "Short hash meets the record ID minimum", ++ systemID: "000000000012369", ++ config: monitor.Config{Protocol: "icmp", Target: "gateway.example.com"}, ++ expected: "0b3fd2", ++ }, ++ { ++ name: "Existing six-character ID is unchanged", ++ systemID: "000000000000274", ++ config: monitor.Config{Protocol: "icmp", Target: "gateway.example.com"}, ++ expected: "77a996", ++ }, + { + name: "HTTP monitor on example.com", + systemID: "sys123", +@@ -217,6 +229,59 @@ func TestGenerateMonitorID(t *testing.T) { + } + } + ++func TestNetworkMonitorShortIDRequests(t *testing.T) { ++ for _, method := range []string{http.MethodPost, http.MethodPatch} { ++ t.Run(method, func(t *testing.T) { ++ hub, testApp, err := createTestHub(t) ++ require.NoError(t, err) ++ defer cleanupTestHub(hub, testApp) ++ bindNetworkMonitorsEvents(hub) ++ user, err := createTestUser(hub) ++ require.NoError(t, err) ++ system, err := createTestRecord(hub, "systems", map[string]any{ ++ "id": "000000000012369", "name": "Paused", "host": "localhost", "port": "45876", ++ "status": "paused", "users": []string{user.Id}, ++ }) ++ require.NoError(t, err) ++ payload := map[string]any{ ++ "system": system.Id, "target": "gateway.example.com", "protocol": "icmp", ++ "interval": 60, "enabled": true, ++ } ++ url := "/api/collections/network_monitors/records" ++ var oldID string ++ if method == http.MethodPatch { ++ previous, err := createTestRecord(hub, "network_monitors", map[string]any{ ++ "system": system.Id, "target": "website.example.com", "protocol": "icmp", "interval": 60, ++ }) ++ require.NoError(t, err) ++ oldID = previous.Id ++ url += "/" + oldID ++ } ++ data, err := json.Marshal(payload) ++ require.NoError(t, err) ++ token, err := user.NewAuthToken() ++ require.NoError(t, err) ++ router, err := apis.NewRouter(hub) ++ require.NoError(t, err) ++ handler, err := router.BuildMux() ++ require.NoError(t, err) ++ request := httptest.NewRequest(method, url, bytes.NewReader(data)) ++ request.Header.Set("Content-Type", "application/json") ++ request.Header.Set("Authorization", token) ++ response := httptest.NewRecorder() ++ handler.ServeHTTP(response, request) ++ require.Equal(t, http.StatusOK, response.Code, response.Body.String()) ++ record, err := hub.FindRecordById("network_monitors", "0b3fd2") ++ require.NoError(t, err) ++ assert.Equal(t, "gateway.example.com", record.GetString("target")) ++ if oldID != "" { ++ _, err = hub.FindRecordById("network_monitors", oldID) ++ require.Error(t, err) ++ } ++ }) ++ } ++} ++ + func TestCopyMonitorToNewRecordDropsResultFields(t *testing.T) { + hub, testApp, err := createTestHub(t) + require.NoError(t, err) diff --git a/tasks/henrygd__beszel-2454/solution/solve.sh b/tasks/henrygd__beszel-2454/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2454/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/henrygd__beszel-2454/task.toml b/tasks/henrygd__beszel-2454/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8c3cba5eb4851393e346726c1da4965201c97e9e --- /dev/null +++ b/tasks/henrygd__beszel-2454/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2454" +description = "fix(hub): pad short monitor IDs to the schema minimum" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "65f00ae119269113613a39028b7a935693b860e6" +reference = "https://github.com/henrygd/beszel/pull/2454" +source_access = "auto" +built_at = "2026-11-16T16:09:53.468480+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:db15c74fdbb717053fce9aa3bff28df7e6236ee81d2da56c2beb9acc9c55d521" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T23:48:58Z" +diff_format = "unified" +context_files = [ + "internal/hub/network_monitors.go", + "internal/hub/network_monitors_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 69 +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:00.827606+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d6e5769e8c4318cc71a1c0fcd74d8f70f0d08689cfb4e5c6064eb2e21988f11f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2454/tests/capture.py b/tasks/henrygd__beszel-2454/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2454/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/henrygd__beszel-2454/tests/instruction.md b/tasks/henrygd__beszel-2454/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5bcd159d1afab6621fb4799ba823a238924f84d1 --- /dev/null +++ b/tasks/henrygd__beszel-2454/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(hub): pad short monitor IDs to the schema minimum + +## Description + +Some monitor configurations produce a hash shorter than the record schema's six-character minimum, causing creation or configuration updates to fail validation. Pad only those short monitor IDs, preserving existing valid IDs and the shared hash used by other records. + +The regression reproduces HTTP 400 for authenticated creation and configuration updates before the fix, then reads back the corrected record afterwards. Existing ID and batch-creation controls pass under the race detector. The same patch passes its focused race checks on the base revision without other changes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `65f00ae11926`. 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/henrygd__beszel-2454/tests/oracle.patch b/tasks/henrygd__beszel-2454/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3f64f5f0b46ac5e7aa46c614cdad5515828f2f27 --- /dev/null +++ b/tasks/henrygd__beszel-2454/tests/oracle.patch @@ -0,0 +1,105 @@ +diff --git a/internal/hub/network_monitors.go b/internal/hub/network_monitors.go +index 98e9e0e8..89415bf8 100644 +--- a/internal/hub/network_monitors.go ++++ b/internal/hub/network_monitors.go +@@ -1,6 +1,7 @@ + package hub + + import ( ++ "fmt" + "strconv" + "time" + +@@ -21,7 +22,8 @@ func generateMonitorID(systemId string, config monitor.Config) string { + if config.Protocol == "dns" { + args = append(args, config.Server) + } +- return systems.MakeStableHashId(args...) ++ // Meet the record ID minimum without changing existing IDs of six or more characters. ++ return fmt.Sprintf("%06s", systems.MakeStableHashId(args...)) + } + + // bindNetworkMonitorsEvents keeps monitor records and agent monitor state in sync. +diff --git a/internal/hub/network_monitors_test.go b/internal/hub/network_monitors_test.go +index c0d60b3d..71dd4b82 100644 +--- a/internal/hub/network_monitors_test.go ++++ b/internal/hub/network_monitors_test.go +@@ -87,6 +87,18 @@ func TestGenerateMonitorID(t *testing.T) { + config monitor.Config + expected string + }{ ++ { ++ name: "Short hash meets the record ID minimum", ++ systemID: "000000000012369", ++ config: monitor.Config{Protocol: "icmp", Target: "gateway.example.com"}, ++ expected: "0b3fd2", ++ }, ++ { ++ name: "Existing six-character ID is unchanged", ++ systemID: "000000000000274", ++ config: monitor.Config{Protocol: "icmp", Target: "gateway.example.com"}, ++ expected: "77a996", ++ }, + { + name: "HTTP monitor on example.com", + systemID: "sys123", +@@ -217,6 +229,59 @@ func TestGenerateMonitorID(t *testing.T) { + } + } + ++func TestNetworkMonitorShortIDRequests(t *testing.T) { ++ for _, method := range []string{http.MethodPost, http.MethodPatch} { ++ t.Run(method, func(t *testing.T) { ++ hub, testApp, err := createTestHub(t) ++ require.NoError(t, err) ++ defer cleanupTestHub(hub, testApp) ++ bindNetworkMonitorsEvents(hub) ++ user, err := createTestUser(hub) ++ require.NoError(t, err) ++ system, err := createTestRecord(hub, "systems", map[string]any{ ++ "id": "000000000012369", "name": "Paused", "host": "localhost", "port": "45876", ++ "status": "paused", "users": []string{user.Id}, ++ }) ++ require.NoError(t, err) ++ payload := map[string]any{ ++ "system": system.Id, "target": "gateway.example.com", "protocol": "icmp", ++ "interval": 60, "enabled": true, ++ } ++ url := "/api/collections/network_monitors/records" ++ var oldID string ++ if method == http.MethodPatch { ++ previous, err := createTestRecord(hub, "network_monitors", map[string]any{ ++ "system": system.Id, "target": "website.example.com", "protocol": "icmp", "interval": 60, ++ }) ++ require.NoError(t, err) ++ oldID = previous.Id ++ url += "/" + oldID ++ } ++ data, err := json.Marshal(payload) ++ require.NoError(t, err) ++ token, err := user.NewAuthToken() ++ require.NoError(t, err) ++ router, err := apis.NewRouter(hub) ++ require.NoError(t, err) ++ handler, err := router.BuildMux() ++ require.NoError(t, err) ++ request := httptest.NewRequest(method, url, bytes.NewReader(data)) ++ request.Header.Set("Content-Type", "application/json") ++ request.Header.Set("Authorization", token) ++ response := httptest.NewRecorder() ++ handler.ServeHTTP(response, request) ++ require.Equal(t, http.StatusOK, response.Code, response.Body.String()) ++ record, err := hub.FindRecordById("network_monitors", "0b3fd2") ++ require.NoError(t, err) ++ assert.Equal(t, "gateway.example.com", record.GetString("target")) ++ if oldID != "" { ++ _, err = hub.FindRecordById("network_monitors", oldID) ++ require.Error(t, err) ++ } ++ }) ++ } ++} ++ + func TestCopyMonitorToNewRecordDropsResultFields(t *testing.T) { + hub, testApp, err := createTestHub(t) + require.NoError(t, err) diff --git a/tasks/henrygd__beszel-2454/tests/test.sh b/tasks/henrygd__beszel-2454/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..092b9ca2038eb748475172238eebac10a4bd623e --- /dev/null +++ b/tasks/henrygd__beszel-2454/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 65f00ae119269113613a39028b7a935693b860e6 > "$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/henrygd__beszel-2454/tests/verifier.py b/tasks/henrygd__beszel-2454/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2454/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/henrygd__beszel-2456/environment/Dockerfile b/tasks/henrygd__beszel-2456/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..48d250d8e19b372cd6b3c879048b396bd1114674 --- /dev/null +++ b/tasks/henrygd__beszel-2456/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4422be717c3e3cb2e58ebac9c0bebbd30d94e2a1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4422be717c3e3cb2e58ebac9c0bebbd30d94e2a1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4422be717c3e3cb2e58ebac9c0bebbd30d94e2a1 \ + && 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/henrygd__beszel-2456/instruction.md b/tasks/henrygd__beszel-2456/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eddaa46f138b1d58f296ce1e9cb3c6337a30323b --- /dev/null +++ b/tasks/henrygd__beszel-2456/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(hub): prevent caching of authenticated systemd details + +## Description + +Systemd details are returned after checking access to the selected system, but the response advertises `public, max-age=60`. A shared cache can then serve that response to another user without reaching those checks. Send `private, no-store` so each request is authorised. + +The HTTP regression covers an owner, an unrelated user, an unauthenticated request and `SHARE_ALL_SYSTEMS` with a loopback agent. A Squid replay reproduced shared-cache reuse before the change and confirmed denied requests reach the hub afterwards. Hub tests, the focused race test, `go vet` and the production hub build pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4422be717c3e`. 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/henrygd__beszel-2456/solution/patch.diff b/tasks/henrygd__beszel-2456/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6cd0fdaacbade232f39ae2687dbab6638539f443 --- /dev/null +++ b/tasks/henrygd__beszel-2456/solution/patch.diff @@ -0,0 +1,127 @@ +diff --git a/internal/hub/api.go b/internal/hub/api.go +index 9d48960f..ebe5e373 100644 +--- a/internal/hub/api.go ++++ b/internal/hub/api.go +@@ -446,7 +446,8 @@ func (h *Hub) getSystemdInfo(e *core.RequestEvent) error { + if err != nil { + return e.InternalServerError("", err) + } +- e.Response.Header().Set("Cache-Control", "public, max-age=60") ++ e.Response.Header().Set("Cache-Control", "private, max-age=60") ++ e.Response.Header().Add("Vary", "Authorization") + return e.JSON(http.StatusOK, map[string]any{"details": details}) + } + +diff --git a/internal/hub/api_systemd_test.go b/internal/hub/api_systemd_test.go +new file mode 100644 +index 00000000..93ab194e +--- /dev/null ++++ b/internal/hub/api_systemd_test.go +@@ -0,0 +1,107 @@ ++package hub_test ++ ++import ( ++ "io" ++ "net" ++ "net/http" ++ "net/http/httptest" ++ "sync/atomic" ++ "testing" ++ ++ "github.com/fxamacker/cbor/v2" ++ "github.com/gliderlabs/ssh" ++ "github.com/henrygd/beszel/internal/common" ++ beszelTests "github.com/henrygd/beszel/internal/tests" ++ "github.com/stretchr/testify/require" ++) ++ ++func systemdInfoTestHandler(t *testing.T) (http.Handler, string, string, string, *atomic.Int32) { ++ t.Helper() ++ hub, handler := firstUserTestMux(t) ++ t.Cleanup(hub.Cleanup) ++ owner, err := beszelTests.CreateUserWithRole(hub, "owner@example.com", "password123", "user") ++ require.NoError(t, err) ++ other, err := beszelTests.CreateUserWithRole(hub, "other@example.com", "password123", "user") ++ require.NoError(t, err) ++ ownerToken, err := owner.NewAuthToken() ++ require.NoError(t, err) ++ otherToken, err := other.NewAuthToken() ++ require.NoError(t, err) ++ ++ var requests atomic.Int32 ++ agent := &ssh.Server{Version: "beszel_0.20.0", Handler: func(s ssh.Session) { ++ var request common.HubRequest[common.SystemdInfoRequest] ++ if err := cbor.NewDecoder(s).Decode(&request); err != nil { ++ t.Error(err) ++ return ++ } ++ if request.Action != common.GetSystemdInfo || request.Data.ServiceName != "private.service" { ++ t.Errorf("unexpected agent request: %+v", request) ++ return ++ } ++ requests.Add(1) ++ data, err := cbor.Marshal(map[string]any{"Description": "private service details"}) ++ if err == nil { ++ err = cbor.NewEncoder(s).Encode(common.AgentResponse{Data: data}) ++ } ++ if err != nil { ++ t.Error(err) ++ } ++ }} ++ listener, err := net.Listen("tcp", "127.0.0.1:0") ++ require.NoError(t, err) ++ t.Cleanup(func() { _ = agent.Close() }) ++ go func() { _ = agent.Serve(listener) }() ++ host, port, err := net.SplitHostPort(listener.Addr().String()) ++ require.NoError(t, err) ++ record, err := beszelTests.CreateRecord(hub, "systems", map[string]any{ ++ "name": "test-system", "host": host, "port": port, "users": []string{owner.Id}, ++ }) ++ require.NoError(t, err) ++ system, err := hub.GetSystemManager().GetSystem(record.Id) ++ require.NoError(t, err) ++ system.StopUpdater() ++ _, err = beszelTests.CreateRecord(hub, "systemd_services", map[string]any{ ++ "system": record.Id, "name": "private.service", "state": 0, "sub": 1, ++ }) ++ require.NoError(t, err) ++ return handler, "/api/beszel/systemd/info?system=" + record.Id + "&service=private.service", ownerToken, otherToken, &requests ++} ++ ++func TestSystemdInfoCachePolicy(t *testing.T) { ++ t.Setenv("SHARE_ALL_SYSTEMS", "false") ++ t.Setenv("BESZEL_HUB_SHARE_ALL_SYSTEMS", "false") ++ handler, path, owner, other, requests := systemdInfoTestHandler(t) ++ for _, tc := range []struct { ++ name, token, shareAll string ++ status int ++ }{ ++ {"owner", owner, "false", http.StatusOK}, ++ {"other user", other, "false", http.StatusNotFound}, ++ {"unauthenticated", "", "false", http.StatusUnauthorized}, ++ {"shared system", other, "true", http.StatusOK}, ++ } { ++ t.Run(tc.name, func(t *testing.T) { ++ t.Setenv("SHARE_ALL_SYSTEMS", tc.shareAll) ++ t.Setenv("BESZEL_HUB_SHARE_ALL_SYSTEMS", tc.shareAll) ++ req := httptest.NewRequest(http.MethodGet, path, nil) ++ req.Header.Set("Authorization", tc.token) ++ recorder := httptest.NewRecorder() ++ handler.ServeHTTP(recorder, req) ++ response := recorder.Result() ++ defer response.Body.Close() ++ body, err := io.ReadAll(response.Body) ++ require.NoError(t, err) ++ require.Equal(t, tc.status, response.StatusCode) ++ if tc.status == http.StatusOK { ++ require.JSONEq(t, `{"details":{"Description":"private service details"}}`, string(body)) ++ require.Equal(t, "private, max-age=60", response.Header.Get("Cache-Control")) ++ require.Contains(t, response.Header.Values("Vary"), "Authorization") ++ } else { ++ require.NotContains(t, string(body), "private service details") ++ require.NotContains(t, response.Header.Get("Cache-Control"), "public") ++ } ++ }) ++ } ++ require.EqualValues(t, 2, requests.Load(), "only authorised requests should reach the agent") ++} diff --git a/tasks/henrygd__beszel-2456/solution/solve.sh b/tasks/henrygd__beszel-2456/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2456/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/henrygd__beszel-2456/task.toml b/tasks/henrygd__beszel-2456/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..90f93d24f987297becdda79b34ebdaca6ca3c286 --- /dev/null +++ b/tasks/henrygd__beszel-2456/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2456" +description = "fix(hub): prevent caching of authenticated systemd details" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "4422be717c3e3cb2e58ebac9c0bebbd30d94e2a1" +reference = "https://github.com/henrygd/beszel/pull/2456" +source_access = "auto" +built_at = "2026-11-16T16:09:53.451690+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e68bb388a9aa0e39dedfc21f4c2af5a77d77272da9fff067f38d6bd1babba14f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-29T14:54:17Z" +diff_format = "unified" +context_files = [ + "internal/hub/api.go", + "internal/hub/api_systemd_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 110 +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:00.828051+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4d3dc1073c8072f8922acfdb4f79979d14124dd2a700930d4a3e1918926e5c17" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2456/tests/capture.py b/tasks/henrygd__beszel-2456/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2456/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/henrygd__beszel-2456/tests/instruction.md b/tasks/henrygd__beszel-2456/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eddaa46f138b1d58f296ce1e9cb3c6337a30323b --- /dev/null +++ b/tasks/henrygd__beszel-2456/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** fix(hub): prevent caching of authenticated systemd details + +## Description + +Systemd details are returned after checking access to the selected system, but the response advertises `public, max-age=60`. A shared cache can then serve that response to another user without reaching those checks. Send `private, no-store` so each request is authorised. + +The HTTP regression covers an owner, an unrelated user, an unauthenticated request and `SHARE_ALL_SYSTEMS` with a loopback agent. A Squid replay reproduced shared-cache reuse before the change and confirmed denied requests reach the hub afterwards. Hub tests, the focused race test, `go vet` and the production hub build pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4422be717c3e`. 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/henrygd__beszel-2456/tests/oracle.patch b/tasks/henrygd__beszel-2456/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6cd0fdaacbade232f39ae2687dbab6638539f443 --- /dev/null +++ b/tasks/henrygd__beszel-2456/tests/oracle.patch @@ -0,0 +1,127 @@ +diff --git a/internal/hub/api.go b/internal/hub/api.go +index 9d48960f..ebe5e373 100644 +--- a/internal/hub/api.go ++++ b/internal/hub/api.go +@@ -446,7 +446,8 @@ func (h *Hub) getSystemdInfo(e *core.RequestEvent) error { + if err != nil { + return e.InternalServerError("", err) + } +- e.Response.Header().Set("Cache-Control", "public, max-age=60") ++ e.Response.Header().Set("Cache-Control", "private, max-age=60") ++ e.Response.Header().Add("Vary", "Authorization") + return e.JSON(http.StatusOK, map[string]any{"details": details}) + } + +diff --git a/internal/hub/api_systemd_test.go b/internal/hub/api_systemd_test.go +new file mode 100644 +index 00000000..93ab194e +--- /dev/null ++++ b/internal/hub/api_systemd_test.go +@@ -0,0 +1,107 @@ ++package hub_test ++ ++import ( ++ "io" ++ "net" ++ "net/http" ++ "net/http/httptest" ++ "sync/atomic" ++ "testing" ++ ++ "github.com/fxamacker/cbor/v2" ++ "github.com/gliderlabs/ssh" ++ "github.com/henrygd/beszel/internal/common" ++ beszelTests "github.com/henrygd/beszel/internal/tests" ++ "github.com/stretchr/testify/require" ++) ++ ++func systemdInfoTestHandler(t *testing.T) (http.Handler, string, string, string, *atomic.Int32) { ++ t.Helper() ++ hub, handler := firstUserTestMux(t) ++ t.Cleanup(hub.Cleanup) ++ owner, err := beszelTests.CreateUserWithRole(hub, "owner@example.com", "password123", "user") ++ require.NoError(t, err) ++ other, err := beszelTests.CreateUserWithRole(hub, "other@example.com", "password123", "user") ++ require.NoError(t, err) ++ ownerToken, err := owner.NewAuthToken() ++ require.NoError(t, err) ++ otherToken, err := other.NewAuthToken() ++ require.NoError(t, err) ++ ++ var requests atomic.Int32 ++ agent := &ssh.Server{Version: "beszel_0.20.0", Handler: func(s ssh.Session) { ++ var request common.HubRequest[common.SystemdInfoRequest] ++ if err := cbor.NewDecoder(s).Decode(&request); err != nil { ++ t.Error(err) ++ return ++ } ++ if request.Action != common.GetSystemdInfo || request.Data.ServiceName != "private.service" { ++ t.Errorf("unexpected agent request: %+v", request) ++ return ++ } ++ requests.Add(1) ++ data, err := cbor.Marshal(map[string]any{"Description": "private service details"}) ++ if err == nil { ++ err = cbor.NewEncoder(s).Encode(common.AgentResponse{Data: data}) ++ } ++ if err != nil { ++ t.Error(err) ++ } ++ }} ++ listener, err := net.Listen("tcp", "127.0.0.1:0") ++ require.NoError(t, err) ++ t.Cleanup(func() { _ = agent.Close() }) ++ go func() { _ = agent.Serve(listener) }() ++ host, port, err := net.SplitHostPort(listener.Addr().String()) ++ require.NoError(t, err) ++ record, err := beszelTests.CreateRecord(hub, "systems", map[string]any{ ++ "name": "test-system", "host": host, "port": port, "users": []string{owner.Id}, ++ }) ++ require.NoError(t, err) ++ system, err := hub.GetSystemManager().GetSystem(record.Id) ++ require.NoError(t, err) ++ system.StopUpdater() ++ _, err = beszelTests.CreateRecord(hub, "systemd_services", map[string]any{ ++ "system": record.Id, "name": "private.service", "state": 0, "sub": 1, ++ }) ++ require.NoError(t, err) ++ return handler, "/api/beszel/systemd/info?system=" + record.Id + "&service=private.service", ownerToken, otherToken, &requests ++} ++ ++func TestSystemdInfoCachePolicy(t *testing.T) { ++ t.Setenv("SHARE_ALL_SYSTEMS", "false") ++ t.Setenv("BESZEL_HUB_SHARE_ALL_SYSTEMS", "false") ++ handler, path, owner, other, requests := systemdInfoTestHandler(t) ++ for _, tc := range []struct { ++ name, token, shareAll string ++ status int ++ }{ ++ {"owner", owner, "false", http.StatusOK}, ++ {"other user", other, "false", http.StatusNotFound}, ++ {"unauthenticated", "", "false", http.StatusUnauthorized}, ++ {"shared system", other, "true", http.StatusOK}, ++ } { ++ t.Run(tc.name, func(t *testing.T) { ++ t.Setenv("SHARE_ALL_SYSTEMS", tc.shareAll) ++ t.Setenv("BESZEL_HUB_SHARE_ALL_SYSTEMS", tc.shareAll) ++ req := httptest.NewRequest(http.MethodGet, path, nil) ++ req.Header.Set("Authorization", tc.token) ++ recorder := httptest.NewRecorder() ++ handler.ServeHTTP(recorder, req) ++ response := recorder.Result() ++ defer response.Body.Close() ++ body, err := io.ReadAll(response.Body) ++ require.NoError(t, err) ++ require.Equal(t, tc.status, response.StatusCode) ++ if tc.status == http.StatusOK { ++ require.JSONEq(t, `{"details":{"Description":"private service details"}}`, string(body)) ++ require.Equal(t, "private, max-age=60", response.Header.Get("Cache-Control")) ++ require.Contains(t, response.Header.Values("Vary"), "Authorization") ++ } else { ++ require.NotContains(t, string(body), "private service details") ++ require.NotContains(t, response.Header.Get("Cache-Control"), "public") ++ } ++ }) ++ } ++ require.EqualValues(t, 2, requests.Load(), "only authorised requests should reach the agent") ++} diff --git a/tasks/henrygd__beszel-2456/tests/test.sh b/tasks/henrygd__beszel-2456/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b659173a94f9eddb5f81449bbd6e9c57abe58e77 --- /dev/null +++ b/tasks/henrygd__beszel-2456/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 4422be717c3e3cb2e58ebac9c0bebbd30d94e2a1 > "$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/henrygd__beszel-2456/tests/verifier.py b/tasks/henrygd__beszel-2456/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2456/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/henrygd__beszel-2459/environment/Dockerfile b/tasks/henrygd__beszel-2459/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c491e76c3d2abae9cbf4a79251d72411731e0a75 --- /dev/null +++ b/tasks/henrygd__beszel-2459/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 65f00ae119269113613a39028b7a935693b860e6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 65f00ae119269113613a39028b7a935693b860e6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 65f00ae119269113613a39028b7a935693b860e6 \ + && 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/henrygd__beszel-2459/instruction.md b/tasks/henrygd__beszel-2459/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1c9384fa29613e85d4b1460463c198416be297f3 --- /dev/null +++ b/tasks/henrygd__beszel-2459/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** refactor(agent): avoid deprecated CPU time total helper + +## Description + +Calculate CPU time totals from the same ten fields used by gopsutil's deprecated `TimesStat.Total` method. Preserve the summation order, Linux guest-time adjustment and busy-time calculation. + +Add coverage for all counters, busy percentage and unchanged or regressing samples. CPU tests, `go vet` and the Makefile agent build pass, including the Linux/glibc path. CPU tests and native agent builds also pass on macOS ARM64, Windows AMD64 and Linux ARM64 with the separate test reliability and portability fixes applied. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `65f00ae11926`. 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/henrygd__beszel-2459/solution/patch.diff b/tasks/henrygd__beszel-2459/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c119be1e15074881847e2d0247c859f9e77b461f --- /dev/null +++ b/tasks/henrygd__beszel-2459/solution/patch.diff @@ -0,0 +1,48 @@ +diff --git a/agent/cpu.go b/agent/cpu.go +index f92b9fcd..8ac0c2e9 100644 +--- a/agent/cpu.go ++++ b/agent/cpu.go +@@ -119,7 +119,8 @@ func calculateBusy(t1, t2 cpu.TimesStat) float64 { + // On Linux, it excludes guest and guest_nice time from the total to match kernel behavior. + // Returns total CPU time and busy CPU time (total minus idle and I/O wait time). + func getAllBusy(t cpu.TimesStat) (float64, float64) { +- tot := t.Total() ++ tot := t.User + t.System + t.Idle + t.Nice + t.Iowait + t.Irq + ++ t.Softirq + t.Steal + t.Guest + t.GuestNice + if runtime.GOOS == "linux" { + tot -= t.Guest // Linux 2.6.24+ + tot -= t.GuestNice // Linux 3.2.0+ +diff --git a/agent/cpu_test.go b/agent/cpu_test.go +new file mode 100644 +index 00000000..83b02561 +--- /dev/null ++++ b/agent/cpu_test.go +@@ -0,0 +1,28 @@ ++//go:build testing ++ ++package agent ++ ++import ( ++ "runtime" ++ "testing" ++ ++ "github.com/shirou/gopsutil/v4/cpu" ++ "github.com/stretchr/testify/assert" ++) ++ ++func TestGetAllBusy(t *testing.T) { ++ times := cpu.TimesStat{ ++ User: 1, System: 2, Idle: 3, Nice: 4, Iowait: 5, ++ Irq: 6, Softirq: 7, Steal: 8, Guest: 9, GuestNice: 10, ++ } ++ wantTotal, wantBusy := 55.0, 47.0 ++ if runtime.GOOS == "linux" { ++ wantTotal, wantBusy = 36, 28 ++ } ++ total, busy := getAllBusy(times) ++ assert.Equal(t, wantTotal, total) ++ assert.Equal(t, wantBusy, busy) ++ assert.InDelta(t, wantBusy/wantTotal*100, calculateBusy(cpu.TimesStat{}, times), 1e-10) ++ assert.Zero(t, calculateBusy(times, times)) ++ assert.Zero(t, calculateBusy(times, cpu.TimesStat{})) ++} diff --git a/tasks/henrygd__beszel-2459/solution/solve.sh b/tasks/henrygd__beszel-2459/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2459/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/henrygd__beszel-2459/task.toml b/tasks/henrygd__beszel-2459/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3027daf368455cef027007f2fe6eebf8bb17ae34 --- /dev/null +++ b/tasks/henrygd__beszel-2459/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2459" +description = "refactor(agent): avoid deprecated CPU time total helper" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "65f00ae119269113613a39028b7a935693b860e6" +reference = "https://github.com/henrygd/beszel/pull/2459" +source_access = "auto" +built_at = "2026-11-16T16:09:53.441273+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:40340fd5112df02051185606bcd005f61b28d3802832d9796d7f652fa64af31b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-29T12:42:02Z" +diff_format = "unified" +context_files = [ + "agent/cpu.go", + "agent/cpu_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 31 +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:00.828490+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d6e5769e8c4318cc71a1c0fcd74d8f70f0d08689cfb4e5c6064eb2e21988f11f" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2459/tests/capture.py b/tasks/henrygd__beszel-2459/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2459/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/henrygd__beszel-2459/tests/instruction.md b/tasks/henrygd__beszel-2459/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1c9384fa29613e85d4b1460463c198416be297f3 --- /dev/null +++ b/tasks/henrygd__beszel-2459/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** refactor(agent): avoid deprecated CPU time total helper + +## Description + +Calculate CPU time totals from the same ten fields used by gopsutil's deprecated `TimesStat.Total` method. Preserve the summation order, Linux guest-time adjustment and busy-time calculation. + +Add coverage for all counters, busy percentage and unchanged or regressing samples. CPU tests, `go vet` and the Makefile agent build pass, including the Linux/glibc path. CPU tests and native agent builds also pass on macOS ARM64, Windows AMD64 and Linux ARM64 with the separate test reliability and portability fixes applied. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `65f00ae11926`. 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/henrygd__beszel-2459/tests/oracle.patch b/tasks/henrygd__beszel-2459/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c119be1e15074881847e2d0247c859f9e77b461f --- /dev/null +++ b/tasks/henrygd__beszel-2459/tests/oracle.patch @@ -0,0 +1,48 @@ +diff --git a/agent/cpu.go b/agent/cpu.go +index f92b9fcd..8ac0c2e9 100644 +--- a/agent/cpu.go ++++ b/agent/cpu.go +@@ -119,7 +119,8 @@ func calculateBusy(t1, t2 cpu.TimesStat) float64 { + // On Linux, it excludes guest and guest_nice time from the total to match kernel behavior. + // Returns total CPU time and busy CPU time (total minus idle and I/O wait time). + func getAllBusy(t cpu.TimesStat) (float64, float64) { +- tot := t.Total() ++ tot := t.User + t.System + t.Idle + t.Nice + t.Iowait + t.Irq + ++ t.Softirq + t.Steal + t.Guest + t.GuestNice + if runtime.GOOS == "linux" { + tot -= t.Guest // Linux 2.6.24+ + tot -= t.GuestNice // Linux 3.2.0+ +diff --git a/agent/cpu_test.go b/agent/cpu_test.go +new file mode 100644 +index 00000000..83b02561 +--- /dev/null ++++ b/agent/cpu_test.go +@@ -0,0 +1,28 @@ ++//go:build testing ++ ++package agent ++ ++import ( ++ "runtime" ++ "testing" ++ ++ "github.com/shirou/gopsutil/v4/cpu" ++ "github.com/stretchr/testify/assert" ++) ++ ++func TestGetAllBusy(t *testing.T) { ++ times := cpu.TimesStat{ ++ User: 1, System: 2, Idle: 3, Nice: 4, Iowait: 5, ++ Irq: 6, Softirq: 7, Steal: 8, Guest: 9, GuestNice: 10, ++ } ++ wantTotal, wantBusy := 55.0, 47.0 ++ if runtime.GOOS == "linux" { ++ wantTotal, wantBusy = 36, 28 ++ } ++ total, busy := getAllBusy(times) ++ assert.Equal(t, wantTotal, total) ++ assert.Equal(t, wantBusy, busy) ++ assert.InDelta(t, wantBusy/wantTotal*100, calculateBusy(cpu.TimesStat{}, times), 1e-10) ++ assert.Zero(t, calculateBusy(times, times)) ++ assert.Zero(t, calculateBusy(times, cpu.TimesStat{})) ++} diff --git a/tasks/henrygd__beszel-2459/tests/test.sh b/tasks/henrygd__beszel-2459/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..092b9ca2038eb748475172238eebac10a4bd623e --- /dev/null +++ b/tasks/henrygd__beszel-2459/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 65f00ae119269113613a39028b7a935693b860e6 > "$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/henrygd__beszel-2459/tests/verifier.py b/tasks/henrygd__beszel-2459/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2459/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/henrygd__beszel-2467/environment/Dockerfile b/tasks/henrygd__beszel-2467/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff24ae508e5bc72c184ca1307f4faa546cd36806 --- /dev/null +++ b/tasks/henrygd__beszel-2467/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7626e5e3c84806a67d9e10c8791a6aca9991d2ce 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7626e5e3c84806a67d9e10c8791a6aca9991d2ce \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7626e5e3c84806a67d9e10c8791a6aca9991d2ce \ + && 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/henrygd__beszel-2467/instruction.md b/tasks/henrygd__beszel-2467/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4f9b43dda5c831d588df07e881763cac652d6327 --- /dev/null +++ b/tasks/henrygd__beszel-2467/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** fix(site): confirm before deleting a single network monitor + +## Description + +## 📃 Description + +Deleting a single network monitor from the row menu removed it immediately, without the confirmation pop-up that the systems table shows. Only deleting several selected monitors asked for confirmation. Now every delete asks first. + +## 🪵 Changelog + +### ✏️ Changed + +- The confirmation for a single monitor names the target and its system: "Are you sure you want to delete {target} from {system}?" + +### 🔧 Fixed + +- Deleting a single network monitor now asks for confirmation before anything is removed. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7626e5e3c848`. 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/henrygd__beszel-2467/solution/patch.diff b/tasks/henrygd__beszel-2467/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cee1749322776ac266f34cf9165a9120688bcfa0 --- /dev/null +++ b/tasks/henrygd__beszel-2467/solution/patch.diff @@ -0,0 +1,89 @@ +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +index 52bf131a..ad274ce0 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +@@ -99,7 +99,7 @@ export default function NetworkMonitorsTableNew({ + const [rowSelection, setRowSelection] = useState({}) + const [globalFilter, setGlobalFilter] = useState("") + const [deleteOpen, setDeleteOpen] = useState(false) +- const [pendingDeleteIds, setPendingDeleteIds] = useState([]) ++ const [pendingDelete, setPendingDelete] = useState([]) + const [editingMonitor, setEditingMonitor] = useState() + + const { toast } = useToast() +@@ -197,41 +197,28 @@ export default function NetworkMonitorsTableNew({ + [] + ) + +- const handleDeleteRequest = useCallback( +- async (monitorsToDelete: NetworkMonitorRecord[]) => { +- if (!monitorsToDelete.length) { +- return +- } +- +- const ids = monitorsToDelete.map((monitor) => monitor.id) +- if (ids.length === 1) { +- try { +- await pb.collection("network_monitors").delete(ids[0]) +- } catch (err: unknown) { +- toast({ +- variant: "destructive", +- title: t`Error`, +- description: (err as Error)?.message || t`Failed to delete monitors.`, +- }) +- } +- return +- } +- +- setPendingDeleteIds(ids) +- setDeleteOpen(true) +- }, +- [toast] +- ) ++ const handleDeleteRequest = useCallback((monitorsToDelete: NetworkMonitorRecord[]) => { ++ if (!monitorsToDelete.length) { ++ return ++ } ++ setPendingDelete(monitorsToDelete) ++ setDeleteOpen(true) ++ }, []) + +- const handleBulkDelete = async () => { ++ const handleConfirmDelete = async () => { + setDeleteOpen(false) +- if (!pendingDeleteIds.length) { ++ const ids = pendingDelete.map((monitor) => monitor.id) ++ if (!ids.length) { + return + } + + try { +- await runMonitorBatch(pendingDeleteIds, (batch, id) => batch.collection("network_monitors").delete(id)) +- setPendingDeleteIds([]) ++ if (ids.length === 1) { ++ await pb.collection("network_monitors").delete(ids[0]) ++ } else { ++ await runMonitorBatch(ids, (batch, id) => batch.collection("network_monitors").delete(id)) ++ } ++ setPendingDelete([]) + setRowSelection({}) + } catch (err: unknown) { + toast({ +@@ -446,7 +433,7 @@ export default function NetworkMonitorsTableNew({ + onOpenChange={(open) => { + setDeleteOpen(open) + if (!open) { +- setPendingDeleteIds([]) ++ setPendingDelete([]) + } + }} + > +@@ -465,7 +452,7 @@ export default function NetworkMonitorsTableNew({ + + + Continue + diff --git a/tasks/henrygd__beszel-2467/solution/solve.sh b/tasks/henrygd__beszel-2467/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2467/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/henrygd__beszel-2467/task.toml b/tasks/henrygd__beszel-2467/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a0e9b9ee568cf9b7758f79c546d710d6feaf47e4 --- /dev/null +++ b/tasks/henrygd__beszel-2467/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2467" +description = "fix(site): confirm before deleting a single network monitor" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "7626e5e3c84806a67d9e10c8791a6aca9991d2ce" +reference = "https://github.com/henrygd/beszel/pull/2467" +source_access = "auto" +built_at = "2026-11-16T16:09:53.466758+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:0b198dcc363e45bca3b1c73ffd76896ac11da5bceff0969a57d4f7c2dc5616ab" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T22:01:11Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/network-monitors-table/network-monitors-table.tsx", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 51 +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:00.828928+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:be499de38b1d993936f93c4ab3d8554cb8649e5c96b9fef7141b7a3dc99ba712" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2467/tests/capture.py b/tasks/henrygd__beszel-2467/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2467/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/henrygd__beszel-2467/tests/instruction.md b/tasks/henrygd__beszel-2467/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4f9b43dda5c831d588df07e881763cac652d6327 --- /dev/null +++ b/tasks/henrygd__beszel-2467/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** fix(site): confirm before deleting a single network monitor + +## Description + +## 📃 Description + +Deleting a single network monitor from the row menu removed it immediately, without the confirmation pop-up that the systems table shows. Only deleting several selected monitors asked for confirmation. Now every delete asks first. + +## 🪵 Changelog + +### ✏️ Changed + +- The confirmation for a single monitor names the target and its system: "Are you sure you want to delete {target} from {system}?" + +### 🔧 Fixed + +- Deleting a single network monitor now asks for confirmation before anything is removed. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7626e5e3c848`. 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/henrygd__beszel-2467/tests/oracle.patch b/tasks/henrygd__beszel-2467/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cee1749322776ac266f34cf9165a9120688bcfa0 --- /dev/null +++ b/tasks/henrygd__beszel-2467/tests/oracle.patch @@ -0,0 +1,89 @@ +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +index 52bf131a..ad274ce0 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-table.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-table.tsx +@@ -99,7 +99,7 @@ export default function NetworkMonitorsTableNew({ + const [rowSelection, setRowSelection] = useState({}) + const [globalFilter, setGlobalFilter] = useState("") + const [deleteOpen, setDeleteOpen] = useState(false) +- const [pendingDeleteIds, setPendingDeleteIds] = useState([]) ++ const [pendingDelete, setPendingDelete] = useState([]) + const [editingMonitor, setEditingMonitor] = useState() + + const { toast } = useToast() +@@ -197,41 +197,28 @@ export default function NetworkMonitorsTableNew({ + [] + ) + +- const handleDeleteRequest = useCallback( +- async (monitorsToDelete: NetworkMonitorRecord[]) => { +- if (!monitorsToDelete.length) { +- return +- } +- +- const ids = monitorsToDelete.map((monitor) => monitor.id) +- if (ids.length === 1) { +- try { +- await pb.collection("network_monitors").delete(ids[0]) +- } catch (err: unknown) { +- toast({ +- variant: "destructive", +- title: t`Error`, +- description: (err as Error)?.message || t`Failed to delete monitors.`, +- }) +- } +- return +- } +- +- setPendingDeleteIds(ids) +- setDeleteOpen(true) +- }, +- [toast] +- ) ++ const handleDeleteRequest = useCallback((monitorsToDelete: NetworkMonitorRecord[]) => { ++ if (!monitorsToDelete.length) { ++ return ++ } ++ setPendingDelete(monitorsToDelete) ++ setDeleteOpen(true) ++ }, []) + +- const handleBulkDelete = async () => { ++ const handleConfirmDelete = async () => { + setDeleteOpen(false) +- if (!pendingDeleteIds.length) { ++ const ids = pendingDelete.map((monitor) => monitor.id) ++ if (!ids.length) { + return + } + + try { +- await runMonitorBatch(pendingDeleteIds, (batch, id) => batch.collection("network_monitors").delete(id)) +- setPendingDeleteIds([]) ++ if (ids.length === 1) { ++ await pb.collection("network_monitors").delete(ids[0]) ++ } else { ++ await runMonitorBatch(ids, (batch, id) => batch.collection("network_monitors").delete(id)) ++ } ++ setPendingDelete([]) + setRowSelection({}) + } catch (err: unknown) { + toast({ +@@ -446,7 +433,7 @@ export default function NetworkMonitorsTableNew({ + onOpenChange={(open) => { + setDeleteOpen(open) + if (!open) { +- setPendingDeleteIds([]) ++ setPendingDelete([]) + } + }} + > +@@ -465,7 +452,7 @@ export default function NetworkMonitorsTableNew({ + + + Continue + diff --git a/tasks/henrygd__beszel-2467/tests/test.sh b/tasks/henrygd__beszel-2467/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b7e4ba1d83681f8f9424d1dea07f5de042411399 --- /dev/null +++ b/tasks/henrygd__beszel-2467/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 7626e5e3c84806a67d9e10c8791a6aca9991d2ce > "$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/henrygd__beszel-2467/tests/verifier.py b/tasks/henrygd__beszel-2467/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2467/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/henrygd__beszel-2469/environment/Dockerfile b/tasks/henrygd__beszel-2469/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9128e1df096a5a64285602f0943c6df610944027 --- /dev/null +++ b/tasks/henrygd__beszel-2469/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0b101cc6be4de850f0cdb26a9abd538b27f3e363 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0b101cc6be4de850f0cdb26a9abd538b27f3e363 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0b101cc6be4de850f0cdb26a9abd538b27f3e363 \ + && 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/henrygd__beszel-2469/instruction.md b/tasks/henrygd__beszel-2469/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f5048fc630b2302cf02cc7e6a5c1e101631e3fad --- /dev/null +++ b/tasks/henrygd__beszel-2469/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** feat(hub): add DISABLE_SSH option to skip SSH fallback + +## Description + +## 📃 Description + +Adds a hub-level `DISABLE_SSH` option. When it's set, the hub no longer falls back to SSH when an agent's WebSocket connection drops. It waits for the agent to reconnect instead, so powered-off machines aren't dialed over and over. + + + +## 📖 Documentation + +Docs PR for the hub `DISABLE_SSH` variable to follow. + +## 🪵 Changelog + +### ➕ Added + +- Hub env var `DISABLE_SSH` / `BESZEL_HUB_DISABLE_SSH`. + +### ✏️ Changed + +- The hub skips the SSH fallback for all systems when `DISABLE_SSH=true` is set on the hub. +- With SSH disabled on the hub, the systems table shows the status dot instead of the connection type icon. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0b101cc6be4d`. 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/henrygd__beszel-2469/solution/patch.diff b/tasks/henrygd__beszel-2469/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7a110a53f606dd4b961b077c0003ecda2b1b2df0 --- /dev/null +++ b/tasks/henrygd__beszel-2469/solution/patch.diff @@ -0,0 +1,113 @@ +diff --git a/internal/hub/systems/system.go b/internal/hub/systems/system.go +index f5888f75..0a292668 100644 +--- a/internal/hub/systems/system.go ++++ b/internal/hub/systems/system.go +@@ -66,6 +66,15 @@ type System struct { + lastSavedMonitorProbe map[string]int64 + } + ++// errSSHDisabled is returned instead of dialing SSH when DISABLE_SSH is set on the hub. ++var errSSHDisabled = errors.New("no WebSocket connection and SSH is disabled") ++ ++// sshFallbackDisabled reports whether DISABLE_SSH is set on the hub. ++func sshFallbackDisabled() bool { ++ disableSSH, _ := utils.GetEnv("DISABLE_SSH") ++ return disableSSH == "true" ++} ++ + // GetStatus returns the current monitoring status. + func (sys *System) GetStatus() string { + sys.statusMu.RLock() +@@ -713,7 +722,11 @@ func shouldCloseWebSocket(err error) bool { + // getSSHTransport returns the system's SSH transport, creating it on first use. + // The transport owns the only SSH connection to the agent; it is shared by the + // updater and on-demand requests and connects lazily. ++// It returns errSSHDisabled if DISABLE_SSH is set on the hub. + func (sys *System) getSSHTransport() (*transport.SSHTransport, error) { ++ if sshFallbackDisabled() { ++ return nil, errSSHDisabled ++ } + sys.sshMu.Lock() + defer sys.sshMu.Unlock() + if sys.sshTransport != nil { +diff --git a/internal/hub/systems/system_test.go b/internal/hub/systems/system_test.go +index ab720c7a..e7eac097 100644 +--- a/internal/hub/systems/system_test.go ++++ b/internal/hub/systems/system_test.go +@@ -4,9 +4,14 @@ package systems + + import ( + "context" ++ "net" + "testing" ++ "time" + ++ "github.com/henrygd/beszel/internal/common" + "github.com/henrygd/beszel/internal/entities/system" ++ "github.com/stretchr/testify/require" ++ "golang.org/x/crypto/ssh" + ) + + func TestCombinedData_MigrateDeprecatedFields(t *testing.T) { +@@ -172,3 +177,61 @@ func TestSetDownAfterContextCancelled(t *testing.T) { + t.Fatalf("status should be untouched, got %q", sys.Status) + } + } ++ ++func TestSSHDisabledSkipsSSHFallback(t *testing.T) { ++ t.Setenv("DISABLE_SSH", "true") ++ // manager is nil on purpose: any SSH attempt would panic ++ sys := &System{} ++ ++ var result string ++ err := sys.request(context.Background(), common.GetContainerInfo, nil, &result) ++ require.ErrorIs(t, err, errSSHDisabled) ++ ++ _, err = sys.fetchDataFromAgent(common.DataRequestOptions{}) ++ require.ErrorIs(t, err, errSSHDisabled) ++} ++ ++func TestSSHFallbackDialsAgentUnlessDisabled(t *testing.T) { ++ for _, tc := range []struct { ++ name string ++ hubEnv string ++ wantDial bool ++ }{ ++ {name: "enabled", wantDial: true}, ++ {name: "disabled on hub", hubEnv: "DISABLE_SSH"}, ++ {name: "disabled on hub with prefix", hubEnv: "BESZEL_HUB_DISABLE_SSH"}, ++ } { ++ t.Run(tc.name, func(t *testing.T) { ++ if tc.hubEnv != "" { ++ t.Setenv(tc.hubEnv, "true") ++ } ++ listener, err := net.Listen("tcp", "127.0.0.1:0") ++ require.NoError(t, err) ++ defer listener.Close() ++ accepted := make(chan struct{}, 1) ++ go func() { ++ if conn, err := listener.Accept(); err == nil { ++ accepted <- struct{}{} ++ conn.Close() ++ } ++ }() ++ ++ host, port, _ := net.SplitHostPort(listener.Addr().String()) ++ sm := &SystemManager{sshConfig: &ssh.ClientConfig{HostKeyCallback: ssh.InsecureIgnoreHostKey(), Timeout: time.Second}} ++ sys := &System{Host: host, Port: port, Status: down, manager: sm, ctx: context.Background()} ++ ++ _, err = sys.fetchDataFromAgent(common.DataRequestOptions{}) ++ require.Error(t, err) // listener isn't a real agent ++ if !tc.wantDial { ++ require.ErrorIs(t, err, errSSHDisabled) ++ } ++ ++ select { ++ case <-accepted: ++ require.True(t, tc.wantDial, "hub must not dial SSH when it is disabled") ++ case <-time.After(200 * time.Millisecond): ++ require.False(t, tc.wantDial, "hub must dial SSH when it is enabled") ++ } ++ }) ++ } ++} diff --git a/tasks/henrygd__beszel-2469/solution/solve.sh b/tasks/henrygd__beszel-2469/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2469/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/henrygd__beszel-2469/task.toml b/tasks/henrygd__beszel-2469/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..459b8b9b1d6138bf3d14cb972347c204b397b846 --- /dev/null +++ b/tasks/henrygd__beszel-2469/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2469" +description = "feat(hub): add DISABLE_SSH option to skip SSH fallback" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "0b101cc6be4de850f0cdb26a9abd538b27f3e363" +reference = "https://github.com/henrygd/beszel/pull/2469" +source_access = "auto" +built_at = "2026-11-16T16:09:53.442858+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ba1e1cd3b78fa8fad68669dfba113cf107dd42d206a6e5a76f85ba0b0b8af328" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-01T15:20:01Z" +diff_format = "unified" +context_files = [ + "internal/hub/systems/system.go", + "internal/hub/systems/system_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 76 +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:00.829373+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:f8f2076ae0749226dae5c3d58993d2e74b1fe1832ae7729fa03fd237f7d7c869" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2469/tests/capture.py b/tasks/henrygd__beszel-2469/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2469/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/henrygd__beszel-2469/tests/instruction.md b/tasks/henrygd__beszel-2469/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f5048fc630b2302cf02cc7e6a5c1e101631e3fad --- /dev/null +++ b/tasks/henrygd__beszel-2469/tests/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** feat(hub): add DISABLE_SSH option to skip SSH fallback + +## Description + +## 📃 Description + +Adds a hub-level `DISABLE_SSH` option. When it's set, the hub no longer falls back to SSH when an agent's WebSocket connection drops. It waits for the agent to reconnect instead, so powered-off machines aren't dialed over and over. + + + +## 📖 Documentation + +Docs PR for the hub `DISABLE_SSH` variable to follow. + +## 🪵 Changelog + +### ➕ Added + +- Hub env var `DISABLE_SSH` / `BESZEL_HUB_DISABLE_SSH`. + +### ✏️ Changed + +- The hub skips the SSH fallback for all systems when `DISABLE_SSH=true` is set on the hub. +- With SSH disabled on the hub, the systems table shows the status dot instead of the connection type icon. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0b101cc6be4d`. 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/henrygd__beszel-2469/tests/oracle.patch b/tasks/henrygd__beszel-2469/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7a110a53f606dd4b961b077c0003ecda2b1b2df0 --- /dev/null +++ b/tasks/henrygd__beszel-2469/tests/oracle.patch @@ -0,0 +1,113 @@ +diff --git a/internal/hub/systems/system.go b/internal/hub/systems/system.go +index f5888f75..0a292668 100644 +--- a/internal/hub/systems/system.go ++++ b/internal/hub/systems/system.go +@@ -66,6 +66,15 @@ type System struct { + lastSavedMonitorProbe map[string]int64 + } + ++// errSSHDisabled is returned instead of dialing SSH when DISABLE_SSH is set on the hub. ++var errSSHDisabled = errors.New("no WebSocket connection and SSH is disabled") ++ ++// sshFallbackDisabled reports whether DISABLE_SSH is set on the hub. ++func sshFallbackDisabled() bool { ++ disableSSH, _ := utils.GetEnv("DISABLE_SSH") ++ return disableSSH == "true" ++} ++ + // GetStatus returns the current monitoring status. + func (sys *System) GetStatus() string { + sys.statusMu.RLock() +@@ -713,7 +722,11 @@ func shouldCloseWebSocket(err error) bool { + // getSSHTransport returns the system's SSH transport, creating it on first use. + // The transport owns the only SSH connection to the agent; it is shared by the + // updater and on-demand requests and connects lazily. ++// It returns errSSHDisabled if DISABLE_SSH is set on the hub. + func (sys *System) getSSHTransport() (*transport.SSHTransport, error) { ++ if sshFallbackDisabled() { ++ return nil, errSSHDisabled ++ } + sys.sshMu.Lock() + defer sys.sshMu.Unlock() + if sys.sshTransport != nil { +diff --git a/internal/hub/systems/system_test.go b/internal/hub/systems/system_test.go +index ab720c7a..e7eac097 100644 +--- a/internal/hub/systems/system_test.go ++++ b/internal/hub/systems/system_test.go +@@ -4,9 +4,14 @@ package systems + + import ( + "context" ++ "net" + "testing" ++ "time" + ++ "github.com/henrygd/beszel/internal/common" + "github.com/henrygd/beszel/internal/entities/system" ++ "github.com/stretchr/testify/require" ++ "golang.org/x/crypto/ssh" + ) + + func TestCombinedData_MigrateDeprecatedFields(t *testing.T) { +@@ -172,3 +177,61 @@ func TestSetDownAfterContextCancelled(t *testing.T) { + t.Fatalf("status should be untouched, got %q", sys.Status) + } + } ++ ++func TestSSHDisabledSkipsSSHFallback(t *testing.T) { ++ t.Setenv("DISABLE_SSH", "true") ++ // manager is nil on purpose: any SSH attempt would panic ++ sys := &System{} ++ ++ var result string ++ err := sys.request(context.Background(), common.GetContainerInfo, nil, &result) ++ require.ErrorIs(t, err, errSSHDisabled) ++ ++ _, err = sys.fetchDataFromAgent(common.DataRequestOptions{}) ++ require.ErrorIs(t, err, errSSHDisabled) ++} ++ ++func TestSSHFallbackDialsAgentUnlessDisabled(t *testing.T) { ++ for _, tc := range []struct { ++ name string ++ hubEnv string ++ wantDial bool ++ }{ ++ {name: "enabled", wantDial: true}, ++ {name: "disabled on hub", hubEnv: "DISABLE_SSH"}, ++ {name: "disabled on hub with prefix", hubEnv: "BESZEL_HUB_DISABLE_SSH"}, ++ } { ++ t.Run(tc.name, func(t *testing.T) { ++ if tc.hubEnv != "" { ++ t.Setenv(tc.hubEnv, "true") ++ } ++ listener, err := net.Listen("tcp", "127.0.0.1:0") ++ require.NoError(t, err) ++ defer listener.Close() ++ accepted := make(chan struct{}, 1) ++ go func() { ++ if conn, err := listener.Accept(); err == nil { ++ accepted <- struct{}{} ++ conn.Close() ++ } ++ }() ++ ++ host, port, _ := net.SplitHostPort(listener.Addr().String()) ++ sm := &SystemManager{sshConfig: &ssh.ClientConfig{HostKeyCallback: ssh.InsecureIgnoreHostKey(), Timeout: time.Second}} ++ sys := &System{Host: host, Port: port, Status: down, manager: sm, ctx: context.Background()} ++ ++ _, err = sys.fetchDataFromAgent(common.DataRequestOptions{}) ++ require.Error(t, err) // listener isn't a real agent ++ if !tc.wantDial { ++ require.ErrorIs(t, err, errSSHDisabled) ++ } ++ ++ select { ++ case <-accepted: ++ require.True(t, tc.wantDial, "hub must not dial SSH when it is disabled") ++ case <-time.After(200 * time.Millisecond): ++ require.False(t, tc.wantDial, "hub must dial SSH when it is enabled") ++ } ++ }) ++ } ++} diff --git a/tasks/henrygd__beszel-2469/tests/test.sh b/tasks/henrygd__beszel-2469/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b9a251addc75bbe09ed7661b64c52660486a2233 --- /dev/null +++ b/tasks/henrygd__beszel-2469/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 0b101cc6be4de850f0cdb26a9abd538b27f3e363 > "$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/henrygd__beszel-2469/tests/verifier.py b/tasks/henrygd__beszel-2469/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2469/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/henrygd__beszel-2474/environment/Dockerfile b/tasks/henrygd__beszel-2474/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a4db6dd19bafe29c6c10abffcd8bc5c74f4c012b --- /dev/null +++ b/tasks/henrygd__beszel-2474/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 1ab38e57c59c470ae579caa268b7d9dcdbda95ba 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 1ab38e57c59c470ae579caa268b7d9dcdbda95ba \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 1ab38e57c59c470ae579caa268b7d9dcdbda95ba \ + && 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/henrygd__beszel-2474/instruction.md b/tasks/henrygd__beszel-2474/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..46922f666053d4dca5c07f951044408aa96e6161 --- /dev/null +++ b/tasks/henrygd__beszel-2474/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** fix(agent): count ZFS snapshot reads in pool I/O stats + +## Description + +## 📃 Description + +. + +Reads through `.zfs/snapshot/` never appear in Beszel's pool I/O graph, even while `htop`/`iotop` show sustained reads. Two kernel-side facts cause this: + +- OpenZFS intentionally skips creating `objset-*` kstats for snapshot objsets (`dataset_kstats_create()` returns early on `dmu_objset_is_snapshot()`), so summing per-dataset counters — the fallback `readPoolCounters()` uses whenever the `io` file is missing — can never see snapshot traffic. +- The pool-level `io` kstat itself only exists on OpenZFS ≤ 2.0 (it was removed in 2.1), so on current kernels the objset sum is the only source beszel reads. + +OpenZFS 2.3 added pool-wide logical read/write counters to the `iostats` kstat (`arc_read_bytes`, `direct_read_bytes`, `arc_write_bytes`, `direct_write_bytes`), fed by `spa_iostats_read_add`/`spa_iostats_write_add` — the same accounting hooks that attribute I/O to userspace tasks (`task_io_account_read`), which is why they line up with what `iotop` reports. These counters are pool-scoped rather than dataset-scoped, so they cover mounted snapshots too. + +Changes: + +- Prefer `iostats` (`arc_*` + `direct_*` byte counters) in `readPoolCounters()` when all four fields are present (OpenZFS 2.3+). On earlier releases the file exists but only carries TRIM stats, so the reader requires all four counters and falls through when they are absent. +- Keep the legacy `io` counters (OpenZFS ≤ 2.0) and the `objset-*` sum as fallbacks, unchanged. +- Add `iostats` to the pool discovery glob so a pool exposing only `state`/`iostats` is still found. + +Tests cover the new source (`iostats` beats the incomplete objset sum), the pre-2.3 shape (TRIM-only `iostats` falls back to `objset-*`), and required-field validation. Verified with `go build ./...`, `go vet ./...`, and `go test -tags testing ./zfs/... -count=1` (all pass); the new test fails on the pre-fix code path (returns the objset sum instead of the `iostats` total). + +One known limit: on OpenZFS 2.1–2.2 there is no procfs counter at all that includes snapshot reads, so those kernels keep the existing dataset-sum behavior. + +## 🪵 Changelog + +### 🔧 Fixed + +- ZFS pool I/O stats now count reads served through `.zfs/snapshot/` on OpenZFS 2.3+ by preferring the pool-wide `iostats` counters. + +AI-assisted. I wrote and verified this change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1ab38e57c59c`. 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/henrygd__beszel-2474/solution/patch.diff b/tasks/henrygd__beszel-2474/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..096f01226416066250ad97c97400345466195103 --- /dev/null +++ b/tasks/henrygd__beszel-2474/solution/patch.diff @@ -0,0 +1,254 @@ +diff --git a/agent/zfs/zfs_linux.go b/agent/zfs/zfs_linux.go +index b5a25779..b297678a 100644 +--- a/agent/zfs/zfs_linux.go ++++ b/agent/zfs/zfs_linux.go +@@ -18,6 +18,11 @@ var ( + devZfsPath = "/dev/zfs" + ) + ++// errNoPoolIOStats marks an "iostats" file that predates OpenZFS 2.3 and ++// reports no pool read/write counters (TRIM statistics only), so callers may ++// fall back to older counter sources. ++var errNoPoolIOStats = errors.New("no pool I/O counters") ++ + func ARCSize() (uint64, error) { + file, err := os.Open(filepath.Join(procZfsPath, "arcstats")) + if err != nil { +@@ -61,7 +66,7 @@ func checkZfsDevice() error { + // ZFS collector and avoid keeping a `zpool iostat` subprocess alive. + func PoolKernelStats() ([]PoolKernelStat, error) { + poolDirs := make(map[string]struct{}) +- for _, filename := range []string{"state", "io", "objset-*"} { ++ for _, filename := range []string{"state", "io", "iostats", "objset-*"} { + paths, err := filepath.Glob(filepath.Join(procZfsPath, "*", filename)) + if err != nil { + return nil, err +@@ -97,11 +102,25 @@ func PoolKernelStats() ([]PoolKernelStat, error) { + return pools, nil + } + +-// readPoolCounters supports both ZFS kernel interfaces. OpenZFS through 2.3 +-// exposes aggregate vdev counters in "io". When that file is unavailable, sum +-// the logical I/O counters exposed for each dataset in the pool. ++// readPoolCounters supports the ZFS kernel interfaces. OpenZFS 2.3+ exposes ++// pool-wide read/write counters in "iostats" that cover every objset, ++// including mounted snapshots, which never get an "objset-*" kstat. OpenZFS ++// through 2.0 exposes aggregate vdev counters in "io". When neither pool-level ++// interface is usable, sum the logical I/O counters exposed for each dataset. + func readPoolCounters(poolDir string) (uint64, uint64, error) { +- nread, nwrite, err := readPoolIO(filepath.Join(poolDir, "io")) ++ nread, nwrite, err := readPoolIOStats(filepath.Join(poolDir, "iostats")) ++ if err == nil { ++ return nread, nwrite, nil ++ } ++ // Older sources are tried only when "iostats" is absent or predates ++ // OpenZFS 2.3. A read or parse failure on a usable file is returned: ++ // silently switching counter sources would feed kernelStats counters ++ // from different interfaces under the same pool name and produce a ++ // false I/O spike once "iostats" recovers. ++ if !errors.Is(err, os.ErrNotExist) && !errors.Is(err, errNoPoolIOStats) { ++ return 0, 0, err ++ } ++ nread, nwrite, err = readPoolIO(filepath.Join(poolDir, "io")) + if err == nil || !errors.Is(err, os.ErrNotExist) { + return nread, nwrite, err + } +@@ -144,6 +163,59 @@ func readPoolIO(path string) (uint64, uint64, error) { + return 0, 0, fmt.Errorf("I/O counters not found in %s", path) + } + ++// readPoolIOStats reads the pool I/O counters exported by OpenZFS 2.3+ in the ++// "iostats" kstat. Reads are counted on ARC misses at their compressed size, so ++// reads served from the ARC are excluded; writes are counted at their logical ++// size. The file exists on earlier releases but then only reports TRIM ++// statistics, so all four byte counters are required for the file to be usable. ++func readPoolIOStats(path string) (uint64, uint64, error) { ++ file, err := os.Open(path) ++ if err != nil { ++ return 0, 0, err ++ } ++ defer file.Close() ++ ++ var arcRead, arcWrite, directRead, directWrite uint64 ++ var found uint8 ++ scanner := bufio.NewScanner(file) ++ for scanner.Scan() { ++ fields := strings.Fields(scanner.Text()) ++ if len(fields) < 3 { ++ continue ++ } ++ var target *uint64 ++ var bit uint8 ++ switch fields[0] { ++ case "arc_read_bytes": ++ target, bit = &arcRead, 1<<0 ++ case "direct_read_bytes": ++ target, bit = &directRead, 1<<1 ++ case "arc_write_bytes": ++ target, bit = &arcWrite, 1<<2 ++ case "direct_write_bytes": ++ target, bit = &directWrite, 1<<3 ++ default: ++ continue ++ } ++ value, err := strconv.ParseUint(fields[2], 10, 64) ++ if err != nil { ++ return 0, 0, fmt.Errorf("parsing %s in %s: %w", fields[0], path, err) ++ } ++ *target = value ++ found |= bit ++ } ++ if err := scanner.Err(); err != nil { ++ return 0, 0, err ++ } ++ if found == 0 { ++ return 0, 0, fmt.Errorf("%w in %s", errNoPoolIOStats, path) ++ } ++ if found != 0x0f { ++ return 0, 0, fmt.Errorf("incomplete pool I/O counters in %s", path) ++ } ++ return arcRead + directRead, arcWrite + directWrite, nil ++} ++ + func readPoolObjsets(poolDir string) (uint64, uint64, error) { + paths, err := filepath.Glob(filepath.Join(poolDir, "objset-*")) + if err != nil { +diff --git a/agent/zfs/zfs_linux_test.go b/agent/zfs/zfs_linux_test.go +index 7ecb59a0..41f216ba 100644 +--- a/agent/zfs/zfs_linux_test.go ++++ b/agent/zfs/zfs_linux_test.go +@@ -66,6 +66,111 @@ func TestPoolKernelStatsOpenZfs24(t *testing.T) { + }, stats[0]) + } + ++func TestPoolKernelStatsOpenZfs23(t *testing.T) { ++ root := t.TempDir() ++ oldPath := procZfsPath ++ procZfsPath = root ++ t.Cleanup(func() { procZfsPath = oldPath }) ++ ++ // OpenZFS 2.3+ exposes logical pool read/write counters in "iostats". ++ // They cover every objset, including mounted snapshots, which never get ++ // an "objset-*" kstat, so the objset sum alone under-reports reads. ++ poolDir := filepath.Join(root, "tank") ++ require.NoError(t, os.MkdirAll(poolDir, 0o755)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "state"), []byte("ONLINE\n"), 0o644)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "iostats"), []byte( ++ "15 1 0x01 26 5176 227423 2127661979232\n"+ ++ "name type data\n"+ ++ "trim_extents_written 4 0\n"+ ++ "arc_read_count 4 12\n"+ ++ "arc_read_bytes 4 5000\n"+ ++ "arc_write_count 4 7\n"+ ++ "arc_write_bytes 4 3000\n"+ ++ "direct_read_count 4 1\n"+ ++ "direct_read_bytes 4 500\n"+ ++ "direct_write_count 4 1\n"+ ++ "direct_write_bytes 4 200\n", ++ ), 0o644)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "objset-0x1"), []byte( ++ "34 1 0x01 28 7872 0 0\n"+ ++ "name type data\n"+ ++ "dataset_name 7 tank\n"+ ++ "nwritten 4 2000\n"+ ++ "nread 4 1000\n", ++ ), 0o644)) ++ ++ stats, err := PoolKernelStats() ++ require.NoError(t, err) ++ require.Len(t, stats, 1) ++ assert.Equal(t, PoolKernelStat{ ++ Name: "tank", Health: "ONLINE", NRead: 5500, NWrite: 3200, ++ }, stats[0]) ++} ++ ++func TestPoolKernelStatsIOStatsTrimOnly(t *testing.T) { ++ root := t.TempDir() ++ oldPath := procZfsPath ++ procZfsPath = root ++ t.Cleanup(func() { procZfsPath = oldPath }) ++ ++ // Before OpenZFS 2.3 the "iostats" file only reports TRIM counters, so ++ // the per-dataset "objset-*" files remain the only usable source. ++ poolDir := filepath.Join(root, "tank") ++ require.NoError(t, os.MkdirAll(poolDir, 0o755)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "state"), []byte("ONLINE\n"), 0o644)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "iostats"), []byte( ++ "15 1 0x01 18 3736 227423 2127661979232\n"+ ++ "name type data\n"+ ++ "trim_extents_written 4 10\n"+ ++ "trim_bytes_written 4 4096\n", ++ ), 0o644)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "objset-0x1"), []byte( ++ "34 1 0x01 28 7872 0 0\n"+ ++ "name type data\n"+ ++ "dataset_name 7 tank\n"+ ++ "nwritten 4 2000\n"+ ++ "nread 4 1000\n", ++ ), 0o644)) ++ ++ stats, err := PoolKernelStats() ++ require.NoError(t, err) ++ require.Len(t, stats, 1) ++ assert.Equal(t, PoolKernelStat{ ++ Name: "tank", Health: "ONLINE", NRead: 1000, NWrite: 2000, ++ }, stats[0]) ++} ++ ++func TestPoolKernelStatsIOStatsErrorDoesNotFallback(t *testing.T) { ++ root := t.TempDir() ++ oldPath := procZfsPath ++ procZfsPath = root ++ t.Cleanup(func() { procZfsPath = oldPath }) ++ ++ // A malformed "iostats" on a kernel that supports it must surface an ++ // error. Silently switching to the per-dataset sum would drop snapshot ++ // reads and, when "iostats" recovers, make kernelStats report a false ++ // I/O spike by comparing counters from two different interfaces. ++ poolDir := filepath.Join(root, "tank") ++ require.NoError(t, os.MkdirAll(poolDir, 0o755)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "state"), []byte("ONLINE\n"), 0o644)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "iostats"), []byte( ++ "arc_read_bytes 4 notanumber\n"+ ++ "arc_write_bytes 4 3000\n"+ ++ "direct_read_bytes 4 500\n"+ ++ "direct_write_bytes 4 200\n", ++ ), 0o644)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "objset-0x1"), []byte( ++ "34 1 0x01 28 7872 0 0\n"+ ++ "name type data\n"+ ++ "dataset_name 7 tank\n"+ ++ "nwritten 4 2000\n"+ ++ "nread 4 1000\n", ++ ), 0o644)) ++ ++ _, err := PoolKernelStats() ++ require.Error(t, err) ++} ++ + func TestPoolKernelStatsNoZfs(t *testing.T) { + oldPath := procZfsPath + procZfsPath = t.TempDir() +@@ -89,6 +194,22 @@ func TestReadObjsetIORequiresAllCounters(t *testing.T) { + require.Error(t, err) + } + ++func TestReadPoolIOStatsRequiresAllCounters(t *testing.T) { ++ path := filepath.Join(t.TempDir(), "iostats") ++ require.NoError(t, os.WriteFile(path, []byte( ++ "arc_read_bytes 4 10\ndirect_read_bytes 4 5\narc_write_bytes 4 7\n"), 0o644)) ++ _, _, err := readPoolIOStats(path) ++ require.Error(t, err) ++} ++ ++func TestReadPoolIOStatsTrimOnlySignalsFallback(t *testing.T) { ++ path := filepath.Join(t.TempDir(), "iostats") ++ require.NoError(t, os.WriteFile(path, []byte( ++ "trim_extents_written 4 10\ntrim_bytes_written 4 4096\n"), 0o644)) ++ _, _, err := readPoolIOStats(path) ++ assert.ErrorIs(t, err, errNoPoolIOStats) ++} ++ + func TestCollectorsSkipCommandsWhenDevZfsMissing(t *testing.T) { + root := t.TempDir() + oldDevZfsPath := devZfsPath diff --git a/tasks/henrygd__beszel-2474/solution/solve.sh b/tasks/henrygd__beszel-2474/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2474/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/henrygd__beszel-2474/task.toml b/tasks/henrygd__beszel-2474/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..18ac8c72959ced55cc93ec6ad03c5fa8766b1068 --- /dev/null +++ b/tasks/henrygd__beszel-2474/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2474" +description = "fix(agent): count ZFS snapshot reads in pool I/O stats" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "1ab38e57c59c470ae579caa268b7d9dcdbda95ba" +reference = "https://github.com/henrygd/beszel/pull/2474" +source_access = "auto" +built_at = "2026-11-16T16:09:53.445853+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4446882b46c5a92e436d4fd217137547ad8da68d70add261af11319b9934d3b8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-30T22:22:51Z" +diff_format = "unified" +context_files = [ + "agent/zfs/zfs_linux.go", + "agent/zfs/zfs_linux_test.go", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 203 +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:00.829811+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:13f7015466a6465ad748a566baf4624c32299576ff1f1b0696cf3c1c5d3979da" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2474/tests/capture.py b/tasks/henrygd__beszel-2474/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2474/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/henrygd__beszel-2474/tests/instruction.md b/tasks/henrygd__beszel-2474/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..46922f666053d4dca5c07f951044408aa96e6161 --- /dev/null +++ b/tasks/henrygd__beszel-2474/tests/instruction.md @@ -0,0 +1,38 @@ +# Issue + +**Title:** fix(agent): count ZFS snapshot reads in pool I/O stats + +## Description + +## 📃 Description + +. + +Reads through `.zfs/snapshot/` never appear in Beszel's pool I/O graph, even while `htop`/`iotop` show sustained reads. Two kernel-side facts cause this: + +- OpenZFS intentionally skips creating `objset-*` kstats for snapshot objsets (`dataset_kstats_create()` returns early on `dmu_objset_is_snapshot()`), so summing per-dataset counters — the fallback `readPoolCounters()` uses whenever the `io` file is missing — can never see snapshot traffic. +- The pool-level `io` kstat itself only exists on OpenZFS ≤ 2.0 (it was removed in 2.1), so on current kernels the objset sum is the only source beszel reads. + +OpenZFS 2.3 added pool-wide logical read/write counters to the `iostats` kstat (`arc_read_bytes`, `direct_read_bytes`, `arc_write_bytes`, `direct_write_bytes`), fed by `spa_iostats_read_add`/`spa_iostats_write_add` — the same accounting hooks that attribute I/O to userspace tasks (`task_io_account_read`), which is why they line up with what `iotop` reports. These counters are pool-scoped rather than dataset-scoped, so they cover mounted snapshots too. + +Changes: + +- Prefer `iostats` (`arc_*` + `direct_*` byte counters) in `readPoolCounters()` when all four fields are present (OpenZFS 2.3+). On earlier releases the file exists but only carries TRIM stats, so the reader requires all four counters and falls through when they are absent. +- Keep the legacy `io` counters (OpenZFS ≤ 2.0) and the `objset-*` sum as fallbacks, unchanged. +- Add `iostats` to the pool discovery glob so a pool exposing only `state`/`iostats` is still found. + +Tests cover the new source (`iostats` beats the incomplete objset sum), the pre-2.3 shape (TRIM-only `iostats` falls back to `objset-*`), and required-field validation. Verified with `go build ./...`, `go vet ./...`, and `go test -tags testing ./zfs/... -count=1` (all pass); the new test fails on the pre-fix code path (returns the objset sum instead of the `iostats` total). + +One known limit: on OpenZFS 2.1–2.2 there is no procfs counter at all that includes snapshot reads, so those kernels keep the existing dataset-sum behavior. + +## 🪵 Changelog + +### 🔧 Fixed + +- ZFS pool I/O stats now count reads served through `.zfs/snapshot/` on OpenZFS 2.3+ by preferring the pool-wide `iostats` counters. + +AI-assisted. I wrote and verified this change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `1ab38e57c59c`. 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/henrygd__beszel-2474/tests/oracle.patch b/tasks/henrygd__beszel-2474/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..096f01226416066250ad97c97400345466195103 --- /dev/null +++ b/tasks/henrygd__beszel-2474/tests/oracle.patch @@ -0,0 +1,254 @@ +diff --git a/agent/zfs/zfs_linux.go b/agent/zfs/zfs_linux.go +index b5a25779..b297678a 100644 +--- a/agent/zfs/zfs_linux.go ++++ b/agent/zfs/zfs_linux.go +@@ -18,6 +18,11 @@ var ( + devZfsPath = "/dev/zfs" + ) + ++// errNoPoolIOStats marks an "iostats" file that predates OpenZFS 2.3 and ++// reports no pool read/write counters (TRIM statistics only), so callers may ++// fall back to older counter sources. ++var errNoPoolIOStats = errors.New("no pool I/O counters") ++ + func ARCSize() (uint64, error) { + file, err := os.Open(filepath.Join(procZfsPath, "arcstats")) + if err != nil { +@@ -61,7 +66,7 @@ func checkZfsDevice() error { + // ZFS collector and avoid keeping a `zpool iostat` subprocess alive. + func PoolKernelStats() ([]PoolKernelStat, error) { + poolDirs := make(map[string]struct{}) +- for _, filename := range []string{"state", "io", "objset-*"} { ++ for _, filename := range []string{"state", "io", "iostats", "objset-*"} { + paths, err := filepath.Glob(filepath.Join(procZfsPath, "*", filename)) + if err != nil { + return nil, err +@@ -97,11 +102,25 @@ func PoolKernelStats() ([]PoolKernelStat, error) { + return pools, nil + } + +-// readPoolCounters supports both ZFS kernel interfaces. OpenZFS through 2.3 +-// exposes aggregate vdev counters in "io". When that file is unavailable, sum +-// the logical I/O counters exposed for each dataset in the pool. ++// readPoolCounters supports the ZFS kernel interfaces. OpenZFS 2.3+ exposes ++// pool-wide read/write counters in "iostats" that cover every objset, ++// including mounted snapshots, which never get an "objset-*" kstat. OpenZFS ++// through 2.0 exposes aggregate vdev counters in "io". When neither pool-level ++// interface is usable, sum the logical I/O counters exposed for each dataset. + func readPoolCounters(poolDir string) (uint64, uint64, error) { +- nread, nwrite, err := readPoolIO(filepath.Join(poolDir, "io")) ++ nread, nwrite, err := readPoolIOStats(filepath.Join(poolDir, "iostats")) ++ if err == nil { ++ return nread, nwrite, nil ++ } ++ // Older sources are tried only when "iostats" is absent or predates ++ // OpenZFS 2.3. A read or parse failure on a usable file is returned: ++ // silently switching counter sources would feed kernelStats counters ++ // from different interfaces under the same pool name and produce a ++ // false I/O spike once "iostats" recovers. ++ if !errors.Is(err, os.ErrNotExist) && !errors.Is(err, errNoPoolIOStats) { ++ return 0, 0, err ++ } ++ nread, nwrite, err = readPoolIO(filepath.Join(poolDir, "io")) + if err == nil || !errors.Is(err, os.ErrNotExist) { + return nread, nwrite, err + } +@@ -144,6 +163,59 @@ func readPoolIO(path string) (uint64, uint64, error) { + return 0, 0, fmt.Errorf("I/O counters not found in %s", path) + } + ++// readPoolIOStats reads the pool I/O counters exported by OpenZFS 2.3+ in the ++// "iostats" kstat. Reads are counted on ARC misses at their compressed size, so ++// reads served from the ARC are excluded; writes are counted at their logical ++// size. The file exists on earlier releases but then only reports TRIM ++// statistics, so all four byte counters are required for the file to be usable. ++func readPoolIOStats(path string) (uint64, uint64, error) { ++ file, err := os.Open(path) ++ if err != nil { ++ return 0, 0, err ++ } ++ defer file.Close() ++ ++ var arcRead, arcWrite, directRead, directWrite uint64 ++ var found uint8 ++ scanner := bufio.NewScanner(file) ++ for scanner.Scan() { ++ fields := strings.Fields(scanner.Text()) ++ if len(fields) < 3 { ++ continue ++ } ++ var target *uint64 ++ var bit uint8 ++ switch fields[0] { ++ case "arc_read_bytes": ++ target, bit = &arcRead, 1<<0 ++ case "direct_read_bytes": ++ target, bit = &directRead, 1<<1 ++ case "arc_write_bytes": ++ target, bit = &arcWrite, 1<<2 ++ case "direct_write_bytes": ++ target, bit = &directWrite, 1<<3 ++ default: ++ continue ++ } ++ value, err := strconv.ParseUint(fields[2], 10, 64) ++ if err != nil { ++ return 0, 0, fmt.Errorf("parsing %s in %s: %w", fields[0], path, err) ++ } ++ *target = value ++ found |= bit ++ } ++ if err := scanner.Err(); err != nil { ++ return 0, 0, err ++ } ++ if found == 0 { ++ return 0, 0, fmt.Errorf("%w in %s", errNoPoolIOStats, path) ++ } ++ if found != 0x0f { ++ return 0, 0, fmt.Errorf("incomplete pool I/O counters in %s", path) ++ } ++ return arcRead + directRead, arcWrite + directWrite, nil ++} ++ + func readPoolObjsets(poolDir string) (uint64, uint64, error) { + paths, err := filepath.Glob(filepath.Join(poolDir, "objset-*")) + if err != nil { +diff --git a/agent/zfs/zfs_linux_test.go b/agent/zfs/zfs_linux_test.go +index 7ecb59a0..41f216ba 100644 +--- a/agent/zfs/zfs_linux_test.go ++++ b/agent/zfs/zfs_linux_test.go +@@ -66,6 +66,111 @@ func TestPoolKernelStatsOpenZfs24(t *testing.T) { + }, stats[0]) + } + ++func TestPoolKernelStatsOpenZfs23(t *testing.T) { ++ root := t.TempDir() ++ oldPath := procZfsPath ++ procZfsPath = root ++ t.Cleanup(func() { procZfsPath = oldPath }) ++ ++ // OpenZFS 2.3+ exposes logical pool read/write counters in "iostats". ++ // They cover every objset, including mounted snapshots, which never get ++ // an "objset-*" kstat, so the objset sum alone under-reports reads. ++ poolDir := filepath.Join(root, "tank") ++ require.NoError(t, os.MkdirAll(poolDir, 0o755)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "state"), []byte("ONLINE\n"), 0o644)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "iostats"), []byte( ++ "15 1 0x01 26 5176 227423 2127661979232\n"+ ++ "name type data\n"+ ++ "trim_extents_written 4 0\n"+ ++ "arc_read_count 4 12\n"+ ++ "arc_read_bytes 4 5000\n"+ ++ "arc_write_count 4 7\n"+ ++ "arc_write_bytes 4 3000\n"+ ++ "direct_read_count 4 1\n"+ ++ "direct_read_bytes 4 500\n"+ ++ "direct_write_count 4 1\n"+ ++ "direct_write_bytes 4 200\n", ++ ), 0o644)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "objset-0x1"), []byte( ++ "34 1 0x01 28 7872 0 0\n"+ ++ "name type data\n"+ ++ "dataset_name 7 tank\n"+ ++ "nwritten 4 2000\n"+ ++ "nread 4 1000\n", ++ ), 0o644)) ++ ++ stats, err := PoolKernelStats() ++ require.NoError(t, err) ++ require.Len(t, stats, 1) ++ assert.Equal(t, PoolKernelStat{ ++ Name: "tank", Health: "ONLINE", NRead: 5500, NWrite: 3200, ++ }, stats[0]) ++} ++ ++func TestPoolKernelStatsIOStatsTrimOnly(t *testing.T) { ++ root := t.TempDir() ++ oldPath := procZfsPath ++ procZfsPath = root ++ t.Cleanup(func() { procZfsPath = oldPath }) ++ ++ // Before OpenZFS 2.3 the "iostats" file only reports TRIM counters, so ++ // the per-dataset "objset-*" files remain the only usable source. ++ poolDir := filepath.Join(root, "tank") ++ require.NoError(t, os.MkdirAll(poolDir, 0o755)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "state"), []byte("ONLINE\n"), 0o644)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "iostats"), []byte( ++ "15 1 0x01 18 3736 227423 2127661979232\n"+ ++ "name type data\n"+ ++ "trim_extents_written 4 10\n"+ ++ "trim_bytes_written 4 4096\n", ++ ), 0o644)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "objset-0x1"), []byte( ++ "34 1 0x01 28 7872 0 0\n"+ ++ "name type data\n"+ ++ "dataset_name 7 tank\n"+ ++ "nwritten 4 2000\n"+ ++ "nread 4 1000\n", ++ ), 0o644)) ++ ++ stats, err := PoolKernelStats() ++ require.NoError(t, err) ++ require.Len(t, stats, 1) ++ assert.Equal(t, PoolKernelStat{ ++ Name: "tank", Health: "ONLINE", NRead: 1000, NWrite: 2000, ++ }, stats[0]) ++} ++ ++func TestPoolKernelStatsIOStatsErrorDoesNotFallback(t *testing.T) { ++ root := t.TempDir() ++ oldPath := procZfsPath ++ procZfsPath = root ++ t.Cleanup(func() { procZfsPath = oldPath }) ++ ++ // A malformed "iostats" on a kernel that supports it must surface an ++ // error. Silently switching to the per-dataset sum would drop snapshot ++ // reads and, when "iostats" recovers, make kernelStats report a false ++ // I/O spike by comparing counters from two different interfaces. ++ poolDir := filepath.Join(root, "tank") ++ require.NoError(t, os.MkdirAll(poolDir, 0o755)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "state"), []byte("ONLINE\n"), 0o644)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "iostats"), []byte( ++ "arc_read_bytes 4 notanumber\n"+ ++ "arc_write_bytes 4 3000\n"+ ++ "direct_read_bytes 4 500\n"+ ++ "direct_write_bytes 4 200\n", ++ ), 0o644)) ++ require.NoError(t, os.WriteFile(filepath.Join(poolDir, "objset-0x1"), []byte( ++ "34 1 0x01 28 7872 0 0\n"+ ++ "name type data\n"+ ++ "dataset_name 7 tank\n"+ ++ "nwritten 4 2000\n"+ ++ "nread 4 1000\n", ++ ), 0o644)) ++ ++ _, err := PoolKernelStats() ++ require.Error(t, err) ++} ++ + func TestPoolKernelStatsNoZfs(t *testing.T) { + oldPath := procZfsPath + procZfsPath = t.TempDir() +@@ -89,6 +194,22 @@ func TestReadObjsetIORequiresAllCounters(t *testing.T) { + require.Error(t, err) + } + ++func TestReadPoolIOStatsRequiresAllCounters(t *testing.T) { ++ path := filepath.Join(t.TempDir(), "iostats") ++ require.NoError(t, os.WriteFile(path, []byte( ++ "arc_read_bytes 4 10\ndirect_read_bytes 4 5\narc_write_bytes 4 7\n"), 0o644)) ++ _, _, err := readPoolIOStats(path) ++ require.Error(t, err) ++} ++ ++func TestReadPoolIOStatsTrimOnlySignalsFallback(t *testing.T) { ++ path := filepath.Join(t.TempDir(), "iostats") ++ require.NoError(t, os.WriteFile(path, []byte( ++ "trim_extents_written 4 10\ntrim_bytes_written 4 4096\n"), 0o644)) ++ _, _, err := readPoolIOStats(path) ++ assert.ErrorIs(t, err, errNoPoolIOStats) ++} ++ + func TestCollectorsSkipCommandsWhenDevZfsMissing(t *testing.T) { + root := t.TempDir() + oldDevZfsPath := devZfsPath diff --git a/tasks/henrygd__beszel-2474/tests/test.sh b/tasks/henrygd__beszel-2474/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..879a0928bac3d35fea4570224c28b75fd66d907c --- /dev/null +++ b/tasks/henrygd__beszel-2474/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 1ab38e57c59c470ae579caa268b7d9dcdbda95ba > "$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/henrygd__beszel-2474/tests/verifier.py b/tasks/henrygd__beszel-2474/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2474/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/henrygd__beszel-2476/environment/Dockerfile b/tasks/henrygd__beszel-2476/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2928457d4f79e5d60857c8e26edb06ad94040fea --- /dev/null +++ b/tasks/henrygd__beszel-2476/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6c47ca8eccb1ed2b8148546f4f0acebd10cad0a5 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6c47ca8eccb1ed2b8148546f4f0acebd10cad0a5 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6c47ca8eccb1ed2b8148546f4f0acebd10cad0a5 \ + && 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/henrygd__beszel-2476/instruction.md b/tasks/henrygd__beszel-2476/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68e1763beef5f46ceed6975f2cdcdd2a0611cfe8 --- /dev/null +++ b/tasks/henrygd__beszel-2476/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** hotfix: remove unused useLingui + +## Description + +## 📃 Description + +After PR #2403 was merged, `systemTranslation` was no longer being called in the navbar file; subsequently, PR #2405 was merged, which included changes based on the assumption that `systemTranslation` was still being called. +This hotfix removes the usage and prevents the following error: +``` +src/components/navbar.tsx:45:8 - error TS6133: 't' is declared but its value is never read. +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6c47ca8eccb1`. 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/henrygd__beszel-2476/solution/patch.diff b/tasks/henrygd__beszel-2476/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1a9323691c29fff2e66156ae007c322174b60e8d --- /dev/null +++ b/tasks/henrygd__beszel-2476/solution/patch.diff @@ -0,0 +1,18 @@ +diff --git a/internal/site/src/components/navbar.tsx b/internal/site/src/components/navbar.tsx +index 79b50c31..28bf234c 100644 +--- a/internal/site/src/components/navbar.tsx ++++ b/internal/site/src/components/navbar.tsx +@@ -1,4 +1,4 @@ +-import { Trans, useLingui } from "@lingui/react/macro" ++import { Trans } from "@lingui/react/macro" + import { getPagePath } from "@nanostores/router" + import { + ContainerIcon, +@@ -42,7 +42,6 @@ const CommandPalette = lazy(() => import("./command-palette")) + const isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0 + + export default function Navbar() { +- const { t } = useLingui() + const [addSystemDialogOpen, setAddSystemDialogOpen] = useState(false) + const [commandPaletteOpen, setCommandPaletteOpen] = useState(false) + diff --git a/tasks/henrygd__beszel-2476/solution/solve.sh b/tasks/henrygd__beszel-2476/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2476/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/henrygd__beszel-2476/task.toml b/tasks/henrygd__beszel-2476/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..43dcc52a15008b448e163e406adebd107d974e45 --- /dev/null +++ b/tasks/henrygd__beszel-2476/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2476" +description = "hotfix: remove unused useLingui" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "6c47ca8eccb1ed2b8148546f4f0acebd10cad0a5" +reference = "https://github.com/henrygd/beszel/pull/2476" +source_access = "auto" +built_at = "2026-11-16T16:09:53.453005+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:741e4a1f4be8e29587d09fcc237fa7c9e27df8f91a99b56fbe18b4f376a29a7a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-29T21:21:46Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/navbar.tsx", +] +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:00.830267+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:710621dd50673cc1ea16ef9bdadbaf322962d0610208c9084c152a1ca5d4c533" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2476/tests/capture.py b/tasks/henrygd__beszel-2476/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2476/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/henrygd__beszel-2476/tests/instruction.md b/tasks/henrygd__beszel-2476/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68e1763beef5f46ceed6975f2cdcdd2a0611cfe8 --- /dev/null +++ b/tasks/henrygd__beszel-2476/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** hotfix: remove unused useLingui + +## Description + +## 📃 Description + +After PR #2403 was merged, `systemTranslation` was no longer being called in the navbar file; subsequently, PR #2405 was merged, which included changes based on the assumption that `systemTranslation` was still being called. +This hotfix removes the usage and prevents the following error: +``` +src/components/navbar.tsx:45:8 - error TS6133: 't' is declared but its value is never read. +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6c47ca8eccb1`. 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/henrygd__beszel-2476/tests/oracle.patch b/tasks/henrygd__beszel-2476/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1a9323691c29fff2e66156ae007c322174b60e8d --- /dev/null +++ b/tasks/henrygd__beszel-2476/tests/oracle.patch @@ -0,0 +1,18 @@ +diff --git a/internal/site/src/components/navbar.tsx b/internal/site/src/components/navbar.tsx +index 79b50c31..28bf234c 100644 +--- a/internal/site/src/components/navbar.tsx ++++ b/internal/site/src/components/navbar.tsx +@@ -1,4 +1,4 @@ +-import { Trans, useLingui } from "@lingui/react/macro" ++import { Trans } from "@lingui/react/macro" + import { getPagePath } from "@nanostores/router" + import { + ContainerIcon, +@@ -42,7 +42,6 @@ const CommandPalette = lazy(() => import("./command-palette")) + const isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0 + + export default function Navbar() { +- const { t } = useLingui() + const [addSystemDialogOpen, setAddSystemDialogOpen] = useState(false) + const [commandPaletteOpen, setCommandPaletteOpen] = useState(false) + diff --git a/tasks/henrygd__beszel-2476/tests/test.sh b/tasks/henrygd__beszel-2476/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3a2618515e0ad31bd928d38efb5e252a045d73c8 --- /dev/null +++ b/tasks/henrygd__beszel-2476/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 6c47ca8eccb1ed2b8148546f4f0acebd10cad0a5 > "$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/henrygd__beszel-2476/tests/verifier.py b/tasks/henrygd__beszel-2476/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2476/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/henrygd__beszel-2478/environment/Dockerfile b/tasks/henrygd__beszel-2478/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..db0518cda841c2544c26d51520fffe7b8c4d3bc1 --- /dev/null +++ b/tasks/henrygd__beszel-2478/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e01e2a20e9d32e46ed5eaaa4cf48cf04f56d9a9f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e01e2a20e9d32e46ed5eaaa4cf48cf04f56d9a9f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e01e2a20e9d32e46ed5eaaa4cf48cf04f56d9a9f \ + && 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/henrygd__beszel-2478/instruction.md b/tasks/henrygd__beszel-2478/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9233b551dd38a1c855838ec25d6751422c7a099e --- /dev/null +++ b/tasks/henrygd__beszel-2478/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** feat(site): allow dismissing the active alerts banner and soften its red + +## Description + +## 📃 Description + +Adds a dismiss button to the active alerts banner. Once dismissed, it stays hidden until a new alert triggers. + +This PR also softens the banner's red in dark mode, following the feedback on #2445. + +## 🪵 Changelog + +### ➕ Added + +- Optional dismiss button on `AlertBannerSheet` +- Dismiss button on the active alerts banner. The dismissal is saved in the browser, so it survives a page reload. + +### ✏️ Changed + +- In dark mode the banner and sheet icons use `red-400` instead of `red-500`, and the border is softer + +## 📷 Screenshots + +Scherm­afbeelding 2026-09-29 om 23 58 58 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e01e2a20e9d3`. 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/henrygd__beszel-2478/solution/patch.diff b/tasks/henrygd__beszel-2478/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9d77ae72ec443873b6ab1c3892b59f2bb5c33b8d --- /dev/null +++ b/tasks/henrygd__beszel-2478/solution/patch.diff @@ -0,0 +1,179 @@ +diff --git a/internal/site/src/components/active-alerts.tsx b/internal/site/src/components/active-alerts.tsx +index 41af5f35..e00efd26 100644 +--- a/internal/site/src/components/active-alerts.tsx ++++ b/internal/site/src/components/active-alerts.tsx +@@ -1,10 +1,11 @@ + import { alertInfo } from "@/lib/alerts" + import { $alerts, $allSystemsById } from "@/lib/stores" ++import { useBrowserStorage } from "@/lib/utils" + import type { AlertRecord } from "@/types" + import { Plural, Trans } from "@lingui/react/macro" + import { useStore } from "@nanostores/react" + import { getPagePath } from "@nanostores/router" +-import { useMemo, useState } from "react" ++import { useEffect, useMemo, useState } from "react" + import { AlertBannerSheet, AlertBannerSheetItem } from "./alert-banner-sheet" + import { $router } from "./router" + +@@ -49,6 +50,9 @@ export const ActiveAlerts = ({ className }: { className?: string }) => { + const alerts = useStore($alerts) + const systems = useStore($allSystemsById) + const [open, setOpen] = useState(false) ++ // ids of the alerts that were active when the banner was last dismissed. ++ // session storage because a retrigger while the page is closed keeps the same id. ++ const [dismissedIds, setDismissedIds] = useBrowserStorage("dismissedAlerts", [], sessionStorage) + + const { activeAlerts, systemCount, alertsKey } = useMemo(() => { + const activeAlerts: AlertRecord[] = [] +@@ -69,9 +73,24 @@ export const ActiveAlerts = ({ className }: { className?: string }) => { + return { activeAlerts, systemCount: systemIds.size, alertsKey: alertsKey.join("") } + }, [alerts]) + ++ // forget dismissed alerts once they resolve so they show again if they retrigger. ++ // skipped while alerts are still loading so a reload doesn't clear the dismissal, ++ // and re-run once loaded in case they resolved while the page was closed. ++ const alertsLoaded = Object.keys(alerts).length > 0 ++ useEffect(() => { ++ if (!alertsLoaded) { ++ return ++ } ++ const activeIds = new Set(activeAlerts.map((alert) => alert.id)) ++ if (dismissedIds.some((id) => !activeIds.has(id))) { ++ setDismissedIds(dismissedIds.filter((id) => activeIds.has(id))) ++ } ++ }, [alertsKey, alertsLoaded]) ++ + return useMemo(() => { + const alertCount = activeAlerts.length +- if (alertCount === 0) { ++ // stay hidden after dismissing until an alert triggers that wasn't active at the time ++ if (alertCount === 0 || activeAlerts.every((alert) => dismissedIds.includes(alert.id))) { + return null + } + // name the alert directly in the banner when there is only one +@@ -80,6 +99,7 @@ export const ActiveAlerts = ({ className }: { className?: string }) => { + setDismissedIds(activeAlerts.map((alert) => alert.id))} + className={className} + title={ + alertCount === 1 ? ( +@@ -117,5 +137,5 @@ export const ActiveAlerts = ({ className }: { className?: string }) => { + })} + + ) +- }, [alertsKey, systemCount, systems, open, className]) ++ }, [alertsKey, systemCount, systems, open, className, dismissedIds]) + } +diff --git a/internal/site/src/components/alert-banner-sheet.tsx b/internal/site/src/components/alert-banner-sheet.tsx +index ab066f95..a109fe97 100644 +--- a/internal/site/src/components/alert-banner-sheet.tsx ++++ b/internal/site/src/components/alert-banner-sheet.tsx +@@ -1,5 +1,5 @@ +-import { Trans } from "@lingui/react/macro" +-import { ChevronRightIcon, type LucideIcon, TriangleAlertIcon } from "lucide-react" ++import { Trans, useLingui } from "@lingui/react/macro" ++import { ChevronRightIcon, type LucideIcon, TriangleAlertIcon, XIcon } from "lucide-react" + import type { ReactNode } from "react" + import { cn } from "@/lib/utils" + import { Link } from "./router" +@@ -20,6 +20,7 @@ export function AlertBannerSheet({ + sheetTitle, + sheetDescription, + icon: Icon = TriangleAlertIcon, ++ onDismiss, + className, + children, + }: { +@@ -31,9 +32,12 @@ export function AlertBannerSheet({ + sheetTitle: ReactNode + sheetDescription?: ReactNode + icon?: LucideIcon ++ /** Shows a dismiss button when provided */ ++ onDismiss?: () => void + className?: string + children: ReactNode + }) { ++ const { t } = useLingui() + return ( + + +@@ -42,7 +46,7 @@ export function AlertBannerSheet({ +
+ {title} + {description && ( +- {description} ++ {description} + )} +
+
+@@ -50,12 +54,24 @@ export function AlertBannerSheet({ + + ++ {onDismiss && ( ++ ++ )} + + + +@@ -88,7 +104,7 @@ export function AlertBannerSheetItem({ + onClick={onClick} + className="group flex items-start gap-3 rounded-lg border p-3 transition-colors hover:bg-accent/60" + > +-
++
+ +
+
+diff --git a/internal/site/src/components/ui/alert.tsx b/internal/site/src/components/ui/alert.tsx +index 52e92237..2b187be5 100644 +--- a/internal/site/src/components/ui/alert.tsx ++++ b/internal/site/src/components/ui/alert.tsx +@@ -10,7 +10,7 @@ const alertVariants = cva( + variant: { + default: "bg-background text-foreground [&>svg]:text-foreground", + destructive: +- "bg-destructive/5 border-destructive/50 text-destructive dark:bg-destructive/6 dark:text-red-500 dark:border-destructive/70 [&>svg]:text-destructive", ++ "bg-destructive/5 border-destructive/50 text-destructive dark:bg-destructive/6 dark:text-red-400 dark:border-destructive/50 [&>svg]:text-destructive dark:[&>svg]:text-red-400", + }, + }, + defaultVariants: { +diff --git a/internal/site/src/lib/utils.ts b/internal/site/src/lib/utils.ts +index 4860c706..a85bed08 100644 +--- a/internal/site/src/lib/utils.ts ++++ b/internal/site/src/lib/utils.ts +@@ -229,14 +229,14 @@ function getStorageValue(key: string, defaultValue: unknown, storageInterface: S + /** Hook to sync value in local or session storage */ + export function useBrowserStorage(key: string, defaultValue: T, storageInterface: Storage = localStorage) { + key = `besz-${key}` +- const [value, setValue] = useState(() => { ++ const [value, setValue] = useState(() => { + return getStorageValue(key, defaultValue, storageInterface) + }) + useEffect(() => { + storageInterface?.setItem(key, JSON.stringify(value)) + }, [key, value]) + +- return [value, setValue] ++ return [value, setValue] as const + } + + /** Format temperature to user's preferred unit */ diff --git a/tasks/henrygd__beszel-2478/solution/solve.sh b/tasks/henrygd__beszel-2478/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2478/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/henrygd__beszel-2478/task.toml b/tasks/henrygd__beszel-2478/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..127581e94de21e3668a53f89e617d4d090df7aeb --- /dev/null +++ b/tasks/henrygd__beszel-2478/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2478" +description = "feat(site): allow dismissing the active alerts banner and soften its red" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "e01e2a20e9d32e46ed5eaaa4cf48cf04f56d9a9f" +reference = "https://github.com/henrygd/beszel/pull/2478" +source_access = "auto" +built_at = "2026-11-16T16:09:53.448733+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:069e0d1b2b6c91a5d00ecddd0b22c0e84d2d42b6d6833aed191e42edff439d16" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-30T16:17:03Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/active-alerts.tsx", + "internal/site/src/components/alert-banner-sheet.tsx", + "internal/site/src/components/ui/alert.tsx", + "internal/site/src/lib/utils.ts", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 58 +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:00.830733+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0b01f96747c5bc00380d8ac0dd58735c6d2b0008a1bee7d4a8f0b6fb77e6e2c2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2478/tests/capture.py b/tasks/henrygd__beszel-2478/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2478/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/henrygd__beszel-2478/tests/instruction.md b/tasks/henrygd__beszel-2478/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9233b551dd38a1c855838ec25d6751422c7a099e --- /dev/null +++ b/tasks/henrygd__beszel-2478/tests/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** feat(site): allow dismissing the active alerts banner and soften its red + +## Description + +## 📃 Description + +Adds a dismiss button to the active alerts banner. Once dismissed, it stays hidden until a new alert triggers. + +This PR also softens the banner's red in dark mode, following the feedback on #2445. + +## 🪵 Changelog + +### ➕ Added + +- Optional dismiss button on `AlertBannerSheet` +- Dismiss button on the active alerts banner. The dismissal is saved in the browser, so it survives a page reload. + +### ✏️ Changed + +- In dark mode the banner and sheet icons use `red-400` instead of `red-500`, and the border is softer + +## 📷 Screenshots + +Scherm­afbeelding 2026-09-29 om 23 58 58 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e01e2a20e9d3`. 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/henrygd__beszel-2478/tests/oracle.patch b/tasks/henrygd__beszel-2478/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9d77ae72ec443873b6ab1c3892b59f2bb5c33b8d --- /dev/null +++ b/tasks/henrygd__beszel-2478/tests/oracle.patch @@ -0,0 +1,179 @@ +diff --git a/internal/site/src/components/active-alerts.tsx b/internal/site/src/components/active-alerts.tsx +index 41af5f35..e00efd26 100644 +--- a/internal/site/src/components/active-alerts.tsx ++++ b/internal/site/src/components/active-alerts.tsx +@@ -1,10 +1,11 @@ + import { alertInfo } from "@/lib/alerts" + import { $alerts, $allSystemsById } from "@/lib/stores" ++import { useBrowserStorage } from "@/lib/utils" + import type { AlertRecord } from "@/types" + import { Plural, Trans } from "@lingui/react/macro" + import { useStore } from "@nanostores/react" + import { getPagePath } from "@nanostores/router" +-import { useMemo, useState } from "react" ++import { useEffect, useMemo, useState } from "react" + import { AlertBannerSheet, AlertBannerSheetItem } from "./alert-banner-sheet" + import { $router } from "./router" + +@@ -49,6 +50,9 @@ export const ActiveAlerts = ({ className }: { className?: string }) => { + const alerts = useStore($alerts) + const systems = useStore($allSystemsById) + const [open, setOpen] = useState(false) ++ // ids of the alerts that were active when the banner was last dismissed. ++ // session storage because a retrigger while the page is closed keeps the same id. ++ const [dismissedIds, setDismissedIds] = useBrowserStorage("dismissedAlerts", [], sessionStorage) + + const { activeAlerts, systemCount, alertsKey } = useMemo(() => { + const activeAlerts: AlertRecord[] = [] +@@ -69,9 +73,24 @@ export const ActiveAlerts = ({ className }: { className?: string }) => { + return { activeAlerts, systemCount: systemIds.size, alertsKey: alertsKey.join("") } + }, [alerts]) + ++ // forget dismissed alerts once they resolve so they show again if they retrigger. ++ // skipped while alerts are still loading so a reload doesn't clear the dismissal, ++ // and re-run once loaded in case they resolved while the page was closed. ++ const alertsLoaded = Object.keys(alerts).length > 0 ++ useEffect(() => { ++ if (!alertsLoaded) { ++ return ++ } ++ const activeIds = new Set(activeAlerts.map((alert) => alert.id)) ++ if (dismissedIds.some((id) => !activeIds.has(id))) { ++ setDismissedIds(dismissedIds.filter((id) => activeIds.has(id))) ++ } ++ }, [alertsKey, alertsLoaded]) ++ + return useMemo(() => { + const alertCount = activeAlerts.length +- if (alertCount === 0) { ++ // stay hidden after dismissing until an alert triggers that wasn't active at the time ++ if (alertCount === 0 || activeAlerts.every((alert) => dismissedIds.includes(alert.id))) { + return null + } + // name the alert directly in the banner when there is only one +@@ -80,6 +99,7 @@ export const ActiveAlerts = ({ className }: { className?: string }) => { + setDismissedIds(activeAlerts.map((alert) => alert.id))} + className={className} + title={ + alertCount === 1 ? ( +@@ -117,5 +137,5 @@ export const ActiveAlerts = ({ className }: { className?: string }) => { + })} + + ) +- }, [alertsKey, systemCount, systems, open, className]) ++ }, [alertsKey, systemCount, systems, open, className, dismissedIds]) + } +diff --git a/internal/site/src/components/alert-banner-sheet.tsx b/internal/site/src/components/alert-banner-sheet.tsx +index ab066f95..a109fe97 100644 +--- a/internal/site/src/components/alert-banner-sheet.tsx ++++ b/internal/site/src/components/alert-banner-sheet.tsx +@@ -1,5 +1,5 @@ +-import { Trans } from "@lingui/react/macro" +-import { ChevronRightIcon, type LucideIcon, TriangleAlertIcon } from "lucide-react" ++import { Trans, useLingui } from "@lingui/react/macro" ++import { ChevronRightIcon, type LucideIcon, TriangleAlertIcon, XIcon } from "lucide-react" + import type { ReactNode } from "react" + import { cn } from "@/lib/utils" + import { Link } from "./router" +@@ -20,6 +20,7 @@ export function AlertBannerSheet({ + sheetTitle, + sheetDescription, + icon: Icon = TriangleAlertIcon, ++ onDismiss, + className, + children, + }: { +@@ -31,9 +32,12 @@ export function AlertBannerSheet({ + sheetTitle: ReactNode + sheetDescription?: ReactNode + icon?: LucideIcon ++ /** Shows a dismiss button when provided */ ++ onDismiss?: () => void + className?: string + children: ReactNode + }) { ++ const { t } = useLingui() + return ( + + +@@ -42,7 +46,7 @@ export function AlertBannerSheet({ +
+ {title} + {description && ( +- {description} ++ {description} + )} +
+
+@@ -50,12 +54,24 @@ export function AlertBannerSheet({ + + ++ {onDismiss && ( ++ ++ )} + + + +@@ -88,7 +104,7 @@ export function AlertBannerSheetItem({ + onClick={onClick} + className="group flex items-start gap-3 rounded-lg border p-3 transition-colors hover:bg-accent/60" + > +-
++
+ +
+
+diff --git a/internal/site/src/components/ui/alert.tsx b/internal/site/src/components/ui/alert.tsx +index 52e92237..2b187be5 100644 +--- a/internal/site/src/components/ui/alert.tsx ++++ b/internal/site/src/components/ui/alert.tsx +@@ -10,7 +10,7 @@ const alertVariants = cva( + variant: { + default: "bg-background text-foreground [&>svg]:text-foreground", + destructive: +- "bg-destructive/5 border-destructive/50 text-destructive dark:bg-destructive/6 dark:text-red-500 dark:border-destructive/70 [&>svg]:text-destructive", ++ "bg-destructive/5 border-destructive/50 text-destructive dark:bg-destructive/6 dark:text-red-400 dark:border-destructive/50 [&>svg]:text-destructive dark:[&>svg]:text-red-400", + }, + }, + defaultVariants: { +diff --git a/internal/site/src/lib/utils.ts b/internal/site/src/lib/utils.ts +index 4860c706..a85bed08 100644 +--- a/internal/site/src/lib/utils.ts ++++ b/internal/site/src/lib/utils.ts +@@ -229,14 +229,14 @@ function getStorageValue(key: string, defaultValue: unknown, storageInterface: S + /** Hook to sync value in local or session storage */ + export function useBrowserStorage(key: string, defaultValue: T, storageInterface: Storage = localStorage) { + key = `besz-${key}` +- const [value, setValue] = useState(() => { ++ const [value, setValue] = useState(() => { + return getStorageValue(key, defaultValue, storageInterface) + }) + useEffect(() => { + storageInterface?.setItem(key, JSON.stringify(value)) + }, [key, value]) + +- return [value, setValue] ++ return [value, setValue] as const + } + + /** Format temperature to user's preferred unit */ diff --git a/tasks/henrygd__beszel-2478/tests/test.sh b/tasks/henrygd__beszel-2478/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1f04fd93a2689ef93e7f22876f6264a6e06ae4ae --- /dev/null +++ b/tasks/henrygd__beszel-2478/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 e01e2a20e9d32e46ed5eaaa4cf48cf04f56d9a9f > "$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/henrygd__beszel-2478/tests/verifier.py b/tasks/henrygd__beszel-2478/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2478/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/henrygd__beszel-2480/environment/Dockerfile b/tasks/henrygd__beszel-2480/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..db0518cda841c2544c26d51520fffe7b8c4d3bc1 --- /dev/null +++ b/tasks/henrygd__beszel-2480/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e01e2a20e9d32e46ed5eaaa4cf48cf04f56d9a9f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e01e2a20e9d32e46ed5eaaa4cf48cf04f56d9a9f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e01e2a20e9d32e46ed5eaaa4cf48cf04f56d9a9f \ + && 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/henrygd__beszel-2480/instruction.md b/tasks/henrygd__beszel-2480/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1697a911a7f8f171e3314c372002a3d5e626d2d1 --- /dev/null +++ b/tasks/henrygd__beszel-2480/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** refactor(ui): remove "Copy to system" from network monitor actions + +## Description + +## 📃 Description + +Removes the **Copy to system** action from the network monitor row menu, and renames **Bulk copy** to **Copy bulk config**. + +Copy to system didn't add anything over the existing ways to add a monitor to other systems, and it was broken: + +- **Add Monitor** already lets you select multiple systems, so recreating a monitor elsewhere takes only a few fields. +- **Bulk copy → Bulk Add** already copies monitors between systems, and it does it better. It works for several monitors at once and skips systems that already have the monitor. +- **It failed silently.** Monitor IDs are a hash of system + target + protocol (+ port/server), so copying to a system that already had the monitor hit a duplicate ID. The error was swallowed, so nothing happened and no message was shown. +- **It offered unsupported systems.** It listed every system, including ones whose agent doesn't support network monitors. +- **It copied stale data.** It copied the source monitor's latest results and certificate info onto the new record. + +Fixing it properly would have meant a new dialog with its own duplicate detection mirroring the hub's ID logic, all to duplicate Bulk Add. Removing it is simpler. + +**Bulk copy** is renamed to **Copy bulk config** to make clear that it copies the config line meant for Bulk Add. + +## 🪵 Changelog + +### ✏️ Changed + +- Renamed the network monitor action **Bulk copy** to **Copy bulk config** + +### 🗑️ Removed + +- **Copy to system** action from the network monitor row menu. Use Add Monitor with multiple systems, or Copy bulk config → Bulk Add. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e01e2a20e9d3`. 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/henrygd__beszel-2480/solution/patch.diff b/tasks/henrygd__beszel-2480/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..297d70c00d1a48df8387e2deffc9348b23f9d122 --- /dev/null +++ b/tasks/henrygd__beszel-2480/solution/patch.diff @@ -0,0 +1,75 @@ +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx +index d3bf4751..91dde913 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx +@@ -15,7 +15,6 @@ import { + PauseCircleIcon, + PlayCircleIcon, + CopyIcon, +- CopyPlusIcon, + ShieldCheckIcon, + } from "lucide-react" + import { t } from "@lingui/core/macro" +@@ -25,9 +24,6 @@ import { + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, +- DropdownMenuSub, +- DropdownMenuSubContent, +- DropdownMenuSubTrigger, + DropdownMenuTrigger, + } from "@/components/ui/dropdown-menu" + import { Plural, Trans } from "@lingui/react/macro" +@@ -40,7 +36,6 @@ import { useMemo } from "react" + import { formatBulkMonitorLine } from "@/components/network-monitors-table/monitor-dialog" + import { Badge } from "../ui/badge" + import { getCertDaysLeft, getCertExpiryLevel, getMonitorTarget } from "@/lib/network-monitor-utils" +-import { pb } from "@/lib/api" + + const certExpiryDotColors = { ok: "bg-green-500", warning: "bg-yellow-500", critical: "bg-red-500" } + +@@ -308,11 +303,6 @@ export function getMonitorColumns( + const isBulkAction = actionRows.length > 1 + const shouldPause = actionRows.some((monitor) => monitor.enabled) + const bulkCopyContent = actionRows.map((monitor) => formatBulkMonitorLine(monitor)).join("\n") +- const allSystems = useStore($allSystemsById) +- const otherSystems = useMemo( +- () => Object.values(allSystems).filter((s) => !isBulkAction && s.id !== row.original.system), +- [allSystems, isBulkAction] +- ) + return ( + + +@@ -357,31 +347,8 @@ export function getMonitorColumns( + }} + > + +- Bulk copy ++ Copy bulk config + +- {!isBulkAction && otherSystems.length > 0 && ( +- +- +- +- Copy to system +- +- +- {otherSystems.map((sys) => ( +- { +- const { id: _id, system: _system, ...rest } = row.original +- pb.collection("network_monitors") +- .create({ ...rest, system: sys.id }) +- .catch(() => {}) +- }} +- > +- {sys.name} +- +- ))} +- +- +- )} + + { diff --git a/tasks/henrygd__beszel-2480/solution/solve.sh b/tasks/henrygd__beszel-2480/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/henrygd__beszel-2480/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/henrygd__beszel-2480/task.toml b/tasks/henrygd__beszel-2480/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f635533ec9dc60de82d97d061e80593dff635121 --- /dev/null +++ b/tasks/henrygd__beszel-2480/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/henrygd__beszel-2480" +description = "refactor(ui): remove \"Copy to system\" from network monitor actions" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "beszel", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "henrygd/beszel" +ref = "e01e2a20e9d32e46ed5eaaa4cf48cf04f56d9a9f" +reference = "https://github.com/henrygd/beszel/pull/2480" +source_access = "auto" +built_at = "2026-11-16T16:09:53.450262+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3ba38d8ea967d081ca0537847dfc78e311aab6d37286de4e266465c817425c72" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-30T16:13:32Z" +diff_format = "unified" +context_files = [ + "internal/site/src/components/network-monitors-table/network-monitors-columns.tsx", +] +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:00.831200+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:0b01f96747c5bc00380d8ac0dd58735c6d2b0008a1bee7d4a8f0b6fb77e6e2c2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/henrygd__beszel-2480/tests/capture.py b/tasks/henrygd__beszel-2480/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/henrygd__beszel-2480/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/henrygd__beszel-2480/tests/instruction.md b/tasks/henrygd__beszel-2480/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1697a911a7f8f171e3314c372002a3d5e626d2d1 --- /dev/null +++ b/tasks/henrygd__beszel-2480/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** refactor(ui): remove "Copy to system" from network monitor actions + +## Description + +## 📃 Description + +Removes the **Copy to system** action from the network monitor row menu, and renames **Bulk copy** to **Copy bulk config**. + +Copy to system didn't add anything over the existing ways to add a monitor to other systems, and it was broken: + +- **Add Monitor** already lets you select multiple systems, so recreating a monitor elsewhere takes only a few fields. +- **Bulk copy → Bulk Add** already copies monitors between systems, and it does it better. It works for several monitors at once and skips systems that already have the monitor. +- **It failed silently.** Monitor IDs are a hash of system + target + protocol (+ port/server), so copying to a system that already had the monitor hit a duplicate ID. The error was swallowed, so nothing happened and no message was shown. +- **It offered unsupported systems.** It listed every system, including ones whose agent doesn't support network monitors. +- **It copied stale data.** It copied the source monitor's latest results and certificate info onto the new record. + +Fixing it properly would have meant a new dialog with its own duplicate detection mirroring the hub's ID logic, all to duplicate Bulk Add. Removing it is simpler. + +**Bulk copy** is renamed to **Copy bulk config** to make clear that it copies the config line meant for Bulk Add. + +## 🪵 Changelog + +### ✏️ Changed + +- Renamed the network monitor action **Bulk copy** to **Copy bulk config** + +### 🗑️ Removed + +- **Copy to system** action from the network monitor row menu. Use Add Monitor with multiple systems, or Copy bulk config → Bulk Add. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e01e2a20e9d3`. 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/henrygd__beszel-2480/tests/oracle.patch b/tasks/henrygd__beszel-2480/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..297d70c00d1a48df8387e2deffc9348b23f9d122 --- /dev/null +++ b/tasks/henrygd__beszel-2480/tests/oracle.patch @@ -0,0 +1,75 @@ +diff --git a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx +index d3bf4751..91dde913 100644 +--- a/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx ++++ b/internal/site/src/components/network-monitors-table/network-monitors-columns.tsx +@@ -15,7 +15,6 @@ import { + PauseCircleIcon, + PlayCircleIcon, + CopyIcon, +- CopyPlusIcon, + ShieldCheckIcon, + } from "lucide-react" + import { t } from "@lingui/core/macro" +@@ -25,9 +24,6 @@ import { + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, +- DropdownMenuSub, +- DropdownMenuSubContent, +- DropdownMenuSubTrigger, + DropdownMenuTrigger, + } from "@/components/ui/dropdown-menu" + import { Plural, Trans } from "@lingui/react/macro" +@@ -40,7 +36,6 @@ import { useMemo } from "react" + import { formatBulkMonitorLine } from "@/components/network-monitors-table/monitor-dialog" + import { Badge } from "../ui/badge" + import { getCertDaysLeft, getCertExpiryLevel, getMonitorTarget } from "@/lib/network-monitor-utils" +-import { pb } from "@/lib/api" + + const certExpiryDotColors = { ok: "bg-green-500", warning: "bg-yellow-500", critical: "bg-red-500" } + +@@ -308,11 +303,6 @@ export function getMonitorColumns( + const isBulkAction = actionRows.length > 1 + const shouldPause = actionRows.some((monitor) => monitor.enabled) + const bulkCopyContent = actionRows.map((monitor) => formatBulkMonitorLine(monitor)).join("\n") +- const allSystems = useStore($allSystemsById) +- const otherSystems = useMemo( +- () => Object.values(allSystems).filter((s) => !isBulkAction && s.id !== row.original.system), +- [allSystems, isBulkAction] +- ) + return ( + + +@@ -357,31 +347,8 @@ export function getMonitorColumns( + }} + > + +- Bulk copy ++ Copy bulk config + +- {!isBulkAction && otherSystems.length > 0 && ( +- +- +- +- Copy to system +- +- +- {otherSystems.map((sys) => ( +- { +- const { id: _id, system: _system, ...rest } = row.original +- pb.collection("network_monitors") +- .create({ ...rest, system: sys.id }) +- .catch(() => {}) +- }} +- > +- {sys.name} +- +- ))} +- +- +- )} + + { diff --git a/tasks/henrygd__beszel-2480/tests/test.sh b/tasks/henrygd__beszel-2480/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1f04fd93a2689ef93e7f22876f6264a6e06ae4ae --- /dev/null +++ b/tasks/henrygd__beszel-2480/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 e01e2a20e9d32e46ed5eaaa4cf48cf04f56d9a9f > "$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/henrygd__beszel-2480/tests/verifier.py b/tasks/henrygd__beszel-2480/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/henrygd__beszel-2480/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/henrygd__beszel-2483/environment/Dockerfile b/tasks/henrygd__beszel-2483/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..486e37a0701acac113d3bfce52491d85cf8fd29d --- /dev/null +++ b/tasks/henrygd__beszel-2483/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/henrygd/beszel.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/henrygd/beszel.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/henrygd/beszel.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 266f45f104e901019a55eb268e183d3582dcc17b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 266f45f104e901019a55eb268e183d3582dcc17b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 266f45f104e901019a55eb268e183d3582dcc17b \ + && 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/henrygd__beszel-2483/instruction.md b/tasks/henrygd__beszel-2483/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..34a420281d13551e75c2dbe8b6ea793f2d3b6bad --- /dev/null +++ b/tasks/henrygd__beszel-2483/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** fix(ui): reject IP targets for DNS monitors + +## Description + +## 📃 Description + +A DNS monitor with an IP address as its target never sends a query, so it always succeeds and measures nothing. This happens when the resolver's IP goes in Target instead of DNS Server (#2415). The monitor dialog now catches this before saving. + +## 🪵 Changelog + +### 🔧 Fixed + +- The monitor dialog shows an inline hint under Target and disables submit when a DNS monitor's target is an IP address. +- Bulk import rejects the same case. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `266f45f104e9`. 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/henrygd__beszel-2483/solution/patch.diff b/tasks/henrygd__beszel-2483/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3f3c7270922e2d63be3f247eea8873c6ef967c38 --- /dev/null +++ b/tasks/henrygd__beszel-2483/solution/patch.diff @@ -0,0 +1,61 @@ +diff --git a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +index b57dd35a..dfe56422 100644 +--- a/internal/site/src/components/network-monitors-table/monitor-dialog.tsx ++++ b/internal/site/src/components/network-monitors-table/monitor-dialog.tsx +@@ -95,9 +95,22 @@ const NormalizedMonitorValuesSchema = v.pipe( + return Number.isInteger(input.port) && input.port >= 1 && input.port <= 65535 + }, "Port must be between 1 and 65535"), + ["port"] ++ ), ++ // Resolving an IP literal returns it without querying anything, so the check would measure nothing. ++ v.forward( ++ v.check( ++ (input) => input.protocol !== "dns" || !isIpAddress(input.target), ++ "DNS target must be a domain name; put the resolver's IP in DNS Server" ++ ), ++ ["target"] + ) + ) + ++function isIpAddress(value: string) { ++ // Hostnames never contain ":", so any colon means an IPv6 literal (optionally bracketed). ++ return /^(\d{1,3}\.){3}\d{1,3}$/.test(value) || value.includes(":") ++} ++ + // Bulk parsing only trims raw CSV fields. Inference, defaults, and protocol- + // specific validation still go through the shared normalization schema above. + const BulkMonitorSchema = v.object({ +@@ -714,6 +727,7 @@ function MonitorDialogContent({ + const { toast } = useToast() + const { t } = useLingui() + const isEditing = !!monitor ++ const dnsTargetIsIp = protocol === "dns" && isIpAddress(target.trim()) + + // When the dialog is opened, initialize form fields with monitor values (if editing) or defaults (if adding). + useEffect(() => { +@@ -827,8 +841,14 @@ function MonitorDialogContent({ + value={target} + onChange={(e) => setTarget(e.target.value)} + placeholder={protocol === "http" ? "http://localhost:8090" : protocol === "dns" ? "example.com" : "1.1.1.1"} ++ aria-invalid={dnsTargetIsIp} + required + /> ++ {dnsTargetIsIp && ( ++

++ Enter a domain name to look up. Put the resolver's IP in DNS Server. ++

++ )} +
+
+
+
+